Compare commits

..

15 Commits

Author SHA1 Message Date
Angel Capetillo Zavala df2dc7b95c Fit external CaCu donut labels within the existing charts 2026-11-30 16:06:37 -06:00
Angel Capetillo Zavala 44f3dce911 Integrate CaCu indicators, risk views and exports
Adapted from Angel Capetillo Zavala commits c0e4920 and 31400c7 and Edgar Hinojosas CaCu measures. Includes the existing 6F presentation and external donut labels.

Co-authored-by: edgar <edgar.hinojosas@uanl.edu.mx>
2026-11-30 16:02:00 -06:00
Angel Capetillo Zavala bc621f34f9 Regenerate client for CaCu exports and follow-up contracts 2026-11-30 16:01:58 -06:00
Angel Capetillo Zavala c5da898265 Regenerate API client for the existing rebuild contract 2026-11-30 15:59:46 -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
73 changed files with 6012 additions and 391 deletions
+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)];
});
}
+396 -11
View File
@@ -1,5 +1,6 @@
import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] {
@@ -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.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(`21–`)).toBeVisible();
await expect(page.getByText(/Página 2 de \d+, \d+ registros/)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
@@ -101,12 +102,18 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible();
await page.getByText('Fuente de datos · Patients').click();
await expect(page.locator('formly-form')).toBeVisible(); // drawn by hand: its raw form
// a node's caption: its kind, then its name
await page.locator('.node-caption', { hasText: 'Pacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Traducir códigos · cytology', { exact: true }).click();
await page;
await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect
.poll(() =>
@@ -139,13 +146,13 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
}) => {
const problems = watch(page);
await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('clinical_validation');
await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
});
@@ -171,7 +178,7 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.getByText('Fuente de datos · Resultados')).toBeVisible();
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it');
@@ -191,10 +198,54 @@ function captured(domain: string) {
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
const old = items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
return domain === 'cacu' ? rearranged(old) : old;
}
/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the
* opportunity section, under its cards, and the cytology distribution is a table in the joint
* results card (its nested donut is not drawn any more). Nothing else of the old page moves. */
function rearranged(old: any[]) {
const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje');
const moved = old.splice(route, 2); // its heading and its plot
old.splice(
old.findIndex((i) => i.text === 'Indicadores clínicos'),
0,
moved[0],
moved[1],
);
// the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the
// cytology section, under another title) are not headings of this page any more
return old.filter(
(i) =>
!/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test(
i.text ?? '',
),
);
}
/** Sections this platform adds to an old page, by domain, in the order they appear. The old
* headings still have to appear, in their order; nothing else may appear (a figure's own
* `h3.figure-title` inside a measure's card is the card's, not a section). */
const ADDED: Record<string, string[]> = {
cacu: [
'Resultados de citología, VPH y biopsia',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
'VPP tras colposcopía registrada',
],
};
/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */
function oldThenAdded(actual: string[], old: string[], added: string[]) {
const extra: string[] = [];
let found = 0;
for (const heading of actual) {
if (found < old.length && heading === old[found]) found++;
else extra.push(heading);
}
return { allOldInOrder: found === old.length, extra, added };
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
@@ -208,13 +259,19 @@ for (const domain of ['cacu', 'cama', 'tea']) {
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 });
// textContent: a heading inside a collapsed section (CaCu's original confirmation measure)
// is still a heading of the page, though the browser gives it no rendered text.
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
.locator('h2, h3:not(.figure-title)')
.evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
const seen = oldThenAdded(
headings.slice(from).map(period),
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
ADDED[domain] ?? [],
);
expect(seen.allOldInOrder).toBe(true);
expect(seen.extra).toEqual(seen.added);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
@@ -283,3 +340,331 @@ for (const domain of ['cacu', 'cama', 'tea']) {
).toBeVisible();
});
}
test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({
page,
}) => {
const asked: string[] = [];
page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url()));
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 });
// cumulative (the default), step by step with its warning and quartiles, and by ICD-10
// the route's times are in the opportunity section, after its cards and before the clinical ones
const opportunity = tab.locator('section.opportunity');
await expect(opportunity.locator('.route-card')).toBeVisible();
await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0);
expect(
await opportunity.evaluate((el) => {
const kpis = el.querySelector('.kpis')!;
const card = el.querySelector('.route-card')!;
return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING);
}),
).toBe(true);
await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible();
await tab.getByRole('radio', { name: 'Por pasos' }).click();
// by steps: independent bars from zero in a table, every step kept, and the medians not added
const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' });
await expect(steps).toBeVisible();
await expect(steps.locator('tbody tr')).toHaveCount(4);
await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible();
await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0);
await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click();
await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible();
await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click();
await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible();
await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible();
// the sections of the new measures: each one in the place of its subject
for (const measure of [
'CACU_VPH_GENOTIPO',
'CACU_VPH',
'CACU_BIOPSIA_RESULTADOS',
'CACU_VPP_COLPOSCOPIA',
])
await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible();
// a PPV says what it is and what it is not
await expect(
tab
.locator('[data-measure="CACU_VPP_COLPOSCOPIA"]')
.getByText('no un vínculo clínico confirmado'),
).toBeVisible();
// the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut
const joint = tab.locator('.results-card');
const [cyto, hpv, biopsy] = await Promise.all(
['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) =>
joint.locator(`section[data-measure="${m}"]`).boundingBox(),
),
);
expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2);
expect(cyto!.x).toBeLessThan(hpv!.x);
expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1);
expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8);
await expect(
joint.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(joint.getByText('Menor que LIEAG')).toBeVisible();
await expect(joint.getByText('LIEAG o más')).toBeVisible();
// three HPV categories are not listed, and the page says so only when it has such reports
const hpvRows = await joint
.locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th')
.allInnerTexts();
for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable'])
expect(hpvRows.join('|')).not.toContain(hidden);
// the cytology column reads one way at a time: the general table, or the clinical scenarios
const cytology = joint.locator('section[data-measure="CACU_EU7"]');
await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked();
await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0);
await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click();
await expect(cytology.locator('.js-plotly-plot')).toBeVisible();
await expect(cytology.getByRole('table')).toHaveCount(0);
await expect(
cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'),
).toBeVisible();
await expect(cytology.locator('.legend li')).toHaveCount(6);
await cytology.getByRole('radio', { name: 'Distribución general' }).click();
await expect(
cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(
joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'),
).toHaveCount(0);
await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0);
// the confirmation card: one perspective at a time, each with its own PPV and its readings
const confirmation = tab.locator('.confirmation-card');
await expect(
confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }),
).toBeVisible();
await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible();
await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked();
for (const [perspective, measure, title] of [
['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'],
['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'],
]) {
await confirmation.getByRole('radio', { name: perspective, exact: true }).click();
await expect(confirmation.locator('app-ppv-card')).toHaveCount(1);
const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`);
await expect(ppv.getByRole('heading', { name: title })).toBeVisible();
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
await expect(ppv.locator('.ppv-rows')).toHaveCount(0);
for (const mode of [
'Citología previa',
'VPH previo',
'Nivel de histología',
'Ronda de tamizaje',
]) {
await ppv.getByRole('radio', { name: mode, exact: true }).click();
await expect(ppv.getByRole('table', { name: mode })).toBeVisible();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0);
await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
// the score line and the methodological note stay in view in every reading
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
}
await ppv.getByRole('radio', { name: 'Total' }).click();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
}
// the biopsy requests are one more reading of the biopsy perspective, with their own heading
const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]');
await expect(
biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }),
).toBeVisible();
await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }),
).toBeVisible();
await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount(
0,
);
await expect(biopsyPpv.locator('.measure-score')).toContainText(
'solicitudes registradas (no pacientes)',
);
await expect(
biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'),
).toBeVisible();
await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible();
await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible();
await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos');
await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0);
await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }),
).toBeVisible();
// the original confirmation measure is not shown on this tab any more
await expect(confirmation.locator('details')).toHaveCount(0);
await expect(tab.getByText('medida original')).toHaveCount(0);
await expect(tab.getByText('Denominador: ')).toHaveCount(0);
// the tabs are short and the full explanation is in the tab's content
await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = confirmation.locator('app-ppv-card');
await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click();
await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas');
await expect(colposcopy.getByRole('radio')).toHaveCount(5);
const tops = await colposcopy
.locator('mat-button-toggle')
.evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size);
expect(tops).toBe(1); // one line on desktop
// the patients by HPV result: the whole as a donut, then one breakdown at a time
const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible();
await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
for (const mode of [
'Por grupo de edad',
'Por estatus de seguimiento',
'Por genotipo',
'Por tamizaje inicial o subsecuente',
]) {
await vph.getByRole('radio', { name: mode, exact: true }).click();
await expect(vph.getByRole('table', { name: mode })).toBeVisible();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(0);
await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
}
await vph.getByRole('radio', { name: 'Total' }).click();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
// the two HPV measures are told apart: reports against patients
await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText(
'Pacientes evaluadas por resultado de VPH',
);
await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText(
'Cuenta reportes, no pacientes',
);
expect(asked).toEqual([]);
});
test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const rows = page.locator('table.worklist tbody tr:not(.stage-panel)');
await expect(rows.first().locator('a')).toBeVisible();
const total = async () =>
Number(
/(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0,
);
// her age at the cut-off, and the stages: a compact line with a chevron that opens the panel
await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible();
await expect(rows.first().locator('app-stages .node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click();
const panel = page.locator('tr.stage-panel');
await expect(panel).toContainText('Toma de muestra');
await expect(panel).toContainText('Desde anterior');
await expect(panel.locator('.node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click();
await expect(panel).toHaveCount(0);
// the age filters apply before the page is cut; the name search of Rebuild is still there
const all = await total();
await page.getByLabel('Edad mínima').fill('200');
await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible();
await page.getByLabel('Edad mínima').fill('45');
await expect(async () => expect(await total()).toBeLessThan(all)).toPass();
await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible();
await page.getByRole('button', { name: 'Limpiar edades' }).click();
await expect(async () => expect(await total()).toBe(all)).toPass();
// the whole query, as the two files
const [pdf] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar PDF' }).click(),
]);
expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf');
expect(
readFileSync((await pdf.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
const [xlsx] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(),
]);
expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx');
expect(
readFileSync((await xlsx.path())!)
.subarray(0, 2)
.toString(),
).toBe('PK');
// her record: age, the detailed stages, the scales, and the file
await rows.first().locator('a').first().click();
await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:');
await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5);
await expect(page.getByText('Desde toma:').first()).toBeVisible();
await expect(page.getByText('Riesgo inmediato')).toBeVisible();
await expect(page.getByText('Riesgo a 5 años')).toBeVisible();
const [ficha] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar ficha PDF' }).click(),
]);
expect(
readFileSync((await ficha.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
expect(problems).toEqual([]);
});
/** 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([]);
});
}
+505 -13
View File
@@ -328,6 +328,88 @@
"title": "Correction",
"type": "object"
},
"Document": {
"properties": {
"columns": {
"items": {
"type": "string"
},
"maxItems": 12,
"minItems": 1,
"title": "Columns",
"type": "array"
},
"parameters": {
"items": {
"items": {
"type": "string"
},
"type": "array"
},
"maxItems": 30,
"title": "Parameters",
"type": "array"
},
"risk_scales": {
"items": {
"additionalProperties": true,
"type": "object"
},
"maxItems": 40,
"title": "Risk Scales",
"type": "array"
},
"row_stages": {
"items": {
"items": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"type": "array"
},
"maxItems": 5000,
"title": "Row Stages",
"type": "array"
},
"rows": {
"items": {
"items": {
"type": "string"
},
"type": "array"
},
"maxItems": 5000,
"title": "Rows",
"type": "array"
},
"timeline": {
"items": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"maxItems": 5,
"title": "Timeline",
"type": "array"
},
"title": {
"maxLength": 150,
"title": "Title",
"type": "string"
}
},
"required": [
"title",
"parameters",
"columns",
"rows"
],
"title": "Document",
"type": "object"
},
"Domain": {
"enum": [
"cacu",
@@ -422,6 +504,7 @@
},
"default": {},
"description": "Dato \u2192 columna, sin leer el texto.",
"keys": "field",
"title": "Datos tomados de columnas",
"type": "object"
},
@@ -455,13 +538,70 @@
"eeg"
],
"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": {
"additionalProperties": {
"type": "string"
},
"default": {},
"keys": "field",
"title": "Formatos de fecha",
"type": "object"
},
@@ -535,6 +675,7 @@
},
"default": {},
"description": "Dato \u2192 expresi\u00f3n con un grupo ( ).",
"keys": "field",
"title": "Patrones",
"type": "object"
},
@@ -595,7 +736,63 @@
"eeg"
],
"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": {
"maxLength": 40,
@@ -705,7 +902,8 @@
"url",
"oauth",
"table",
"format"
"format",
"columns"
],
"title": "Type",
"type": "string"
@@ -828,7 +1026,7 @@
"type": "string"
},
"on": {
"description": "Pares [columna izquierda, derecha].",
"description": "Columna de la primera entrada = columna de la segunda.",
"items": {
"maxItems": 2,
"minItems": 2,
@@ -1003,6 +1201,7 @@
"type": "string"
},
"description": "Dato de la plataforma \u2192 columna del sitio.",
"keys": "field",
"title": "Campos",
"type": "object"
},
@@ -1012,6 +1211,7 @@
},
"default": {},
"description": "Por ejemplo %d/%m/%Y.",
"keys": "field",
"title": "Formatos de fecha",
"type": "object"
},
@@ -1059,6 +1259,7 @@
},
"default": {},
"description": "Un dato igual para todas las filas.",
"keys": "field",
"title": "Valores fijos",
"type": "object"
}
@@ -1173,6 +1374,24 @@
"title": "Metric",
"type": "object"
},
"Model": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"title": {
"title": "Title",
"type": "string"
}
},
"required": [
"name",
"title"
],
"title": "Model",
"type": "object"
},
"Option": {
"additionalProperties": false,
"properties": {
@@ -1692,12 +1911,14 @@
"properties": {
"args": {
"additionalProperties": true,
"advanced": true,
"default": {},
"description": "Los de la fuente dlt.",
"title": "Argumentos (JSON)",
"title": "Argumentos",
"type": "object"
},
"guided": {
"advanced": true,
"anyOf": [
{
"$ref": "#/components/schemas/Guided"
@@ -1705,7 +1926,8 @@
{
"type": "null"
}
]
],
"title": "Asistente"
},
"id": {
"maxLength": 40,
@@ -1746,6 +1968,7 @@
]
},
"primary_key": {
"advanced": true,
"default": [],
"description": "Columnas que identifican una fila.",
"items": {
@@ -1755,6 +1978,7 @@
"type": "array"
},
"resource": {
"advanced": true,
"anyOf": [
{
"type": "string"
@@ -1767,12 +1991,14 @@
"title": "Recurso"
},
"source": {
"advanced": true,
"description": "M\u00f3dulo:funci\u00f3n de la fuente dlt.",
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
"title": "Fuente dlt",
"type": "string"
},
"then": {
"advanced": true,
"anyOf": [
{
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
@@ -1986,7 +2212,63 @@
"eeg"
],
"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": {
"maxLength": 40,
@@ -2590,6 +2872,75 @@
]
}
},
"/cacu/exports/capabilities": {
"get": {
"operationId": "capabilities",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {}
}
},
"description": "Successful Response"
}
},
"summary": "Capabilities",
"tags": [
"exports"
]
}
},
"/cacu/exports/{kind}": {
"post": {
"operationId": "export",
"parameters": [
{
"in": "path",
"name": "kind",
"required": true,
"schema": {
"title": "Kind",
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Document"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Export",
"tags": [
"exports"
]
}
},
"/domains": {
"get": {
"operationId": "domains",
@@ -3398,6 +3749,7 @@
},
"/models/{domain}": {
"get": {
"description": "The domain's registered models, with their names on screen.",
"operationId": "models",
"parameters": [
{
@@ -3415,7 +3767,7 @@
"application/json": {
"schema": {
"items": {
"type": "string"
"$ref": "#/components/schemas/Model"
},
"title": "Response Models",
"type": "array"
@@ -3645,7 +3997,7 @@
},
"/models/{domain}/{name}/versions/{version}/promote": {
"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",
"parameters": [
{
@@ -3707,7 +4059,7 @@
},
"/models/{domain}/{name}/versions/{version}/reports/clinical_validation": {
"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",
"parameters": [
{
@@ -4263,6 +4615,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": {
"get": {
"operationId": "studies",
@@ -4773,7 +5172,7 @@
},
"/{domain}/fhir/Condition": {
"get": {
"description": "What clinical notes diagnosed.",
"description": "What clinical notes diagnosed (CaMa: and each recurrence).",
"operationId": "search_condition",
"parameters": [
{
@@ -4859,7 +5258,7 @@
},
"/{domain}/fhir/DiagnosticReport": {
"get": {
"description": "The domain's reports (each study of the catalog with a report), as known by the last\nday with data.",
"description": "The domain's reports (each study of the catalog with a report), as known by the last\nday with data (CaCu: or by `stage-cutoff`, for the stages of each sample's route).",
"operationId": "search_diagnostic_report",
"parameters": [
{
@@ -4888,6 +5287,23 @@
"title": "Subject"
}
},
{
"in": "query",
"name": "stage-cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"title": "Stage-Cutoff"
}
},
{
"in": "query",
"name": "_count",
@@ -5443,6 +5859,82 @@
"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": "CaCu: completed years at the cut-off",
"in": "query",
"name": "follow-up-age-min",
"required": false,
"schema": {
"anyOf": [
{
"maximum": 150,
"minimum": 0,
"type": "integer"
},
{
"type": "null"
}
],
"description": "CaCu: completed years at the cut-off",
"title": "Follow-Up-Age-Min"
}
},
{
"description": "CaCu: completed years at the cut-off",
"in": "query",
"name": "follow-up-age-max",
"required": false,
"schema": {
"anyOf": [
{
"maximum": 150,
"minimum": 0,
"type": "integer"
},
{
"type": "null"
}
],
"description": "CaCu: completed years at the cut-off",
"title": "Follow-Up-Age-Max"
}
},
{
"description": "-recent or -risk-<outcome>",
"in": "query",
@@ -5610,7 +6102,7 @@
},
"/{domain}/fhir/Procedure": {
"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",
"parameters": [
{
+29
View File
@@ -0,0 +1,29 @@
/* 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 Capabilities$Params {
}
export function capabilities(http: HttpClient, rootUrl: string, params?: Capabilities$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, capabilities.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
capabilities.PATH = '/cacu/exports/capabilities';
+34
View File
@@ -0,0 +1,34 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Document } from '../../models/document';
export interface Export$Params {
kind: string;
body: Document
}
export function export$(http: HttpClient, rootUrl: string, params: Export$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, export$.PATH, 'post');
if (params) {
rb.path('kind', params.kind, {});
rb.body(params.body, 'application/json');
}
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<any>;
})
);
}
export$.PATH = '/cacu/exports/{kind}';
@@ -16,6 +16,7 @@ export interface SearchDiagnosticReport$Params {
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'stage-cutoff'?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
@@ -26,6 +27,7 @@ export function searchDiagnosticReport(http: HttpClient, rootUrl: string, params
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('stage-cutoff', params['stage-cutoff'], {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
+24
View File
@@ -24,6 +24,26 @@ export interface SearchPatient$Params {
'follow-up-cutoff'?: (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);
/**
* CaCu: completed years at the cut-off
*/
'follow-up-age-min'?: (number | null);
/**
* CaCu: completed years at the cut-off
*/
'follow-up-age-max'?: (number | null);
/**
* -recent or -risk-<outcome>
*/
@@ -56,6 +76,10 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('follow-up-age-min', params['follow-up-age-min'], {});
rb.query('follow-up-age-max', params['follow-up-age-max'], {});
rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
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 { Domain } from '../../models/domain';
import { Model } from '../../models/model';
export interface Models$Params {
domain: Domain;
}
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> {
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Model>>> {
const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
@@ -24,7 +25,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<string>>;
return r as StrictHttpResponse<Array<Model>>;
})
);
}
+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';
+6
View File
@@ -5,6 +5,10 @@ export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
export type { Capabilities$Params as Capabilities$Params } from './fn/exports/capabilities';
export { capabilities as capabilities } from './fn/exports/capabilities';
export type { Export$Params as Export$Params } from './fn/exports/export';
export { export$ as export$ } from './fn/exports/export';
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
@@ -75,6 +79,8 @@ export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unr
export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies';
export type { Study$Params as Study$Params } from './fn/eeg/study';
+2
View File
@@ -9,6 +9,7 @@ export type { Browsed } from './models/browsed';
export type { Catalog } from './models/catalog';
export type { Condition } from './models/condition';
export type { Correction } from './models/correction';
export type { Document } from './models/document';
export type { Domain } from './models/domain';
export type { Entry } from './models/entry';
export type { ErrorModel } from './models/error-model';
@@ -24,6 +25,7 @@ export type { Listing } from './models/listing';
export type { Login } from './models/login';
export type { Map } from './models/map';
export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
+18
View File
@@ -0,0 +1,18 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Document {
columns: Array<string>;
parameters: Array<Array<string>>;
risk_scales?: Array<{
[key: string]: any;
}>;
row_stages?: Array<Array<{
[key: string]: string;
}>>;
rows: Array<Array<string>>;
timeline?: Array<{
[key: string]: string;
}>;
title: string;
}
+1 -1
View File
@@ -11,5 +11,5 @@ export interface FieldSpec {
placeholder?: string;
provider?: (string | null);
required?: boolean;
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format';
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format' | 'columns';
}
+1 -1
View File
@@ -18,7 +18,7 @@ export interface Join {
label?: string;
/**
* Pares [columna izquierda, derecha].
* Columna de la primera entrada = columna de la segunda.
*/
on: Array<[string, string]>;
position?: (Position | null);
+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;
}
+5 -3
View File
@@ -4,7 +4,9 @@
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (domain(); as current) {
<span class="title">Plataforma de Indicadores</span>
<span class="title">{{
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
}}</span>
<button
mat-flat-button
class="domain"
@@ -16,7 +18,7 @@
</button>
<mat-menu #menu="matMenu">
@for (d of others(); track d) {
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a>
<a mat-menu-item [routerLink]="['/' + section(), d]">{{ labels[d] }}</a>
}
</mat-menu>
} @else {
@@ -31,7 +33,7 @@
</nav>
@if (auth.user(); as u) {
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
<mat-icon>account_circle</mat-icon> {{ u.name || u.email }}
<mat-icon>account_circle</mat-icon><span class="who-name">{{ u.name || u.email }}</span>
</button>
<mat-menu #account="matMenu">
<span class="who" mat-menu-item disabled>{{ u.email }}</span>
+38 -1
View File
@@ -21,10 +21,22 @@
.title {
flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.25rem;
font-weight: 500;
}
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain,
.sections a,
.user {
flex-shrink: 0;
white-space: nowrap;
}
.domain {
--mat-button-filled-container-color: var(--color-primary);
--mat-button-filled-label-text-color: var(--color-text);
@@ -67,10 +79,35 @@
width: clamp(155px, 15vw, 185px);
}
@media (max-width: 720px) {
@media (max-width: 1100px) {
.title {
display: none;
}
.header {
justify-content: space-between;
gap: var(--space-3);
}
.sections {
gap: var(--space-3);
}
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name {
display: none;
}
.domain {
max-width: 15rem;
}
.domain ::ng-deep .mdc-button__label {
overflow: hidden;
text-overflow: ellipsis;
}
}
@media (max-width: 720px) {
.header {
flex-wrap: wrap;
padding-block: var(--space-2);
}
}
.user {
+5 -4
View File
@@ -43,10 +43,11 @@ export class App {
),
{ initialValue: '' },
);
/** The domain of an indicator page, if this is one. */
protected readonly domain = computed(
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined,
);
/** The section and domain of a page that has one (indicators, governance): the switcher
* moves between that section's domains. */
private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
);
+62 -35
View File
@@ -73,10 +73,6 @@
</button>
</div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) {
<div class="inputs">
Entradas:
@@ -87,40 +83,71 @@
}
</div>
} @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
<p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
}
@if (guided(d); as g) {
<div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
<mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
<mat-tab label="Configuración">
@if (d.kind === 'source') {
@if (guided(d)) {
<div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
} @else {
<p class="muted">
Esta fuente no corresponde a ningún tipo del asistente. Edítela en «Avanzado» o
vuelva a conectarla con el asistente.
</p>
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con el asistente
</button>
}
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
[options]="formOptions"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
</mat-tab>
<mat-tab label="Avanzado">
<p class="hint">
Para personal técnico: el nodo completo como lo guarda la plataforma.
@if (guided(d)) {
Si cambia su fuente aquí, deja de editarse con el asistente.
}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
<mat-hint>Nombre interno: minúsculas, números y _.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full raw">
<mat-label>Nodo (JSON)</mat-label>
<textarea
matInput
rows="16"
[value]="raw(d)"
(input)="rawDraft.set($any($event.target).value)"
></textarea>
</mat-form-field>
@if (rawError()) {
<p class="error" role="alert">{{ rawError() }}</p>
}
<button mat-stroked-button [disabled]="rawDraft() === undefined" (click)="applyRaw()">
Aplicar
</button>
</div>
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)">
Avanzado (para personal técnico)
</mat-slide-toggle>
} @else if (d.kind === 'source') {
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con ayuda
</button>
}
@if (!guided(d) || advanced()) {
@if (guided(d)) {
<p class="muted">Si cambia algo aquí, la fuente deja de editarse con ayuda.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
}
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
</mat-tab>
</mat-tab-group>
<button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) {
<div class="preview">
+52
View File
@@ -140,3 +140,55 @@ h2 {
color: var(--color-success, #2e7d32);
}
}
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node {
box-sizing: border-box;
overflow: hidden;
padding: 4px 10px;
display: flex;
align-items: center;
}
:host ::ng-deep .node-caption {
min-width: 0;
width: 100%;
line-height: 1.2;
}
:host ::ng-deep .node-caption .kind {
display: block;
font-size: 10px;
color: var(--color-text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
:host ::ng-deep .node-caption .name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: 12px;
font-weight: 500;
overflow-wrap: anywhere;
}
.panel-tabs {
margin-top: var(--space-2);
}
.panel-tabs .hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: var(--space-3) 0;
}
.raw textarea {
font-family: monospace;
font-size: 12px;
}
.error {
color: var(--mat-sys-error);
font-size: 13px;
}
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3);
}
+86 -15
View File
@@ -1,5 +1,13 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core';
import {
Component,
computed,
effect,
inject,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -7,7 +15,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatDialog } from '@angular/material/dialog';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTabsModule } from '@angular/material/tabs';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
@@ -57,21 +65,21 @@ export const KINDS: Record<Kind, string> = {
read: 'Leer documentos',
route: 'Separar por tipo',
map: 'Traducir códigos',
extract: 'Sacar datos',
extract: 'Extraer datos',
fhir: 'Leer FHIR',
join: 'Juntar',
join: 'Unir',
link: 'Identificar a la persona',
target: 'Guardar en la plataforma',
};
export const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Saca el texto de cada documento (PDF, Word, escaneos con OCR).',
read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route:
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Toma de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee paquetes FHIR que un sistema envió y saca de ellos los estudios.',
join: 'Junta dos entradas que hablan de lo mismo; por ejemplo, un resultado con su orden.',
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.',
};
@@ -90,7 +98,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule,
MatInputModule,
MatListModule,
MatSlideToggleModule,
MatTabsModule,
MatTableModule,
MatTooltipModule,
Vflow,
@@ -107,8 +115,9 @@ export class Conectar {
private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP;
/** The raw form of a source drawn with the dialog ("Avanzado"). */
protected readonly advanced = signal(false);
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -132,6 +141,20 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
});
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */
@@ -264,7 +287,8 @@ export class Conectar {
);
this.form = new UntypedFormGroup({});
this.preview.set(undefined);
this.advanced.set(false);
this.rawDraft.set(undefined);
this.rawError.set('');
}
/** A source the dialog drew (its answers make its dlt fields). */
@@ -279,13 +303,46 @@ export class Conectar {
const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
);
if (this.advanced()) delete values['guided']; // drawn by hand from here on
this.update(
id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
);
}
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2);
}
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void {
const d = this.doc();
const text = this.rawDraft();
if (!d || text === undefined) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(text);
} catch {
this.rawError.set('El texto no es JSON válido.');
return;
}
if (parsed['kind'] !== d.kind) {
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
return;
}
if (d.kind === 'source') {
const dlt = ['source', 'args', 'resource', 'then'] as const;
const before = d as unknown as Record<string, unknown>;
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
delete parsed['guided'];
}
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
this.select(d.id);
}
protected rename(to: string): void {
const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
@@ -363,7 +420,7 @@ export class Conectar {
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.');
this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
} catch (e) {
this.message.set(problem(e));
}
@@ -389,7 +446,14 @@ export class Conectar {
}
function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`;
// ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
`<div class="node-caption" title="${kind} · ${name}">` +
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
);
}
/** Each node's distance from the sources: its column when it has no saved position. */
@@ -416,3 +480,10 @@ function problem(e: unknown): string {
}
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' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
on: {
type: 'array',
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
},
extra: { type: 'object', title: 'Extra' },
source: { type: 'string', advanced: true },
},
},
},
@@ -25,7 +31,7 @@ describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']);
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
expect(schema.required).toEqual(['when']);
});
@@ -34,7 +40,13 @@ describe('node forms from the pipeline schema', () => {
expect(schema.properties.resource.type).toBe('string');
});
it('edits maps as JSON', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json');
it('edits maps of texts and pairs as rows', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
});
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
expect(schema.properties.extra).toBeUndefined();
expect(schema.properties.source).toBeUndefined();
});
});
+236 -2
View File
@@ -3,6 +3,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { ReactiveFormsModule } from '@angular/forms';
import {
ConfigOption,
@@ -27,11 +28,29 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!;
const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field];
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f));
// The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
delete node.properties![field];
}
node.required = (node.required ?? []).filter(
(f) => !CANVAS_FIELDS.includes(f) && f in (node.properties ?? {}),
);
delete node.additionalProperties;
return simplify(node, defs);
}
function isJson(schema: Schema): boolean {
return (
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
'json'
);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) {
const { $ref, ...rest } = schema;
@@ -45,6 +64,34 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return simplify({ ...kept[0], ...rest }, defs);
}
}
const values = schema.additionalProperties as Schema | boolean | undefined;
if (
schema.type === 'object' &&
!schema.properties &&
typeof values === 'object' &&
values.type === 'string'
) {
const byField = (schema as { keys?: string }).keys === 'field';
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
} as Schema;
}
const pair = schema.items as Schema | undefined;
if (
schema.type === 'array' &&
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'pairs' } },
} as Schema;
}
const isMap = schema.type === 'object' && !schema.properties;
const isTuple =
schema.type === 'array' &&
@@ -117,7 +164,7 @@ export class ArrayType extends FieldArrayType {}
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: `
<mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }} (JSON)</mat-label>
<mat-label>{{ props.label }}</mat-label>
<textarea
matInput
rows="4"
@@ -152,11 +199,198 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
}
}
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
@if (props['fieldKeys']) {
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
@for (o of keyOptions(row[0]); track o[0]) {
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[value]="row[0]"
(change)="edit(i, $any($event.target).value, row[1])"
/>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
<mat-label>Valor</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
column-gap: 4px;
row-gap: 6px;
padding: 8px 0;
border-bottom: 1px solid var(--color-border);
}
.key,
.value {
min-width: 0;
grid-column: 1;
}
.row button {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
string | undefined;
const titles: Record<string, string> = entity
? (all[entity] ?? {})
: Object.assign({}, ...Object.values(all));
const options = Object.entries(titles);
if (current && !(current in titles)) options.unshift([current, current]);
return options;
}
protected rows(): [string, string][] {
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
this.formControl.markAsDirty();
}
protected edit(i: number, key: string, value: string): void {
const rows = this.rows();
rows[i] = [key.trim(), value];
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
: undefined;
let n = rows.length + 1;
while (used.has(`campo_${n}`)) n++;
this.save([...rows, [free ?? `campo_${n}`, '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Primera entrada</mat-label>
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
</mat-form-field>
<span>=</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Segunda entrada</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 6px;
}
.half {
flex: 1;
min-width: 0;
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(rows);
this.formControl.markAsDirty();
}
protected edit(i: number, side: 0 | 1, value: string): void {
const rows = this.rows();
rows[i][side] = value.trim();
this.save(rows);
}
protected add(): void {
this.save([...this.rows(), ['', '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
export const FORMLY_TYPES: ConfigOption = {
types: [
{ name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType },
{ name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
+20 -1
View File
@@ -128,6 +128,25 @@
}
</mat-form-field>
}
@case ('columns') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
multiple
[ngModel]="listed(name)"
(ngModelChange)="set(name, $event.length ? $event : null)"
[attr.data-field]="name"
placeholder="Todas"
>
@for (c of columnOptions(name); track c) {
<mat-option [value]="c">{{ c }}</mat-option>
}
</mat-select>
<mat-hint>{{
columnOptions(name).length ? f.help : 'Pulse «Probar conexión» para ver las columnas.'
}}</mat-hint>
</mat-form-field>
}
@case ('folder') {
<div class="picker">
<mat-form-field appearance="outline" class="grow">
@@ -319,7 +338,7 @@
</p>
@if (t.detail) {
<details>
<summary>Lo que respondió el sistema</summary>
<summary>Respuesta de la fuente</summary>
<pre>{{ t.detail }}</pre>
</details>
}
+10
View File
@@ -204,6 +204,16 @@ export class SourceDialog {
}
/** The tables a database listed, for its table field. */
/** 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[]) : [];
}
/** 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)])];
}
protected tables(): string[] {
return this.tableList();
}
+8
View File
@@ -134,3 +134,11 @@ export function byDeviation(zones: Site[]): Site[] {
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
);
}
/** 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',
};
+57
View File
@@ -0,0 +1,57 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
export interface ExportStage {
state: string;
provenance?: string;
label?: string;
date?: string;
prev?: string;
start?: string;
}
export interface ExportRiskScale {
label: string;
value?: number;
low?: number;
high?: number;
outcome?: string;
model?: string;
horizon?: string;
}
export interface ExportDocument {
title: string;
parameters: string[][];
columns: string[];
rows: string[][];
timeline?: ExportStage[];
row_stages?: ExportStage[][];
risk_scales?: ExportRiskScale[];
}
export async function downloadDocument(
http: HttpClient,
format: 'pdf' | 'xlsx',
doc: ExportDocument,
) {
let blob: Blob;
try {
blob = await firstValueFrom(
http.post(`/api/cacu/exports/${format}`, doc, { responseType: 'blob' }),
);
} catch (error) {
if (error instanceof HttpErrorResponse && error.error instanceof Blob) {
try {
const body = JSON.parse(await error.error.text());
if (typeof body.detail === 'string') throw new Error(body.detail);
} catch (parsed) {
if (parsed instanceof Error && !(parsed instanceof SyntaxError)) throw parsed;
}
}
throw error;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cacu-${format === 'pdf' ? 'reporte.pdf' : 'seguimiento.xlsx'}`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
}
+4 -2
View File
@@ -286,8 +286,10 @@ export function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
],
layout: {
xaxis: { title: { text: 'Meses desde el diagnóstico' } },
yaxis: { title: { text: yTitle } },
// One label per month with every curve's survival there, as percentages.
hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
},
},
};
+67 -33
View File
@@ -1,10 +1,6 @@
<section class="page">
<h1>Gobernanza de modelos</h1>
<nav class="domains" aria-label="Dominios">
@for (d of domains.value() ?? []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<h1>{{ labels[domain()] ?? domain() }}</h1>
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
<form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -17,13 +13,44 @@
name="asOf"
/>
</mat-form-field>
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button>
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button>
@if (confirming(); as c) {
<span class="confirm" role="alert">
{{
c === 'train'
? '¿Entrenar todos los modelos de este dominio ahora?'
: '¿Calcular los riesgos de todas las pacientes con los modelos en producción?'
}}
<button mat-flat-button type="button" (click)="start(c)">Sí, iniciar</button>
<button mat-button type="button" (click)="confirming.set(undefined)">Cancelar</button>
</span>
} @else {
<button
mat-flat-button
type="button"
[disabled]="running()"
(click)="confirming.set('train')"
>
Entrenar
</button>
<button
mat-stroked-button
type="button"
[disabled]="running()"
(click)="confirming.set('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
Analizar EEG
</button>
}
}
@if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span>
<span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
@if (running()) {
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
}
}
</form>
@if (message()) {
@@ -33,17 +60,19 @@
@if (models.isLoading()) {
<app-loading what="los modelos" />
} @else if (!models.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
<p class="muted empty">Sin modelos entrenados en este dominio.</p>
}
@for (m of models.value() ?? []; track m.name) {
<div class="card model">
<h2>{{ m.name }}</h2>
<h2>
{{ m.title }} <code class="muted code">{{ m.name }}</code>
</h2>
<table class="plain">
<thead>
<tr>
<th>Versión</th>
<th>Creada</th>
<th>Entrenamiento / prueba</th>
<th>Datos</th>
<th>Informes</th>
<th>Validación clínica</th>
<th></th>
@@ -59,32 +88,37 @@
}
</td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num">
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td class="nowrap">{{ sizes(v) }}</td>
<td>
@for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r
}}</a>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chosen.set({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
<div class="reports">
@for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r
}}</a>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chosen.set({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</div>
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
#file
type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
hidden
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
<button mat-stroked-button type="button" (click)="file.click()">
Subir validación clínica
</button>
} @else {
Agregada
}
@@ -105,7 +139,7 @@
@if (chosen(); as c) {
<div class="card">
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2>
<h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" />
+32 -12
View File
@@ -1,18 +1,8 @@
:host {
display: block;
}
h1 {
text-align: center;
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
.subtitle {
margin: 4px 0 var(--space-4);
}
.actions {
display: flex;
@@ -30,6 +20,7 @@ h1 {
white-space: nowrap;
}
.badge {
white-space: nowrap;
margin-left: var(--space-2);
padding: 2px 8px;
border-radius: 999px;
@@ -45,3 +36,32 @@ td a {
padding: 48px 0;
text-align: center;
}
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
}
.reports a {
margin-right: 0;
}
h2 .code {
font-size: 12px;
font-weight: 400;
margin-left: var(--space-2);
}
.confirm {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: 4px 4px 4px 12px;
border-radius: 8px;
background: var(--color-surface-warning, #fdf3dc);
}
td button {
white-space: nowrap;
}
+60 -11
View File
@@ -6,7 +6,6 @@ import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
@@ -17,9 +16,9 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import { score } from '../api/fn/models/score';
import { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status';
import type { Domain } from '../api/models/domain';
import type { Version } from '../api/models/version';
@@ -47,7 +46,6 @@ const REPORTS: Record<string, string> = {
MatButtonModule,
MatFormFieldModule,
MatInputModule,
RouterLink,
Plot,
],
templateUrl: './gobernanza.html',
@@ -60,15 +58,15 @@ export class Gobernanza {
protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly refreshed = signal(0);
protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
loader: async ({ params: { domain } }) => {
const names = await this.api.invoke(models, { domain });
const found = await this.api.invoke(models, { domain });
return Promise.all(
names.map(async (name) => ({
found.map(async ({ name, title }) => ({
name,
title,
versions: await this.api.invoke(versions, { domain, name }),
})),
);
@@ -96,7 +94,41 @@ export class Gobernanza {
});
protected readonly metricNames = METRIC_NAMES;
protected readonly asOf = signal('');
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
undefined,
);
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
protected readonly running = computed(() => {
const r = this.run();
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
});
protected readonly STATUS: Record<string, string> = {
QUEUED: 'en cola',
NOT_STARTED: 'por iniciar',
STARTING: 'iniciando',
STARTED: 'en curso',
SUCCESS: 'terminado',
FAILURE: 'con error',
CANCELING: 'deteniéndose',
CANCELED: 'detenido',
};
/** A model's title by its name, for messages. */
protected titleOf(name: string): string {
return this.models.value()?.find((m) => m.name === name)?.title ?? name;
}
/** What a version learned from, as its metrics say it (each kind of model its own). */
protected sizes(v: Version): string {
const m = v.metrics;
const n = (x: number) => x.toLocaleString('es-MX');
if (m['n_train'] !== undefined)
return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`;
if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`;
if (m['children'] !== undefined) return `${n(m['children'])} niños`;
const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox'));
if (c) return `C-index ${c[1].toFixed(3)}`;
return '—';
}
protected readonly message = signal('');
protected champion(v: Version): boolean {
@@ -117,18 +149,27 @@ export class Gobernanza {
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string },
});
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
this.refreshed.update((n) => n + 1);
}
protected async promote(name: string, version: number): Promise<void> {
try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${name} v${version} es ahora la versión en producción.`);
this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.refreshed.update((n) => n + 1);
} catch (e) {
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
this.message.set(`No se promovió: ${detail ?? 'error'}`);
// "<model> v1 has no clinical_validation, interpretability": the reports it lacks
const missing = /has no (.+)$/.exec(String(detail ?? ''))?.[1];
this.message.set(
missing
? `No se promovió: faltan informes (${missing
.split(', ')
.map((r) => this.reportNames[r] ?? r)
.join(', ')}).`
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
);
}
}
@@ -140,14 +181,22 @@ export class Gobernanza {
private async follow(run_id: string, label: string): Promise<void> {
for (;;) {
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
this.run.set({ kind: label, status });
this.run.set({ id: run_id, kind: label, status });
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
await new Promise((r) => setTimeout(r, 2000));
}
this.refreshed.update((n) => n + 1);
}
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
}
protected async start(kind: 'train' | 'score'): Promise<void> {
this.confirming.set(undefined);
const domain = this.domain() as Domain;
const { run_id } =
kind === 'train'
+157
View File
@@ -0,0 +1,157 @@
import { describe, expect, it } from 'vitest';
import {
BIOPSY_REPORTS,
CYTOLOGY_REPORTS,
distribution,
durationMax,
durationRows,
HPV_REPORTS,
icdRows,
requests,
withoutHidden,
} from './cacu-results';
import { PAGES } from './pages';
import { PPV_NOTES, Reading, STRATA, name } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: {
category: Object.fromEntries(
Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
describe('distributions of reports', () => {
it('counts HPV reports and keeps inconsistent and zero categories', () => {
const d = distribution(
report(4, { negative: 2, positive_16: 1, inconsistent: 1 }),
HPV_REPORTS,
)!;
expect(d.total).toBe(4);
expect(d.rows.map((r) => r.count)).toEqual([2, 1, 0, 0, 0, 0, 1]);
expect(d.outside).toBe(0);
});
it('leaves what the table does not list outside it and says how much is without data', () => {
const d = distribution(
report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }),
BIOPSY_REPORTS,
)!;
expect(d.total).toBe(3);
expect(d.noData).toBe(1);
expect(d.outside).toBe(2);
});
it('does not invent a report: missing, or counts that do not add up, draw nothing; zero is zero', () => {
expect(distribution(undefined, HPV_REPORTS)).toBeUndefined();
expect(distribution(report(2, { normal: 1 }), BIOPSY_REPORTS)).toBeUndefined();
expect(distribution(report(0, {}), HPV_REPORTS)).toMatchObject({
total: 0,
max: 0,
outside: 0,
});
});
});
describe('the categories a table leaves out', () => {
const hidden = ['positive_incomplete', 'inconsistent'];
it('lists the rest, keeps the total and the percentage denominator, and counts what it hides', () => {
const d = distribution(
report(10, { negative: 5, positive_16: 2, positive_incomplete: 2, inconsistent: 1 }),
HPV_REPORTS,
)!;
const v = withoutHidden(d, hidden);
expect(d.total).toBe(10);
expect(v.shown.map((r) => r.code)).not.toContain('positive_incomplete');
expect(v.shown.map((r) => r.code)).not.toContain('inconsistent');
expect(v.hiddenCount).toBe(3);
expect(v.max).toBe(5);
// nothing hidden: the rows are all of them and the count is zero (the page adds no note)
expect(withoutHidden(d).shown).toHaveLength(HPV_REPORTS.length);
expect(withoutHidden(d).hiddenCount).toBe(0);
});
it('is the page choice for HPV; cytology and biopsy keep every category', () => {
const results = PAGES['cacu'].clinical.find((s) => s.kind === 'results')!;
if (results.kind !== 'results') throw new Error('no joint card');
expect(results.hpv.hide).toEqual(hidden);
expect(results.cytology.hide).toBeUndefined();
expect(results.biopsy.hide).toBeUndefined();
expect(CYTOLOGY_REPORTS.map((r) => r[0])).toEqual([
'NILM',
'ASC-US',
'LSIL',
'ASC-H',
'HSIL',
'CIS',
]);
});
});
describe('biopsy requests', () => {
it('reads every state of the request and keeps them apart from patients', () => {
const r = requests(
report(9, { high_grade: 3, below_high_grade: 2, pending: 2, no_grade: 1, ambiguous: 1 }),
)!;
expect(r).toMatchObject({ total: 9, high: 3, below: 2, pending: 2, noGrade: 1, ambiguous: 1 });
expect(r.unclassified + r.inconsistent).toBe(0);
});
it('is none for a missing, failed or inconsistent report, and a zero total is a real zero', () => {
expect(requests(undefined)).toBeUndefined();
expect(requests({ ...report(1, { pending: 1 }), error: true })).toBeUndefined();
expect(requests(report(3, { pending: 1 }))).toBeUndefined();
expect(requests(report(0, {}))?.total).toBe(0);
});
});
describe('ICD-10 breakdown', () => {
it('lists each code with its median and quartiles, most frequent first', () => {
const r: Reading = {
populations: { 'initial-population': 3, 'measure-observation': 3 },
strata: {
diagnosis_code: {
C53: { 'measure-observation': 2 },
sin_codigo: { 'measure-observation': 1 },
},
},
stratumScores: {
diagnosis_code: {
C53: { median: 30, low: 25, high: 40 },
sin_codigo: { median: 12 },
},
},
};
expect(icdRows(r)).toEqual([
{ label: 'C53', count: 2, median: 30, low: 25, high: 40 },
{ label: 'Sin código disponible', count: 1, median: 12 },
]);
expect(icdRows(undefined)).toEqual([]);
});
});
describe('route by steps', () => {
const at = (score?: number, n = 4, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
it('keeps every step, tells absent from zero and scales from zero to the largest quartile', () => {
const rows = durationRows([
{ label: 'a', r: at(0, 3, 0, 2) },
{ label: 'b', r: at(undefined) },
{ label: 'c', r: at(13, 4, 9, 41) },
{ label: 'd', r: undefined },
]);
expect(rows.map((r) => r.label)).toEqual(['a', 'b', 'c', 'd']);
expect(rows[0]).toMatchObject({ median: 0, observations: 3, low: 0, high: 2 });
expect(rows[1].median).toBeUndefined();
expect(rows[1].observations).toBeUndefined();
expect(rows[3].median).toBeUndefined();
expect(durationMax(rows)).toBe(41);
expect(durationMax(durationRows([{ label: 'x', r: undefined }]))).toBe(0);
});
});
+167
View File
@@ -0,0 +1,167 @@
import type { Reading } from './measures';
/** One category of a distribution: its code in the report, its words and its colour. */
export type DistRow = readonly [code: string, label: string, color: string];
/** A distribution drawn as a table with a bar per category (CaCu's results of HPV and biopsy). */
export interface Distribution {
rows: { code: string; label: string; color: string; count: number }[];
/** units in the categories shown */
total: number;
/** units of the period that are in none of them */
outside: number;
max: number;
/** units the report counts as "no data" (no grade, no result) */
noData: number;
}
/** The categories of a report's `category` stratum, as counts of units. The strata must add up
* to the population: otherwise the report is not trusted and nothing is drawn. A category the
* report does not list is a zero, a missing report is not. */
export function distribution(
reading: Reading | undefined,
categories: readonly DistRow[],
): Distribution | undefined {
const cells = reading?.strata['category'];
const population = reading?.populations['initial-population'];
if (!cells || population === undefined) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (
counts.some((n) => n === undefined || !Number.isInteger(n) || n < 0) ||
counts.reduce((a, b) => a + b, 0) !== population
)
return undefined;
const rows = categories.map(([code, label, color]) => ({
code,
label,
color,
count: cells[code]?.['initial-population'] ?? 0,
}));
const total = rows.reduce((sum, row) => sum + row.count, 0);
return {
rows,
total,
outside: population - total,
max: Math.max(0, ...rows.map((row) => row.count)),
noData: cells['no_data']?.['initial-population'] ?? 0,
};
}
/** Cytology results by Bethesda category (one sample per patient, the latest valid). */
export const CYTOLOGY_REPORTS: readonly DistRow[] = [
['NILM', 'Normal', '#408651'],
['ASC-US', 'ASC-US', '#2778B8'],
['LSIL', 'LIEBG', '#B19525'],
['ASC-H', 'ASC-H', '#7955B1'],
['HSIL', 'LIEAG', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
];
/** The rows a table lists once some categories are left out of it: the total, the percentages and
* the units outside stay as the report gives them (nothing is recomputed); only the rows, the
* bars' scale and a count of what is not listed change. */
export function withoutHidden(d: Distribution, hide: readonly string[] = []) {
const shown = d.rows.filter((r) => !hide.includes(r.code));
return {
shown,
max: Math.max(0, ...shown.map((r) => r.count)),
hiddenCount: d.rows.filter((r) => hide.includes(r.code)).reduce((n, r) => n + r.count, 0),
};
}
/** HPV reports by genotype (one report per patient and sample date). */
export const HPV_REPORTS: readonly DistRow[] = [
['negative', 'Negativo', '#42a77e'],
['positive_16', 'Positivo 16 exclusivamente', '#df8640'],
['positive_18', 'Positivo 18 exclusivamente', '#c29c42'],
['positive_16_18', 'Positivo 16 y 18', '#c24269'],
['positive_other', 'Positivo sin detección de 16/18', '#a8c243'],
['positive_incomplete', 'Positivo con genotipificación incompleta', '#9c42c2'],
['inconsistent', 'No clasificable o inconsistente', '#687786'],
];
/** Biopsy reports by the grade they state. */
export const BIOPSY_REPORTS: readonly DistRow[] = [
['normal', 'Normal', '#408651'],
['LSIL', 'LIEBG (CIN 1)', '#B19525'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
['carcinoma', 'Carcinoma invasor', '#8D4C79'],
];
/** The ICD-10 codes of the diagnosis notes, each with its median and quartiles of days from the
* sample to the diagnosis (an exploratory grouping by the dates that link them). */
export function icdRows(reading: Reading | undefined) {
const scores = reading?.stratumScores?.['diagnosis_code'] ?? {};
return Object.entries(scores)
.map(([label, score]) => ({
label: label
.replace('sin_codigo', 'Sin código disponible')
.replace('ambiguo', 'Diagnóstico ambiguo'),
count: reading?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0,
...score,
}))
.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
}
/** The biopsy requests on record by their state at the cut-off; they are requests, not patients. */
export interface Requests {
total: number;
high: number;
below: number;
pending: number;
noGrade: number;
unclassified: number;
inconsistent: number;
ambiguous: number;
}
/** None when the report is missing, errored or does not add up (the page then says so). */
export function requests(reading: Reading | undefined): Requests | undefined {
const total = reading?.populations['initial-population'];
const cells = reading?.strata['category'];
if (!reading || reading.error || total === undefined || !cells) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (
!Number.isInteger(total) ||
total < 0 ||
counts.some((n) => !Number.isInteger(n) || n < 0) ||
counts.reduce((sum, n) => sum + n, 0) !== total
)
return undefined;
const of = (key: string) => cells[key]?.['initial-population'] ?? 0;
return {
total,
high: of('high_grade'),
below: of('below_high_grade'),
pending: of('pending'),
noGrade: of('no_grade'),
unclassified: of('unclassified'),
inconsistent: of('inconsistent'),
ambiguous: of('ambiguous'),
};
}
/** One row of a duration table: the median days, how many measurements and the quartiles. A
* step with no median keeps its row and says nothing (absent is not zero). */
export interface DurationRow {
label: string;
median?: number;
observations?: number;
low?: number;
high?: number;
}
export function durationRows(steps: { label: string; r: Reading | undefined }[]): DurationRow[] {
return steps.map(({ label, r }) => ({
label,
median: r?.score,
observations: r?.score === undefined ? undefined : r.populations['measure-observation'],
low: r?.score === undefined ? undefined : r.low,
high: r?.score === undefined ? undefined : r.high,
}));
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { requestsAlternate } from './confirmation';
import { Reading } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: {
category: Object.fromEntries(
Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
describe('biopsy requests as a reading of the biopsy card', () => {
it('keeps the request denominator, bars and secondary counts of the old card', () => {
const a = requestsAlternate(report(13, { high_grade: 9, below_high_grade: 4 }), true);
expect(a.score).toBe('69.2 %');
expect(a.detail).toContain('9 de 13 solicitudes registradas (no pacientes)');
expect(a.rows.map((r) => [r.label, r.numerator, r.denominator])).toEqual([
['LIEAG o más', 9, 13],
['Menor que LIEAG', 4, 13],
]);
expect(a.lines[0]).toContain('Pendientes: 0 · Sin grado: 0 · No clasificables: 0');
expect(a.note).toContain('no se pide un corte histórico (as-of)');
});
it('shows pending and ungraded requests in the denominator, not as a result', () => {
const a = requestsAlternate(
report(10, { high_grade: 2, below_high_grade: 1, pending: 4, no_grade: 2, ambiguous: 1 }),
true,
);
expect(a.rows[0].denominator).toBe(10);
expect(a.lines[0]).toContain('Pendientes: 4 · Sin grado: 2');
expect(a.lines[0]).toContain('ambiguos: 1');
});
it('tells no records (a zero) from a missing, failed or inconsistent report', () => {
expect(requestsAlternate(report(0, {}), true).message).toContain('denominador 0');
expect(requestsAlternate(report(0, {}), true).score).toBe('0 solicitudes');
expect(requestsAlternate(undefined, true).message).toContain('No disponible para este periodo');
expect(requestsAlternate(undefined, false).message).toContain('no publicada');
const failed = requestsAlternate({ ...report(1, { pending: 1 }), error: true }, true);
expect(failed.alert).toBe(true);
expect(requestsAlternate(report(5, { pending: 1 }), true).alert).toBe(true);
});
});
+73
View File
@@ -0,0 +1,73 @@
import { requests } from './cacu-results';
import { Reading } from './measures';
import { PpvAlternate } from './ppv';
/** The biopsy requests as one more reading of the biopsy PPV card. They are requests, not
* patients, and the denominator is every request on record (pending and ungraded ones too); the
* histological threshold is high grade (LIEAG or more), not the PPV's LIEBG or more. */
export function requestsAlternate(reading: Reading | undefined, published: boolean): PpvAlternate {
const base = {
label: 'Solicitudes de biopsia',
title: 'Confirmación por solicitudes de biopsia registradas',
note:
'La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones. ' +
'Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud; no se pide un corte ' +
'histórico (as-of) porque la medida no lo admite.',
caption:
'Solicitudes, no pacientes: cada barra cuenta las solicitudes con ese resultado sobre todas las solicitudes ' +
'registradas, incluidas las pendientes y las que no tienen grado.',
rows: [],
lines: [],
};
const without = (message: string, score = 'Sin dato', alert = false): PpvAlternate => ({
...base,
score,
detail: '',
message,
alert,
});
if (!published) return without('No disponible: medida no publicada por el servidor.');
if (reading?.error)
return without('No se pudo consultar las solicitudes de biopsia.', 'Sin dato', true);
if (!reading) return without('No disponible para este periodo.');
const r = requests(reading);
if (!r)
return without(
'Los datos de solicitudes recibidos están incompletos o son inconsistentes.',
'Sin dato',
true,
);
if (!r.total)
return without(
'Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).',
'0 solicitudes',
);
const share = (n: number) => (100 * n) / r.total;
return {
...base,
score: `${share(r.high).toFixed(1)} %`,
detail: `${r.high} de ${r.total} solicitudes registradas (no pacientes) con histología LIEAG o más.`,
rows: [
{
code: 'high_grade',
label: 'LIEAG o más',
color: '#CE4778',
numerator: r.high,
denominator: r.total,
percent: share(r.high),
},
{
code: 'below_high_grade',
label: 'Menor que LIEAG',
color: '#8FA7BB',
numerator: r.below,
denominator: r.total,
percent: share(r.below),
},
],
lines: [
`Pendientes: ${r.pending} · Sin grado: ${r.noGrade} · No clasificables: ${r.unclassified} · ` +
`Fechas inconsistentes: ${r.inconsistent} · Registros fusionados ambiguos: ${r.ambiguous}.`,
],
};
}
+21 -38
View File
@@ -12,38 +12,6 @@ function rgba(hex: string, alpha: number): string {
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
@@ -108,6 +76,8 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
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 : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
@@ -120,7 +90,9 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
/** A result's share inside each clinical scenario (the report's `<stratum>-category` cells):
* each bar is 100 % of the patients of that scenario with a result in the catalogue, and its
* label says how many they are. Compact: a one-line legend above and thin bars. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
@@ -133,24 +105,36 @@ export function scenarioBars(
);
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
const y = scenarios.map((s, i) => `${label(s)}<br>n = ${count(totals[i])}`);
const share = (s: string, i: number, c: string) => (totals[i] ? (100 * n(s, c)) / totals[i] : 0);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
x: scenarios.map((s, i) => share(s, i, c.code)),
customdata: scenarios.map((s) => n(s, c.code)),
text: scenarios.map((s, i) =>
share(s, i, c.code) >= 12 ? `${percent(share(s, i, c.code))} %` : '',
),
textposition: 'inside',
insidetextanchor: 'middle',
textangle: 0,
textfont: { color: '#ffffff', size: 11 },
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
bargap: 0.35,
showlegend: false, // the page draws the legend, which wraps on a narrow screen
margin: { t: 8, r: 8, b: 40, l: 8 },
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
title: { text: '% de las pacientes del escenario con resultado', font: { size: 11 } },
ticksuffix: ' %',
range: [0, 100],
range: [0, 100.5],
dtick: 25,
},
yaxis: {
type: 'category',
@@ -159,7 +143,6 @@ export function scenarioBars(
categoryarray: y,
automargin: true,
},
legend: { orientation: 'h', y: -0.25 },
},
};
}
+50 -2
View File
@@ -1,8 +1,56 @@
import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart } from './follow-up';
import '@angular/compiler';
import { describe, expect, it } from 'vitest';
import type { Patient, RiskAssessment } from 'fhir/r4';
import {
ageGroup,
currentRisk,
exactAge,
patientLabel,
patientName,
rows,
windowStart,
} from './follow-up';
import { periods } from './measures';
describe('follow-up list', () => {
it('uses synthetic FHIR names consistently and keeps the patient id as fallback', () => {
const patient: Patient = {
resourceType: 'Patient',
id: 'abcdef123456',
name: [{ text: ' Ana Ejemplo ' }],
};
const page = {
resourceType: 'Bundle' as const,
type: 'searchset' as const,
entry: [{ resource: patient, search: { mode: 'match' as const } }],
};
expect(rows(page, '2026-01-01', '2026-11-27', 5)[0].name).toBe('Ana Ejemplo');
expect(patientLabel(patient)).toBe('Ana Ejemplo');
expect(
patientName({ ...patient, name: [{ given: ['Ana', 'María'], family: 'Ejemplo' }] }),
).toBe('Ana María Ejemplo');
expect(patientLabel({ ...patient, name: [{ text: ' ' }] })).toBe('abcdef1234');
});
it('calculates completed years only from valid full dates', () => {
expect(exactAge('1980-11-23', '2026-11-22')).toBe(45);
expect(exactAge('1980-11-23', '2026-11-23')).toBe(46);
expect(exactAge('2000-02-29', '2025-02-28')).toBe(24);
expect(exactAge('2000-02', '2026-01-01')).toBeUndefined();
expect(exactAge('2001-02-29', '2026-01-01')).toBeUndefined();
expect(exactAge('2027-01-01', '2026-01-01')).toBeUndefined();
});
it('keeps a missing prediction separate from zero', () => {
const risk = (p?: number): RiskAssessment => ({
resourceType: 'RiskAssessment',
status: 'final',
subject: {},
occurrenceDateTime: '2026-01-01',
method: { coding: [{ code: 'cacu.cin2_pim' }] },
prediction: [{ probabilityDecimal: p, whenRange: { high: { value: 5 } } }],
});
expect(currentRisk([risk()], 'cin2', 5)).toBeUndefined();
expect(currentRisk([risk(0)], 'cin2', 5)).toBe(0);
});
it('starts the window the day after the same day months before (core.follow_up)', () => {
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
+51 -9
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
import { routeFacts, StageFacts } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
@@ -8,7 +9,9 @@ export interface Row {
curp?: string;
status: string;
ageGroup: string;
cytology?: { date: string; result?: string; adequacy?: string };
age?: number;
stageFacts: StageFacts;
cytology?: { date: string; reportDate?: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string };
@@ -17,6 +20,42 @@ export interface Row {
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
/** Prefer the supplied FHIR display text, then a structured name, then the next name. */
export function patientName(patient: Patient | undefined): string | undefined {
for (const name of patient?.name ?? []) {
const text = name.text?.trim();
if (text) return text;
const parts = [...(name.given ?? []), name.family ?? '']
.map((part) => part.trim())
.filter(Boolean);
if (parts.length) return parts.join(' ');
}
return undefined;
}
export function patientLabel(patient: Patient | undefined): string {
return patientName(patient) ?? patient?.id?.slice(0, 10) ?? 'No disponible';
}
/** Completed years on a full, valid calendar date; partial dates are unknown. */
export function exactAge(
birth: string | undefined,
cutoff: string | undefined,
): number | undefined {
const parse = (text?: string): [number, number, number] | undefined => {
if (!text || !/^\d{4}-\d{2}-\d{2}$/.test(text)) return undefined;
const [y, m, d] = text.split('-').map(Number);
if (y < 1 || m < 1 || m > 12 || d < 1) return undefined;
const leap = y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
if (d > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]) return undefined;
return [y, m, d];
};
const b = parse(birth),
c = parse(cutoff);
if (!b || !c || birth! > cutoff!) return undefined;
return c[0] - b[0] - (c[1] < b[1] || (c[1] === b[1] && c[2] < b[2]) ? 1 : 0);
}
const AGE_GROUPS: [number, number][] = [
[25, 34],
[35, 44],
@@ -49,7 +88,7 @@ export function currentRisk(
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) =>
(r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon)
.filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
.map((p) => ({ r, p })),
);
if (!mine.length) return undefined;
@@ -58,9 +97,7 @@ export function currentRisk(
.sort()
.at(-1);
return Math.max(
...mine
.filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal ?? 0),
...mine.filter((x) => x.r.occurrenceDateTime === latest).map((x) => x.p.probabilityDecimal!),
);
}
@@ -99,12 +136,15 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return {
patient,
name: patient.name?.[0]?.text,
name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
age: exactAge(patient.birthDate, cutoff),
stageFacts: routeFacts(last),
cytology: last && {
date: last.effectiveDateTime!,
reportDate: ext(last, 'report-date')?.valueDate,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
},
@@ -146,11 +186,12 @@ export interface CamaRow {
status: string;
priority: string;
ageGroup: string;
mammogram: { date: string; birads?: string };
/** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string };
}
const CAMA_AGE_GROUPS: [number, number][] = [
export const CAMA_AGE_GROUPS: [number, number][] = [
[40, 49],
[50, 59],
[60, 69],
@@ -186,7 +227,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1);
return {
patient,
name: patient.name?.[0]?.text,
name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
@@ -196,6 +237,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
birads: mammogram
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
: undefined,
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
},
biopsy: biopsy && {
date: reported(biopsy)!,
+77
View File
@@ -44,12 +44,17 @@ export function periodTypes(measure: Measure): PeriodType[] {
/** What one report says: its counts, its score and interval, and its strata. */
export interface Reading {
/** The server refused or failed the report (a measure that was asked for, not an empty one). */
error?: boolean;
populations: Record<string, number>;
score?: number;
low?: number;
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
/** A stratum's own score by stratifier and value: a median with its quartiles, or a
* proportion with its interval, whichever the report publishes. */
stratumScores?: Record<string, Record<string, { median: number; low?: number; high?: number }>>;
}
function counts(group: {
@@ -65,6 +70,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined;
const score = group.measureScore;
const strata: Reading['strata'] = {};
const stratumScores: NonNullable<Reading['stratumScores']> = {};
for (const s of group.stratifier ?? []) {
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
@@ -76,6 +82,18 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
counts(x),
]),
);
stratumScores[name] = Object.fromEntries(
(s.stratum ?? [])
.filter((x) => x.measureScore?.value !== undefined)
.map((x) => [
x.value?.text ?? '',
{
median: x.measureScore!.value!,
low: (ext(x.measureScore, 'q1') ?? ext(x.measureScore, 'ic-bajo'))?.valueDecimal,
high: (ext(x.measureScore, 'q3') ?? ext(x.measureScore, 'ic-alto'))?.valueDecimal,
},
]),
);
}
return {
populations: counts(group),
@@ -84,6 +102,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit,
strata,
stratumScores,
};
}
@@ -122,6 +141,17 @@ export const LABELS: Record<string, string> = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
'ASCUS+': 'Citología ASC-US o mayor',
'LSIL+': 'Citología LIEBG o mayor',
'HSIL+': 'Citología LIEAG o mayor',
'LIEBG+': 'Histología LIEBG o mayor',
'LIEAG+': 'Histología LIEAG o mayor',
initial: 'Tamizaje inicial',
subsequent: 'Tamizaje subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'Positivo para VPH 16',
hpv_18: 'Positivo para VPH 18',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
@@ -134,7 +164,43 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía',
referral_cytology: 'Citología previa asociada por fechas',
referral_hpv: 'VPH de la citología previa asociada por fechas',
histology_level: 'Nivel de histología confirmado',
screening_round: 'Tamizaje inicial o subsecuente',
result_initial: 'Resultado en tamizaje inicial',
result_subsequent: 'Resultado en tamizaje subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
hpv_initial: 'VPH en tamizaje inicial',
hpv_subsequent: 'VPH en tamizaje subsecuente',
};
/** What the referral PPVs are: the records show procedures, not issued referrals, and the
* previous cytology is linked by dates. */
export const PPV_NOTES: Record<string, { title: string; note: string }> = {
CACU_VPP_COLPOSCOPIA: {
title: 'VPP tras colposcopía registrada',
note:
'De las pacientes con colposcopía registrada en el periodo (puede inferirse de notas clínicas), ' +
'las que tienen histología LIEBG o mayor. Se muestra la citología previa más reciente en los 365 ' +
'días anteriores: es una asociación por fechas, no un vínculo clínico confirmado ni una referencia emitida.',
},
CACU_VPP_BIOPSIA: {
title: 'VPP tras biopsia registrada',
note:
'De las pacientes con biopsia reportada en el periodo, las que tienen histología LIEBG o mayor. ' +
'La citología previa es una asociación por fechas, no un vínculo clínico confirmado ni una referencia ' +
'emitida. Su denominador difiere del de las solicitudes de biopsia registradas.',
},
CACU_VPH: {
title: 'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
note:
'Una paciente por periodo, por su última muestra con resultado de VPH, aunque la citología no tenga ' +
'resultado. Es distinto de los reportes de VPH por genotipo, que cuentan reportes, no pacientes.',
},
};
export const measureTitle = (m: { name?: string; title?: string }) =>
PPV_NOTES[m.name ?? '']?.title ?? m.title ?? m.name ?? '';
export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
@@ -215,6 +281,17 @@ export function strataBars(measure: Measure, r: Reading, stratifier: string): Fi
y: cells.map(([v]) => name(v)),
x: values,
marker: { color: PALETTE[0] },
...(proportion
? {
text: cells.map(([, c]) =>
c['denominator']
? `${c['numerator'] ?? 0} de ${c['denominator']}`
: 'sin pacientes',
),
textposition: 'auto' as const,
hovertemplate: '%{y}<br>%{x:.1f} % (%{text})<extra></extra>',
}
: {}),
},
],
layout: {
+138 -68
View File
@@ -17,8 +17,56 @@ export interface Kpi {
value?: string;
note?: string;
}
/** A measure's categories as a table with a bar each; say what is counted. */
export interface DistSpec {
title: string;
measure: string;
/** what the units are, in the plural */
unit: string;
/** the categories, and which of them to head with a group line */
catalog: readonly (readonly [string, string, string])[];
groups?: { before: string; label: string; codes: string[] }[];
notes: string[];
/** categories left out of the table (their units stay in the total and the percentages) */
hide?: string[];
}
export type Section =
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] }
| {
kind: 'route';
title: string;
/** `measure`: days from the sample to the step; `stepMeasure`: days from the previous step */
steps: { label: string; measure: string; step?: string; stepMeasure?: string }[];
/** the route in three readings: cumulative, step by step, and by the ICD-10 of the diagnosis */
modes?: { icd: string };
}
/** CaCu's joint card: the cytology and HPV distributions side by side, the biopsy's below, and
* the scenario figure as a complement. */
| {
kind: 'results';
title: string;
cytology: DistSpec;
hpv: DistSpec;
biopsy: DistSpec;
complement: FigureSpec[];
}
/** A positive predictive value read one way at a time (the whole, or a stratifier). */
| {
kind: 'ppv';
measure: string;
modes: PpvMode[];
/** the heading figures when the measure is not a proportion */
summary?: (reading: Reading | undefined) => { score: string; detail: string };
}
/** The generic card of a measure: its score with numerator, denominator and interval, and its strata. */
| { kind: 'measure-card'; measure: string }
/** The histopathological confirmation: one card, two perspectives (a colposcopy and a biopsy
* PPV), the biopsy requests as one more reading of the biopsy one, and the original measure */
| {
kind: 'confirmation';
title: string;
colposcopy: { measure: string; modes: PpvMode[] };
biopsy: { measure: string; modes: PpvMode[]; requests: string };
}
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
| {
kind: 'boxes';
@@ -77,39 +125,21 @@ export interface Catalog {
faded?: string[];
}
import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results';
import { Reading } from './measures';
import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, PpvMode } from './ppv';
import { VPH_MODES, vphSummary } from './vph';
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' },
],
};
/** HPV categories the page leaves out (their reports stay in the total and the percentages). */
const HPV_HIDDEN = ['positive_incomplete', 'inconsistent'];
/** 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'],
/** The cytology results by scenario, in the page's cytology colours. */
const CYTOLOGY_SCENARIO: Catalog = {
groups: [],
categories: CYTOLOGY_REPORTS.map(([code, label, color]) => ({ code, label, color, group: '' })),
};
const CACU_DAYS = {
@@ -120,7 +150,7 @@ const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
const PENDING = 'Este indicador aún no está publicado por el catálogo institucional.';
const PENDING = 'Indicador no publicado en el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
@@ -372,58 +402,98 @@ export const PAGES: Record<string, Page> = {
...CACU_DAYS,
},
],
clinical: [
opportunity: [
{
kind: 'route',
title: 'Tiempos de la ruta del tamizaje',
modes: { icd: 'CACU_TIEMPO_DIAGNOSTICO_CIE10' },
steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
],
},
{
kind: 'figures',
title: 'Distribución de resultados citológicos',
figures: [
{
kind: 'donut',
title: 'Distribución de resultados, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
center: 'pacientes',
label: 'Resultado de citología',
measure: 'CACU_EU_TIEMPO_REPORTE',
step: 'Toma a resultado de citología',
stepMeasure: 'CACU_EU_TIEMPO_REPORTE',
},
{
label: 'Resultado de colposcopía',
measure: 'CACU_DIAS_TOMA_COLPOSCOPIA',
step: 'Del resultado de citología a la colposcopía',
stepMeasure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA',
},
{
label: 'Resultado de biopsia',
measure: 'CACU_DIAS_TOMA_BIOPSIA',
step: 'De la colposcopía al resultado de biopsia',
stepMeasure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
step: 'Del resultado de biopsia al diagnóstico',
stepMeasure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
},
],
clinical: [
{
kind: 'results',
title: 'Resultados de citología, VPH y biopsia',
cytology: {
title: 'Distribución de resultados citológicos',
measure: 'CACU_EU7',
unit: 'pacientes',
catalog: CYTOLOGY_REPORTS,
notes: [
'Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.',
],
},
hpv: {
title: 'Resultados de VPH por genotipo',
measure: 'CACU_VPH_GENOTIPO',
unit: 'reportes',
catalog: HPV_REPORTS,
hide: HPV_HIDDEN,
notes: [
'Un reporte de VPH por paciente y fecha de toma; el periodo es el de la toma. Cuenta reportes, ' +
'no pacientes: es una medida distinta de las pacientes evaluadas por resultado de VPH.',
'Los valores nulos no se cuentan como negativos.',
],
},
biopsy: {
title: 'Resultados de biopsia cervical',
measure: 'CACU_BIOPSIA_RESULTADOS',
unit: 'reportes',
catalog: BIOPSY_REPORTS,
groups: [
{ before: 'normal', label: 'Menor que LIEAG', codes: ['normal', 'LSIL'] },
{ before: 'HSIL', label: 'LIEAG o más', codes: ['HSIL', 'CIS', 'carcinoma'] },
],
notes: [
'Reportes de biopsia con histología clasificable; el periodo es el de la fecha del reporte. ' +
'Las órdenes sin reporte no están incluidas.',
],
},
complement: [
{
kind: 'scenario-bars',
title: 'TOTAL por escenario clínico, {p}',
title: 'Resultados citológicos por escenario clínico, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
catalog: CYTOLOGY_SCENARIO,
stratum: 'follow_up_status',
},
],
},
{ kind: 'ppv', measure: 'CACU_VPH', modes: VPH_MODES, summary: vphSummary },
{
kind: 'figures',
kind: 'confirmation',
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',
},
],
colposcopy: { measure: 'CACU_VPP_COLPOSCOPIA', modes: PPV_COLPOSCOPY_MODES },
biopsy: {
measure: 'CACU_VPP_BIOPSIA',
modes: PPV_BIOPSY_MODES,
requests: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
},
},
],
},
@@ -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();
}
}
+160
View File
@@ -0,0 +1,160 @@
<ng-template #heading let-text>
@if (embedded()) {
<h3 class="ppv-title">{{ text }}</h3>
} @else {
<h2 class="figure-card-title">{{ text }}</h2>
}
</ng-template>
<ng-template #bars let-rows="rows" let-label="label" let-percent="percent">
@let withInterval = hasInterval(rows);
<div class="ppv-rows" role="table" [attr.aria-label]="label">
<div class="ppv-row ppv-head" role="row" [class.with-interval]="withInterval">
<span role="columnheader">Grupo</span>
<span role="columnheader" class="ppv-axis">
<span>0 %</span><span>50 %</span><span>100 %</span>
</span>
<span role="columnheader" class="num">n/N</span>
<span role="columnheader" class="num">{{ percent ?? '%' }}</span>
@if (withInterval) {
<span role="columnheader" class="num">IC 95 %</span>
}
</div>
@for (row of rows; track row.code) {
<div class="ppv-row" role="row" [class.with-interval]="withInterval">
<span role="rowheader" class="ppv-label">{{ row.label }}</span>
<span class="ppv-track" aria-hidden="true">
<span
class="ppv-bar"
[style.width.%]="row.percent ?? 0"
[style.background]="row.color"
></span>
</span>
<span role="cell" class="num">{{ row.numerator }}/{{ row.denominator }}</span>
<span role="cell" class="num">
{{ row.percent === undefined ? '—' : fixed(row.percent) + ' %' }}
</span>
@if (withInterval) {
<span role="cell" class="num">
{{
row.low === undefined || row.high === undefined
? '—'
: fixed(row.low) + '–' + fixed(row.high) + ' %'
}}
</span>
}
</div>
}
</div>
@if (!withInterval) {
<p class="state ppv-caption">El servidor no publica el intervalo por grupo.</p>
}
</ng-template>
<ng-template #toggles>
<mat-button-toggle-group
class="ppv-modes"
aria-label="Lectura de la medida"
[value]="selected()"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.id) {
<mat-button-toggle [value]="m.id">{{ m.label }}</mat-button-toggle>
}
@if (alternate(); as a) {
<mat-button-toggle value="alternate">{{ a.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
</ng-template>
<ng-template #content>
@if (loading()) {
<ng-container *ngTemplateOutlet="heading; context: { $implicit: title() }" />
<app-loading what="la medida" [figure]="true" />
} @else if (alternate(); as a) {
@if (selected() === 'alternate') {
<ng-container *ngTemplateOutlet="heading; context: { $implicit: a.title }" />
<p class="measure-score">{{ a.score }}{{ a.detail ? ' · ' + a.detail : '' }}</p>
@if (a.note) {
<p class="state">{{ a.note }}</p>
}
<ng-container *ngTemplateOutlet="toggles" />
@if (a.message) {
<p class="state" [attr.role]="a.alert ? 'alert' : null">{{ a.message }}</p>
} @else {
<p class="state ppv-caption">{{ a.caption }}</p>
<ng-container
*ngTemplateOutlet="
bars;
context: { rows: a.rows, label: a.label, percent: a.percentLabel }
"
/>
@for (line of a.lines; track line) {
<p class="state ppv-caption">{{ line }}</p>
}
}
} @else {
<ng-container *ngTemplateOutlet="measureView" />
}
} @else {
<ng-container *ngTemplateOutlet="measureView" />
}
</ng-template>
<ng-template #measureView>
<ng-container *ngTemplateOutlet="heading; context: { $implicit: title() }" />
@if (!published()) {
<p class="state">Medida no publicada por el servidor.</p>
@if (alternate()) {
<ng-container *ngTemplateOutlet="toggles" />
}
} @else if (reading()?.error) {
<p class="state" role="alert">No se pudo consultar esta medida.</p>
@if (alternate()) {
<ng-container *ngTemplateOutlet="toggles" />
}
} @else {
<p class="measure-score">{{ score() }} · {{ detail() }}</p>
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (empty() && !alternate()) {
<p class="state">Sin pacientes en el periodo.</p>
} @else {
<ng-container *ngTemplateOutlet="toggles" />
@if (empty()) {
<p class="state">Sin pacientes en el periodo.</p>
} @else {
<p class="state ppv-caption">{{ mode().caption }}</p>
@if (!mode().stratum && !mode().rows) {
@if (donut(); as figure) {
<app-plot [figure]="figure" [height]="260" />
} @else {
<p class="state">El reporte no trae numerador y denominador consistentes.</p>
}
} @else if (rows().length) {
<ng-container
*ngTemplateOutlet="
bars;
context: { rows: rows(), label: mode().label, percent: mode().percentLabel }
"
/>
} @else {
<p class="state">Sin pacientes en esta lectura en el periodo.</p>
}
}
}
}
</ng-template>
@if (embedded()) {
<div class="ppv-embedded">
<ng-container *ngTemplateOutlet="content" />
</div>
} @else {
<mat-card appearance="outlined" class="figure-card measure-card ppv-card">
<mat-card-content>
<ng-container *ngTemplateOutlet="content" />
</mat-card-content>
</mat-card>
}
+91
View File
@@ -0,0 +1,91 @@
:host {
display: block;
}
.figure-card {
margin-top: 24px;
}
h2.figure-card-title {
font-size: 18px;
font-weight: 500;
margin: 0 0 12px;
}
.measure-score {
font-weight: 500;
margin: var(--space-2) 0;
}
.state {
color: var(--color-text-secondary);
font-size: 14px;
}
.ppv-modes {
flex-wrap: wrap;
margin: var(--space-3) 0 var(--space-2);
max-width: 100%;
}
.ppv-caption {
font-size: 13px;
margin: var(--space-2) 0;
}
.ppv-rows {
font-size: 13px;
margin-top: var(--space-2);
}
.ppv-row {
align-items: center;
display: grid;
gap: 12px;
grid-template-columns: minmax(150px, 26%) minmax(120px, 1fr) 64px 64px;
padding: 4px 0;
}
.ppv-row.with-interval {
grid-template-columns: minmax(150px, 26%) minmax(120px, 1fr) 64px 64px 110px;
}
.ppv-head {
color: var(--color-text-secondary);
font-weight: 500;
}
.ppv-axis {
display: flex;
font-weight: 400;
justify-content: space-between;
}
.ppv-label {
font-weight: 500;
min-width: 0;
}
.ppv-track {
background: #eef1f3;
background-image: linear-gradient(to right, #d8dde1 1px, transparent 1px);
background-position: 50% 0;
background-repeat: no-repeat;
display: block;
height: 16px;
}
.ppv-bar {
display: block;
height: 100%;
}
.num {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
@media (max-width: 700px) {
.ppv-row,
.ppv-row.with-interval {
grid-template-columns: 1fr 56px 56px;
}
.ppv-track,
.ppv-axis {
grid-column: 1 / -1;
order: 5;
}
}
.ppv-embedded {
display: block;
}
h3.ppv-title {
font-size: 16px;
font-weight: 500;
margin: 0 0 12px;
}
+65
View File
@@ -0,0 +1,65 @@
import { NgTemplateOutlet } from '@angular/common';
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading';
import { Plot } from '../plot';
import { Reading } from './measures';
import { ppvDonut, PpvAlternate, PpvMode, PpvRow, ppvRows } from './ppv';
/** A positive predictive value in one reading at a time: its score, numerator, denominator and
* interval and what it is and is not stay in view; the buttons choose the whole (a donut) or one
* stratifier of the report (compact bars on a common 0 to 100 % scale, n/N and percent). Every
* measure of this kind can use it by giving its modes. An `alternate` is one more button whose
* view comes from another measure and replaces the whole of the card's own (title, score, note
* and bars), so what is shown always belongs to the measure chosen. */
@Component({
selector: 'app-ppv-card',
imports: [Loading, MatButtonToggleModule, MatCardModule, NgTemplateOutlet, Plot],
templateUrl: './ppv-card.html',
styleUrl: './ppv-card.scss',
})
export class PpvCard {
readonly title = input.required<string>();
/** what the PPV is and is not (never hidden) */
readonly note = input<string>();
/** the score line: "20.0 %" and "3 de 15 pacientes. IC 95 %: …" */
readonly score = input.required<string>();
readonly detail = input.required<string>();
readonly reading = input<Reading>();
readonly loading = input(false);
readonly published = input(true);
readonly modes = input.required<PpvMode[]>();
/** the donut's name for those who confirm */
readonly confirmed = input('Con histología LIEBG o mayor');
/** inside another card: no card of its own, and a smaller title */
readonly embedded = input(false);
/** one more reading, from another measure */
readonly alternate = input<PpvAlternate>();
protected readonly chosen = signal<string | undefined>(undefined);
protected readonly selected = computed(() =>
this.chosen() === 'alternate' && this.alternate() ? 'alternate' : this.mode().id,
);
protected readonly mode = computed(
() => this.modes().find((m) => m.id === this.chosen()) ?? this.modes()[0],
);
protected readonly donut = computed(() => {
const figure = this.mode().figure;
return figure ? figure(this.reading()) : ppvDonut(this.reading(), this.confirmed());
});
protected readonly rows = computed(() => {
const { rows, stratum } = this.mode();
if (rows) return rows(this.reading());
return stratum ? ppvRows(this.reading(), stratum) : [];
});
protected hasInterval(rows: PpvRow[]): boolean {
return rows.some((r) => r.low !== undefined);
}
/** No patients: a PPV's denominator, or a cohort's population. */
protected readonly empty = computed(() => {
const p = this.reading()?.populations ?? {};
return !(p['denominator'] ?? p['initial-population'] ?? 0);
});
protected readonly fixed = (n: number) => n.toFixed(1);
}
+92
View File
@@ -0,0 +1,92 @@
import { describe, expect, it } from 'vitest';
import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, ppvDonut, ppvRows } from './ppv';
import { Reading } from './measures';
const cell = (numerator: number, denominator: number) => ({
'initial-population': denominator,
numerator,
denominator,
});
const report = (strata: Reading['strata'], numerator = 3, denominator = 15): Reading => ({
populations: { 'initial-population': denominator, numerator, denominator },
score: numerator / denominator,
strata,
});
describe('PPV by group', () => {
it('lists the groups in the page order with n/N and percent, and neutral for no data', () => {
const rows = ppvRows(
report({
referral_cytology: {
no_data: cell(1, 4),
'HSIL+': cell(2, 2),
'ASCUS+': cell(2, 8),
},
}),
'referral_cytology',
);
expect(rows.map((r) => r.code)).toEqual(['ASCUS+', 'HSIL+', 'no_data']);
expect(rows[0]).toMatchObject({ numerator: 2, denominator: 8, percent: 25 });
expect(rows[1].percent).toBe(100);
expect(rows[2].color).toBe('#C9CDD2');
// the colours are the cytology ones of the rest of the page
expect(rows[0].color).toBe('#2778B8');
expect(rows[1].color).toBe('#CE4778');
});
it('keeps a group without patients as no rate (not 0 %) and never invents an absent group', () => {
const rows = ppvRows(
report({ histology_level: { 'LIEBG+': cell(0, 0), 'LIEAG+': cell(0, 4) } }),
'histology_level',
);
expect(rows.map((r) => r.code)).toEqual(['LIEBG+', 'LIEAG+']);
expect(rows[0].percent).toBeUndefined();
expect(rows[1].percent).toBe(0);
expect(ppvRows(report({}), 'screening_round')).toEqual([]);
expect(ppvRows(undefined, 'screening_round')).toEqual([]);
});
it('leaves out a cell that does not add up instead of correcting it', () => {
const rows = ppvRows(
report({ screening_round: { initial: cell(5, 4), subsequent: cell(1, 2) } }),
'screening_round',
);
expect(rows.map((r) => r.code)).toEqual(['subsequent']);
});
it('shows an interval only when the report publishes it for the group', () => {
const r = report({ referral_hpv: { negative: cell(1, 5), positive: cell(2, 4) } });
r.stratumScores = { referral_hpv: { positive: { median: 0.5, low: 0.15, high: 0.85 } } };
const rows = ppvRows(r, 'referral_hpv');
expect(rows[0].low).toBeUndefined();
expect(rows[1].low).toBeCloseTo(15);
expect(rows[1].high).toBeCloseTo(85);
});
it('draws the whole as a donut of those who confirm and the rest, and nothing when it is not whole', () => {
const fig = ppvDonut(report({}), 'Con histología LIEBG o mayor')!;
expect((fig.data[0] as { values: number[] }).values).toEqual([3, 12]);
expect(ppvDonut(report({}, 3, 0), 'x')).toBeUndefined();
expect(ppvDonut(undefined, 'x')).toBeUndefined();
});
it('declares the five readings of the colposcopy PPV, total first, and says which overlap', () => {
expect(PPV_COLPOSCOPY_MODES.map((m) => m.stratum)).toEqual([
undefined,
'referral_cytology',
'referral_hpv',
'histology_level',
'screening_round',
]);
for (const id of ['cytology', 'hpv', 'histology'])
expect(PPV_COLPOSCOPY_MODES.find((m) => m.id === id)!.caption).toMatch(
/traslapan|excluyentes/,
);
});
it('gives the biopsy PPV the same readings with its own denominator', () => {
expect(PPV_BIOPSY_MODES.map((m) => m.id)).toEqual(PPV_COLPOSCOPY_MODES.map((m) => m.id));
expect(PPV_BIOPSY_MODES[0].caption).toContain('con biopsia reportada');
expect(PPV_COLPOSCOPY_MODES[0].caption).toContain('con colposcopía registrada');
expect(PPV_BIOPSY_MODES[1].caption).toBe(PPV_COLPOSCOPY_MODES[1].caption);
});
});
+198
View File
@@ -0,0 +1,198 @@
import type { Figure } from '../plot';
import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results';
import { name, Reading } from './measures';
/** One way to read a positive predictive value: the whole, or a stratifier of the report. */
export interface PpvMode {
id: string;
label: string;
/** the report's stratifier (none: the whole, shown as a donut) */
stratum?: string;
/** what the groups are, and whether they overlap, said under the bars */
caption: string;
/** the bars when they do not come from a stratifier of the report as a PPV's do */
rows?: (reading: Reading | undefined) => PpvRow[];
/** the whole's figure when it is not the PPV donut */
figure?: (reading: Reading | undefined) => Figure | undefined;
/** the header of the percent column (default "%") */
percentLabel?: string;
}
/** One bar: the patients that confirm (or are positive) over the patients of the group, as the
* report counts them. */
export interface PpvRow {
code: string;
label: string;
color: string;
numerator: number;
denominator: number;
/** none when the group has no patients (a zero rate is not the same) */
percent?: number;
/** the interval, only when the report publishes it for the group (percent) */
low?: number;
high?: number;
}
const NEUTRAL = '#C9CDD2';
const NEUTRAL_DARK = '#9AA3AB';
/** The colour a category has elsewhere on the page (cytology, HPV, histology), by its code there. */
const of = (rows: readonly (readonly [string, string, string])[], code: string) =>
rows.find((r) => r[0] === code)![2];
/** Colours and order of each stratifier's groups: the page's own for cytology, HPV and
* histology; steel tones for the screening round; neutral for "no data". Colours name a
* category, they are not thresholds. */
const GROUPS: Record<string, [code: string, color: string][]> = {
referral_cytology: [
['ASCUS+', of(CYTOLOGY_REPORTS, 'ASC-US')],
['LSIL+', of(CYTOLOGY_REPORTS, 'LSIL')],
['HSIL+', of(CYTOLOGY_REPORTS, 'HSIL')],
['no_data', NEUTRAL],
],
referral_hpv: [
['negative', of(HPV_REPORTS, 'negative')],
['positive', of(HPV_REPORTS, 'positive_other')],
['hpv_16', of(HPV_REPORTS, 'positive_16')],
['hpv_18', of(HPV_REPORTS, 'positive_18')],
['no_data', NEUTRAL],
],
histology_level: [
['LIEBG+', of(BIOPSY_REPORTS, 'LSIL')],
['LIEAG+', of(BIOPSY_REPORTS, 'HSIL')],
['invasive', of(BIOPSY_REPORTS, 'carcinoma')],
],
screening_round: [
['initial', '#5F7F9A'],
['subsequent', '#8FA7BB'],
['no_data', NEUTRAL],
],
};
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** A stratifier's groups as bars, in the page's order. A group the report does not list is not
* drawn (it is not a zero); a cell that is not whole counts, or whose numerator exceeds its
* denominator, is left out rather than corrected. */
export function ppvRows(reading: Reading | undefined, stratum: string): PpvRow[] {
const cells = reading?.strata[stratum];
if (!cells) return [];
const order = GROUPS[stratum] ?? [];
const known = order.map(([code]) => code);
const codes = [
...known.filter((c) => c in cells),
...Object.keys(cells).filter((c) => !known.includes(c)),
];
return codes.flatMap((code) => {
const { numerator, denominator } = cells[code];
if (!whole(numerator) || !whole(denominator) || numerator > denominator) return [];
const score = reading?.stratumScores?.[stratum]?.[code];
return [
{
code,
label: name(code),
color: order.find(([c]) => c === code)?.[1] ?? NEUTRAL_DARK,
numerator,
denominator,
percent: denominator ? (100 * numerator) / denominator : undefined,
...(score?.low !== undefined && score.high !== undefined
? { low: 100 * score.low, high: 100 * score.high }
: {}),
},
];
});
}
/** The whole PPV as a donut: those who confirm, and the rest in a neutral tone. */
export function ppvDonut(reading: Reading | undefined, confirmed: string): Figure | undefined {
const { numerator, denominator } = reading?.populations ?? {};
if (!whole(numerator) || !whole(denominator) || !denominator || numerator > denominator)
return undefined;
return {
data: [
{
type: 'pie',
hole: 0.62,
labels: [confirmed, 'Resto'],
values: [numerator, denominator - numerator],
sort: false,
direction: 'clockwise',
textinfo: 'value+percent',
textposition: 'outside',
marker: { colors: ['#6A8000', NEUTRAL] },
},
],
layout: {
height: 260,
showlegend: true,
margin: { t: 16, r: 8, b: 16, l: 8 },
legend: { orientation: 'h' },
},
};
}
/** The readings of a referral PPV (the colposcopy's and the biopsy's publish the same four
* stratifiers). The groups of cytology and histology are cumulative and overlap; the HPV ones
* overlap too (a genotype is also a positive); the rounds do not. `patients` says whose the
* denominator is. */
const ppvModes = (patients: string): PpvMode[] => [
{
id: 'total',
label: 'Total',
caption: `Pacientes con histología LIEBG o mayor sobre las pacientes ${patients} en el periodo.`,
},
{
id: 'cytology',
label: 'Citología previa',
stratum: 'referral_cytology',
caption:
'Por citología previa asociada por fechas: es una asociación por fechas, no un vínculo clínico. ' +
'Cada grupo incluye su categoría y las más severas, así que los grupos se traslapan y no son excluyentes. ' +
'«Sin dato»: sin citología previa asociada en los 365 días anteriores.',
},
{
id: 'hpv',
label: 'VPH previo',
stratum: 'referral_hpv',
caption:
'Por VPH de la citología previa asociada por fechas (asociación por fechas, no vínculo clínico). ' +
'Los grupos se traslapan: «Positivo» incluye a quienes son positivas para VPH 16 o 18, y una paciente puede estar en ambos genotipos. ' +
'«Sin dato»: sin resultado de VPH o sin citología previa asociada.',
},
{
id: 'histology',
label: 'Nivel de histología',
stratum: 'histology_level',
caption:
'Por nivel de histología confirmado. ' +
'Tres numeradores distintos sobre el mismo denominador (no son categorías excluyentes): cada nivel incluye los más severos.',
},
{
id: 'round',
label: 'Ronda de tamizaje',
stratum: 'screening_round',
caption:
'Por tamizaje inicial o subsecuente. ' +
'Cada paciente está en un solo grupo. «Sin dato»: sin clasificación de tamizaje inicial o subsecuente.',
},
];
export const PPV_COLPOSCOPY_MODES = ppvModes('con colposcopía registrada');
export const PPV_BIOPSY_MODES = ppvModes('con biopsia reportada');
/** One more reading of a PPV card that comes from another measure (the biopsy requests): it
* brings its own title, heading figures, note and bars, and replaces the card's own while chosen. */
export interface PpvAlternate {
label: string;
title: string;
score: string;
detail: string;
note?: string;
caption: string;
rows: PpvRow[];
/** secondary counts, one per line */
lines: string[];
/** instead of the bars: why there are none (not published, failed, no records) */
message?: string;
alert?: boolean;
percentLabel?: string;
}
+421 -11
View File
@@ -34,7 +34,7 @@
@if (reports.error()) {
<div class="load-error" role="alert">
<p>No se pudieron leer los indicadores del periodo. Vuelve a intentar.</p>
<p>No se obtuvieron los indicadores del periodo.</p>
<button mat-stroked-button (click)="reports.reload()">Reintentar</button>
</div>
}
@@ -53,7 +53,13 @@
@if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" />
} @else {
<div class="kpi-value" [class.pending]="!k.measure">{{ kpiValue(k) }}</div>
<div class="kpi-value" [class.pending]="!k.measure">
@let v = kpiParts(kpiValue(k));
{{ v[0] }}
@if (v[1]) {
<span class="kpi-qualifier">{{ v[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div>
}
</mat-card-content>
@@ -77,16 +83,414 @@
</section>
}
<ng-template #routeTable let-rows let-title="title" let-first="first">
<table class="distribution route-table" [attr.aria-label]="title">
<thead>
<tr>
<th>{{ first }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
@if (row.median !== undefined) {
<span class="bar-track duration-track" aria-hidden="true">
<span
class="bar"
[style.width.%]="routeMax(rows) ? (100 * row.median) / routeMax(rows) : 0"
></span>
@if (row.low !== undefined && row.high !== undefined) {
<span
class="quartile"
[style.left.%]="routeMax(rows) ? (100 * row.low) / routeMax(rows) : 0"
></span>
<span
class="quartile"
[style.left.%]="routeMax(rows) ? (100 * row.high) / routeMax(rows) : 0"
></span>
}
</span>
} @else {
<span class="no-data">Sin mediciones en el periodo</span>
}
</th>
<td>{{ row.median === undefined ? '—' : row.median + ' días' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{ row.low === undefined || row.high === undefined ? '—' : row.low + '–' + row.high }}
</td>
</tr>
}
</tbody>
</table>
</ng-template>
<ng-template #distBlock let-spec let-untitled="untitled">
@if (!untitled) {
<h3 class="dist-title">{{ spec.title }}</h3>
}
@for (note of spec.notes; track note) {
<p class="state">{{ note }}</p>
}
@if (reports.isLoading()) {
<app-loading what="la distribución" [figure]="true" />
} @else if (distOf(spec); as d) {
<p class="state">
{{ d.total }} {{ spec.unit }} en las categorías de la distribución
@if (d.outside) {
· {{ d.outside }} fuera de ellas
}
@if (d.noData) {
· {{ d.noData }} sin dato
}
· escala de las barras de 0 a {{ d.max }}.
</p>
@if (d.hiddenCount) {
<p class="state hidden-note">
Categorías que esta vista no desglosa (genotipificación incompleta, indeterminado o no
clasificable). Total en ellas: {{ d.hiddenCount }} ({{ spec.unit }}), incluido en el total
y en los porcentajes.
</p>
}
@if (!d.total) {
<p class="state">Sin {{ spec.unit }} en el periodo (cero registros, no falta de datos).</p>
}
<table class="distribution" [attr.aria-label]="spec.title">
<thead>
<tr>
<th>Categoría</th>
<th>{{ spec.unit }}</th>
<th>%</th>
</tr>
</thead>
<tbody>
@for (item of d.items; track $index) {
@if (item.kind === 'group') {
<tr class="group">
<th scope="rowgroup" colspan="3">{{ item.label }} · {{ item.count }}</th>
</tr>
} @else {
<tr>
<th scope="row">
<span class="distribution-label">{{ item.label }}</span>
<span class="bar-track" aria-hidden="true">
<span
class="bar"
[style.width.%]="d.max ? (100 * item.count) / d.max : 0"
[style.background]="item.color"
></span>
</span>
</th>
<td>{{ item.count }}</td>
<td>{{ d.total ? ((100 * item.count) / d.total).toFixed(1) + ' %' : '—' }}</td>
</tr>
}
}
</tbody>
</table>
} @else if (rd(spec.measure)?.error) {
<p class="state" role="alert">No se pudo consultar esta medida.</p>
} @else {
<p class="state">
Distribución no disponible para este periodo (la medida no está publicada o su reporte no es
consistente).
</p>
}
</ng-template>
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('route') {
<h3 class="route-title">{{ section.title }}</h3>
@if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" />
} @else if (routeOf(section); as fig) {
<app-plot [figure]="fig" [height]="300" />
} @else {
<p class="state">Sin tiempos publicados en el periodo.</p>
<mat-card appearance="outlined" class="route-card">
<mat-card-content>
<div class="route-head">
<h3 class="route-title">{{ section.title }}</h3>
@if (section.modes) {
<mat-button-toggle-group
class="route-toggle"
aria-label="Lectura de la ruta del tamizaje"
[value]="routeMode()"
(change)="routeMode.set($event.value)"
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="icd10">Desglose por CIE-10</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" />
} @else if (!section.modes || routeMode() === 'sample') {
@let rows = stepRows(section, 'sample');
@if (rows.some((r) => r.median !== undefined)) {
<p class="state">
Mediana desde la toma de muestra hasta cada etapa. Escala: 0 a
{{ routeMax(rows) }} días. Las marcas indican el primer y tercer cuartil.
</p>
<ng-container
*ngTemplateOutlet="
routeTable;
context: {
$implicit: rows,
title: 'Tiempos de la ruta del tamizaje',
first: 'Etapa',
}
"
/>
} @else {
<p class="state">Sin tiempos publicados en el periodo.</p>
}
} @else if (routeMode() === 'step') {
@let rows = stepRows(section, 'step');
@if (rows.some((r) => r.median !== undefined)) {
<p class="state">
Cada barra es la mediana del tramo, desde cero y por separado; las marcas indican
el primer y tercer cuartil. Escala: 0 a {{ routeMax(rows) }} días. Los tramos
pueden corresponder a poblaciones diferentes, por lo que las medianas no se suman.
</p>
<ng-container
*ngTemplateOutlet="
routeTable;
context: {
$implicit: rows,
title: 'Tiempos por tramo de la ruta del tamizaje',
first: 'Tramo',
}
"
/>
} @else {
<p class="state">Sin tiempos por tramo publicados en el periodo.</p>
}
} @else {
@if (icdOf(section); as icd) {
<p class="state">
Desglose exploratorio basado en la asociación temporal existente entre la toma y
la nota de diagnóstico; no confirma un vínculo clínico.
</p>
@if (icd.reading?.error) {
<p class="state" role="alert">No se pudo consultar el desglose por CIE-10.</p>
} @else if (!icd.reading) {
<p class="state">Desglose no disponible en este servidor o periodo.</p>
} @else {
@let max = icdMax(icd.rows);
<p class="state">
{{ icd.reading.populations['measure-observation'] ?? 0 }} mediciones; escala de
0 a {{ max }} días.
</p>
<table
class="distribution route-table"
aria-label="Tiempo a diagnóstico por CIE-10"
>
<thead>
<tr>
<th>CIE-10 y descripción</th>
<th>Mediana</th>
<th>Mediciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of icd.rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
<span class="bar-track duration-track" aria-hidden="true">
<span
class="bar"
[style.width.%]="max ? (100 * row.median) / max : 0"
></span>
<span
class="quartile"
[style.left.%]="max ? (100 * (row.low ?? 0)) / max : 0"
></span>
<span
class="quartile"
[style.left.%]="max ? (100 * (row.high ?? 0)) / max : 0"
></span>
</span>
</th>
<td>{{ row.median }} días</td>
<td>{{ row.count }}</td>
<td>{{ row.low }}–{{ row.high }}</td>
</tr>
} @empty {
<tr>
<td colspan="4">Sin observaciones con código CIE-10 en el periodo.</td>
</tr>
}
</tbody>
</table>
}
}
}
</mat-card-content>
</mat-card>
}
@case ('results') {
<mat-card appearance="outlined" class="figure-card results-card">
<mat-card-content>
<h2 class="figure-card-title">{{ section.title }}</h2>
<div class="results-grid">
<section [attr.data-measure]="section.cytology.measure" class="cytology">
<h3 class="dist-title">{{ section.cytology.title }}</h3>
<mat-button-toggle-group
class="cytology-views"
aria-label="Lectura de los resultados citológicos"
[value]="cytologyView()"
(change)="cytologyView.set($event.value)"
>
<mat-button-toggle value="general">Distribución general</mat-button-toggle>
<mat-button-toggle value="scenario">Por escenario clínico</mat-button-toggle>
</mat-button-toggle-group>
@if (cytologyView() === 'general') {
<ng-container
*ngTemplateOutlet="
distBlock;
context: { $implicit: section.cytology, untitled: true }
"
/>
} @else {
@for (f of section.complement; track f.title) {
<div class="complement" [attr.data-figure]="f.kind">
<p class="state">
Los mismos resultados de la distribución citológica, según el estatus de
seguimiento de cada paciente al inicio del periodo; cada barra suma 100 % de
sus pacientes con resultado (n indica cuántas son).
</p>
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) {
@if (scenarioLegend(f); as legend) {
<ul class="legend" aria-label="Resultados citológicos">
@for (item of legend; track item.label) {
<li>
<span class="swatch" [style.background]="item.color"></span>
{{ item.label }}
</li>
}
</ul>
}
<app-plot [figure]="fig" [height]="scenarioHeight(fig)" />
} @else {
<p class="state">Sin pacientes con resultado en el periodo.</p>
}
</div>
}
}
</section>
<section [attr.data-measure]="section.hpv.measure">
<ng-container *ngTemplateOutlet="distBlock; context: { $implicit: section.hpv }" />
</section>
<section class="biopsy" [attr.data-measure]="section.biopsy.measure">
<ng-container
*ngTemplateOutlet="distBlock; context: { $implicit: section.biopsy }"
/>
</section>
</div>
</mat-card-content>
</mat-card>
}
@case ('confirmation') {
@if (confirmOf(section); as c) {
<mat-card appearance="outlined" class="figure-card confirmation-card">
<mat-card-content>
<h2 class="figure-card-title">{{ section.title }}</h2>
<p class="state confirmation-note">
No son tasas de referencias emitidas: cuentan procedimientos registrados
(colposcopía o biopsia) o solicitudes de biopsia registradas, y la citología previa
se asocia por fechas. Cada lectura tiene su propio denominador y su umbral
histológico.
</p>
<mat-button-toggle-group
class="confirmation-views"
aria-label="Perspectiva de la confirmación histopatológica"
[value]="confirmView()"
(change)="confirmView.set($event.value)"
>
<mat-button-toggle value="colposcopy">Colposcopía</mat-button-toggle>
<mat-button-toggle value="biopsy">Biopsia</mat-button-toggle>
</mat-button-toggle-group>
@if (confirmView() === 'colposcopy') {
<app-ppv-card
[embedded]="true"
[attr.data-measure]="section.colposcopy.measure"
[title]="c.colposcopy.title"
[note]="c.colposcopy.note"
[score]="c.colposcopy.score"
[detail]="c.colposcopy.detail"
[reading]="c.colposcopy.reading"
[loading]="reports.isLoading()"
[published]="c.colposcopy.published"
[modes]="section.colposcopy.modes"
/>
} @else {
<app-ppv-card
[embedded]="true"
[attr.data-measure]="section.biopsy.measure"
[title]="c.biopsy.title"
[note]="c.biopsy.note"
[score]="c.biopsy.score"
[detail]="c.biopsy.detail"
[reading]="c.biopsy.reading"
[loading]="reports.isLoading()"
[published]="c.biopsy.published"
[modes]="section.biopsy.modes"
[alternate]="c.requests"
/>
}
</mat-card-content>
</mat-card>
}
}
@case ('ppv') {
@if (cardOf(section); as c) {
<app-ppv-card
[attr.data-measure]="section.measure"
[title]="c.title"
[note]="c.note"
[score]="c.score"
[detail]="c.detail"
[reading]="c.reading"
[loading]="reports.isLoading()"
[published]="c.published"
[modes]="section.modes"
/>
}
}
@case ('measure-card') {
@if (cardOf(section); as c) {
<mat-card
appearance="outlined"
class="figure-card measure-card"
[attr.data-measure]="section.measure"
>
<mat-card-content>
<h2 class="figure-card-title">{{ c.title }}</h2>
@if (reports.isLoading()) {
<app-loading what="la medida" [figure]="true" />
} @else if (!c.published) {
<p class="state">Medida no publicada por el servidor.</p>
} @else if (c.reading?.error) {
<p class="state" role="alert">No se pudo consultar esta medida.</p>
} @else {
<p class="measure-score">{{ c.score }} · {{ c.detail }}</p>
@if (c.note) {
<p class="state">{{ c.note }}</p>
}
@for (f of c.figures; track f.title) {
<h3 class="figure-title">{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="260" />
} @empty {
<p class="state">Sin pacientes en el periodo.</p>
}
}
</mat-card-content>
</mat-card>
}
}
@case ('tea-summary') {
@@ -152,7 +556,7 @@
<mat-card-content>
<h2 class="box-title">{{ b.title }}</h2>
@if (!b.measure) {
<p class="state"><strong>Integración pendiente.</strong> {{ pending }}</p>
<p class="state">{{ pending }}</p>
<div class="empty-figure">Sin datos publicados</div>
} @else {
<p class="state">Filtro general aplicado: {{ period }}</p>
@@ -177,7 +581,13 @@
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
<mat-card-content>
<h3 class="kpi-title">{{ section.title }}</h3>
<div class="kpi-value">{{ kpiValue(section) }}</div>
<div class="kpi-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>
</mat-card-content>
</mat-card>
+171
View File
@@ -61,6 +61,14 @@ h2 {
font-size: 2rem;
font-weight: 500;
margin: var(--space-2) 0;
line-height: 1.15;
}
.kpi-qualifier {
display: block;
font-size: 14px;
font-weight: 400;
color: var(--color-text-secondary);
}
.kpi-detail {
@@ -297,3 +305,166 @@ h2.box-subtitle {
margin: 0;
}
}
.route-head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
.route-toggle {
flex-wrap: wrap;
max-width: 100%;
}
.route-values summary {
color: var(--color-text-secondary);
cursor: pointer;
padding: var(--space-2) 0;
}
.route-table td {
font-variant-numeric: tabular-nums;
}
.duration-track {
position: relative;
}
.duration-track .bar {
background: #42a77e;
}
.quartile {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.distribution {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
.distribution th {
font-weight: 500;
text-align: left;
}
.distribution td,
.distribution thead th:not(:first-child) {
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.distribution tbody th {
padding: 5px 0;
}
.distribution .group th {
background: #edf2f4;
font-weight: 600;
padding: 6px 8px;
}
.bar-track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
}
.bar {
display: block;
height: 100%;
}
.results-grid .distribution tbody th:has(.distribution-label) {
align-items: center;
display: flex;
gap: 10px;
}
.results-grid .distribution-label {
flex: 0 1 45%;
min-width: 0;
}
.results-grid .bar-track {
flex: 1;
height: 16px;
margin: 0;
min-width: 40px;
}
.measure-score {
font-weight: 500;
margin: var(--space-2) 0;
}
.route-card {
margin-top: 24px;
}
.route-card h3.route-title {
margin-top: 0;
}
.results-grid {
display: grid;
gap: 24px;
grid-template-columns: 1fr;
section {
min-width: 0;
}
p {
font-size: 13px;
margin: var(--space-2) 0;
}
}
h3.dist-title {
font-size: 16px;
font-weight: 500;
margin: var(--space-3) 0;
}
.results-grid .distribution td {
padding-left: 8px;
}
@media (min-width: 850px) {
.results-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.results-grid .biopsy {
grid-column: 1 / -1;
}
}
.hidden-note {
border-left: 3px solid var(--color-border);
padding-left: 8px;
}
.complement {
margin-top: var(--space-2);
}
.no-data {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
.cytology-views {
flex-wrap: wrap;
margin: var(--space-2) 0 var(--space-3);
max-width: 100%;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 14px;
list-style: none;
margin: var(--space-2) 0;
padding: 0;
}
.swatch {
display: inline-block;
height: 10px;
margin-right: 5px;
width: 10px;
}
.confirmation-views {
flex-wrap: wrap;
margin: var(--space-2) 0 var(--space-3);
max-width: 100%;
}
.confirmation-note {
font-size: 13px;
}
+117 -13
View File
@@ -9,6 +9,7 @@ import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import { distribution, durationMax, durationRows, icdRows, withoutHidden } from './cacu-results';
import {
ageShare,
ageStack,
@@ -17,11 +18,10 @@ import {
fill,
nestedDonut,
rateDots,
routeFigure,
scenarioBars,
shareDonut,
} from './figures';
import { FigureSpec, Kpi, PAGES, Section } from './pages';
import { DistSpec, FigureSpec, Kpi, PAGES, Section } from './pages';
import {
detail,
donut,
@@ -31,6 +31,7 @@ import {
periodLabel,
periods,
PeriodType,
PPV_NOTES,
reading,
Reading,
scoring,
@@ -38,6 +39,8 @@ import {
strataBars,
} from './measures';
import { Loading } from '../loading';
import { PpvCard } from './ppv-card';
import { requestsAlternate } from './confirmation';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per
* clinical measure with its figures. */
@@ -52,6 +55,7 @@ import { Loading } from '../loading';
MatCardModule,
MatSelectModule,
Plot,
PpvCard,
],
templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss',
@@ -67,12 +71,17 @@ export class TabIndicadores {
/** The period the figures show (set by Aplicar). */
protected readonly applied = signal<string | undefined>(undefined);
protected readonly routeView = signal<'sample' | 'step'>('sample');
/** CaCu's route in three readings: cumulative from the sample, step by step, by ICD-10. */
/** The confirmation card's perspective. */
protected readonly confirmView = signal<'colposcopy' | 'biopsy'>('colposcopy');
/** The cytology column's two readings, one at a time. */
protected readonly cytologyView = signal<'general' | 'scenario'>('general');
protected readonly routeMode = signal<'sample' | 'step' | 'icd10'>('sample');
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
);
protected readonly pending =
'Este indicador aún no está publicado por el catálogo institucional.';
protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */
protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
@@ -115,11 +124,19 @@ export class TabIndicadores {
if (!params.period) return new Map<string, Reading | undefined>();
const found = await Promise.all(
params.measures.map(async (m) => {
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
try {
// Never `as-of`: CACU_BIOPSIA_SOLICITUD_CONFIRMACION cannot reconstruct the past.
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
} catch (error) {
// A CaCu measure the server cannot serve leaves its own card to say so, not the page.
if (params.domain === 'cacu' && m.name?.startsWith('CACU_'))
return [m.name, { populations: {}, strata: {}, error: true } as Reading] as const;
throw error;
}
}),
);
return new Map(found);
@@ -202,6 +219,12 @@ export class TabIndicadores {
return this.byName().get(code);
}
/** A card's value and note, from its templates (a card with no measure: its words). */
/** "27 días (mediana)" as the value and its qualifier, shown smaller beneath it. */
protected kpiParts(text: string): [string, string] {
const found = /^(.*?)\s*(\([^)]*\))$/.exec(text);
return found ? [found[1], found[2]] : [text, ''];
}
protected kpiValue(k: Kpi): string {
if (!k.measure) return k.value ?? '';
const r = this.rd(k.measure);
@@ -260,10 +283,91 @@ export class TabIndicadores {
return (code && this.byName().get(code)?.title) || '';
}
/** A clinical section's route or figures, drawn from the applied period's reports. */
protected routeOf(section: Section): Figure | undefined {
if (section.kind !== 'route') return undefined;
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) }));
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined;
/** A route's steps in one reading: days from the sample, or from the previous step. */
protected routeSteps(section: Section, mode: 'sample' | 'step') {
if (section.kind !== 'route') return [];
return section.steps.map((s) => ({
label: mode === 'step' ? (s.step ?? s.label) : s.label,
r: this.rd(mode === 'step' ? (s.stepMeasure ?? s.measure) : s.measure),
}));
}
/** The route's table: each step keeps its row, with or without measurements. */
protected stepRows(section: Section, mode: 'sample' | 'step') {
return durationRows(this.routeSteps(section, mode));
}
protected icdOf(section: Section) {
return section.kind === 'route' && section.modes
? { reading: this.rd(section.modes.icd), rows: icdRows(this.rd(section.modes.icd)) }
: undefined;
}
protected icdMax(rows: { median: number; high?: number }[]): number {
return Math.max(0, ...rows.map((r) => Math.max(r.median, r.high ?? 0)));
}
/** A distribution's table: its categories with their group lines, or none when the report
* does not add up (a zero is a zero; a report that is missing or inconsistent is not drawn).
* The categories the spec hides are left out of the rows only: the total, the percentages
* and the units outside stay as the report gives them. */
protected distOf(spec: DistSpec) {
const d = distribution(this.rd(spec.measure), spec.catalog);
if (!d) return undefined;
const { shown, max, hiddenCount } = withoutHidden(d, spec.hide);
const items = shown.flatMap((row) => [
...(spec.groups ?? [])
.filter((g) => g.before === row.code)
.map((g) => ({
kind: 'group' as const,
label: g.label,
count: d.rows.filter((r) => g.codes.includes(r.code)).reduce((n, r) => n + r.count, 0),
})),
{ kind: 'row' as const, ...row },
]);
return {
...d,
items,
max,
hiddenCount,
};
}
/** The scale of a duration table, in days from zero. */
protected routeMax = durationMax;
/** The confirmation card: both PPV cards, the requests reading. */
protected confirmOf(section: Section) {
if (section.kind !== 'confirmation') return undefined;
return {
colposcopy: this.cardOf({ kind: 'ppv', ...section.colposcopy })!,
biopsy: this.cardOf({ kind: 'ppv', ...section.biopsy })!,
requests: requestsAlternate(
this.rd(section.biopsy.requests),
this.byName().has(section.biopsy.requests),
),
};
}
/** A measure's card: its title (the PPVs say they are not referrals), score and figures. */
protected cardOf(section: Section) {
if (section.kind !== 'measure-card' && section.kind !== 'ppv') return undefined;
const m = this.byName().get(section.measure);
const r = this.rd(section.measure);
const summary = section.kind === 'ppv' ? section.summary : undefined;
return {
published: !!m,
reading: r,
title: PPV_NOTES[section.measure]?.title ?? m?.title ?? section.measure,
note: PPV_NOTES[section.measure]?.note,
score: summary ? summary(r).score : m ? formatScore(m, r) : '',
detail: summary ? summary(r).detail : m ? detail(m, r) : '',
figures: this.figureSets().get(section.measure) ?? [],
};
}
/** The legend of the scenario figure, in the catalogue's order (the figure draws none). */
protected scenarioLegend(spec: FigureSpec) {
return spec.kind === 'scenario-bars'
? spec.catalog.categories.map((c) => ({ label: c.label, color: c.color }))
: undefined;
}
/** The scenario figure's height: a slim bar per scenario and room for the axis. */
protected scenarioHeight(fig: Figure): number {
const bars = (fig.data[0] as { y?: unknown[] } | undefined)?.y?.length ?? 1;
return 70 + bars * 46;
}
protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure);
+2 -1
View File
@@ -1,6 +1,7 @@
<section class="card risk-tea" aria-labelledby="tea-risk-title">
<h2 id="tea-risk-title" class="risk-title">Alteraciones de EEG relacionadas al TEA</h2>
<div class="filters">
<app-patient-search [(value)]="search" (searched)="pageIndex.set(0)" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" />
@@ -147,7 +148,7 @@
</tr>
} @empty {
<tr>
<td colspan="7" class="muted">Nadie en la lista con estos filtros.</td>
<td colspan="7" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
</tbody>
+17 -3
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@@ -11,6 +12,7 @@ import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { ageLabel } from './figures';
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). */
export interface TeaRow {
@@ -67,14 +69,18 @@ const CASE: Record<string, string> = {
not_confirmed: 'Sin TEA',
};
/** `theta_power:above` → "theta_power (aumentado)". */
export const alteration = (a: string) =>
a.replace(/:(above|below)$/, (_, s) => (s === 'above' ? ' (aumentado)' : ' (disminuido)'));
export const alteration = (a: string) => {
const [metric, side] = a.split(':');
const shown = (METRIC_NAMES[metric] ?? metric).replace(/ \(.*\)$/, '');
return side ? `${shown} (${side === 'above' ? 'aumentado' : 'disminuido'})` : shown;
};
/** "Análisis de Riesgo" for TEA: the children active in the window, what their EEGs show,
* filtered as the old page filtered them. */
@Component({
selector: 'app-tab-riesgos-tea',
imports: [
PatientSearch,
FormsModule,
KeyValuePipe,
Loading,
@@ -100,6 +106,8 @@ export class TabRiesgosTea {
protected readonly caseState = signal('');
protected readonly altered = signal('');
protected readonly size = signal(50);
/** "Buscar paciente": the pseudonymous id, a record number or a name. */
protected readonly search = signal('');
protected readonly pageIndex = signal(0);
/** The query as last asked for ("Consultar"). */
private readonly asked = signal({ cutoff: '', window: 3 });
@@ -141,7 +149,13 @@ export class TabRiesgosTea {
(!band || (r.mchat !== undefined && band.test(r.mchat))) &&
(!level || (r.css !== undefined && level.test(r.css))) &&
(!this.caseState() || r.case === this.caseState()) &&
(!this.altered() || r.alterations.includes(this.altered())),
(!this.altered() || r.alterations.includes(this.altered())) &&
matchesSearch(this.search(), [
r.name,
r.patient.id,
...(r.patient.name ?? []).map((n) => n.text),
...(r.patient.identifier ?? []).map((i) => i.value),
]),
);
});
protected readonly shown = computed(() =>
+93 -6
View File
@@ -1,4 +1,44 @@
<div class="export-actions">
<button mat-stroked-button type="button" (click)="exportList('xlsx')" [disabled]="cannotExport()">
Exportar Excel (.xlsx)
</button>
<button mat-stroked-button type="button" (click)="exportList('pdf')" [disabled]="cannotExport()">
Exportar PDF
</button>
</div>
@if (exportMessage()) {
<p class="muted" role="alert">{{ exportMessage() }}</p>
}
<form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad mínima</mat-label>
<input
matInput
type="number"
min="0"
max="150"
step="1"
[ngModel]="ageMin()"
(ngModelChange)="ageMin.set($event)"
name="ageMin"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad máxima</mat-label>
<input
matInput
type="number"
min="0"
max="150"
step="1"
[ngModel]="ageMax()"
(ngModelChange)="ageMax.set($event)"
name="ageMax"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="clearAges()">Limpiar edades</button>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
@@ -52,6 +92,13 @@
</mat-form-field>
</form>
@if (invalidAge()) {
<p class="muted" role="alert">
Indique edades enteras entre 0 y 150; la mínima no puede superar la máxima. El rango no está
aplicado.
</p>
}
@if (error()) {
<p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
@@ -71,8 +118,9 @@
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Edad</th>
<th>Estatus de seguimiento</th>
<th>Etapas del tamizaje</th>
<th>Última citología</th>
<th>Último resultado de VPH</th>
<th>Última biopsia</th>
@@ -86,15 +134,41 @@
@for (row of rows(); track row.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
row.name ?? row.patient.id!.slice(0, 10)
}}</a>
<a
[routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
[queryParams]="{ corte: applied(), muestra: row.cytology?.date }"
>{{ patientLabel(row.patient) }}</a
>
@if (row.curp) {
<div class="muted curp">{{ row.curp }}</div>
}
</td>
<td>{{ row.ageGroup }}</td>
<td>
{{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup || 'No disponible' }}</small>
</td>
<td>{{ name(row.status) }}</td>
<td>
<div class="stage-compact">
<app-stages
[sample]="row.cytology?.date"
[report]="row.cytology?.result ? row.cytology?.reportDate : undefined"
[cutoff]="applied()"
[facts]="row.stageFacts"
/>
<button
class="stage-toggle"
type="button"
[attr.aria-label]="
expanded() === row.patient.id ? 'Ocultar etapas' : 'Mostrar etapas'
"
[attr.aria-expanded]="expanded() === row.patient.id"
(click)="toggle(row.patient.id)"
>
<span [class.open]="expanded() === row.patient.id" aria-hidden="true">⌄</span>
</button>
</div>
</td>
<td>
@if (row.cytology; as c) {
{{
@@ -153,10 +227,23 @@
<td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr>
@if (expanded() === row.patient.id) {
<tr class="stage-panel">
<td colspan="11">
<app-stages
[sample]="row.cytology?.date"
[report]="row.cytology?.result ? row.cytology?.reportDate : undefined"
[cutoff]="applied()"
[facts]="row.stageFacts"
[detail]="true"
/>
</td>
</tr>
}
} @empty {
@if (page() && !loading()) {
<tr>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
<td colspan="11" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
}
+53
View File
@@ -10,6 +10,11 @@
margin-bottom: var(--space-4);
}
// a field as wide as its label ("Horizonte de la probabilidad")
.filters mat-form-field {
min-width: 14.5rem;
}
.table-wrap {
overflow-x: auto;
padding: 0;
@@ -43,6 +48,7 @@ a {
.worklist td small {
display: block;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
@@ -54,3 +60,50 @@ a {
.window {
margin: 4px 0 8px;
}
.export-actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
justify-content: flex-end;
margin-bottom: var(--space-3);
}
.stage-compact {
align-items: center;
display: flex;
}
.stage-toggle {
background: transparent;
border: 0;
color: #385c6c;
cursor: pointer;
display: grid;
flex: 0 0 32px;
height: 32px;
padding: 0;
place-items: center;
width: 32px;
}
.stage-toggle:focus-visible {
outline: 2px solid #2778b8;
outline-offset: 2px;
}
.stage-toggle span {
display: block;
font-size: 18px;
line-height: 1;
transition: transform 120ms ease;
}
.stage-toggle span.open {
transform: rotate(180deg);
}
// the detailed stages of one patient, across the table
.stage-panel td {
background: var(--mat-sys-surface-container-low, #f6f8f9);
}
+194 -3
View File
@@ -1,4 +1,5 @@
import { DecimalPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -7,18 +8,29 @@ import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { downloadDocument } from '../export-document';
import { Fhir } from '../fhir';
import { Row, rows, windowStart } from './follow-up';
import { Loading } from '../loading';
import { Stages, stages } from '../paciente/stages';
import { patientLabel, Row, rows, windowStart } from './follow-up';
import { name } from './measures';
import { PatientSearch, patientSearch } from './patient-search';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
const SORTS: Record<string, string> = {
'-recent': 'Estudio más reciente',
'-risk-cin2': 'Mayor riesgo de LIEAG+',
'-risk-cancer': 'Mayor riesgo de cáncer',
};
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status,
* results and current risks, in the order asked for. */
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her age, status, the
* stages of her screening, results and current risks, in the order asked for; and the same
* query as a PDF or an Excel file. */
@Component({
selector: 'app-tab-riesgos',
imports: [
PatientSearch,
DecimalPipe,
FormsModule,
Loading,
@@ -27,12 +39,14 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
MatInputModule,
MatSelectModule,
RouterLink,
Stages,
],
templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss',
})
export class TabRiesgos {
private readonly fhir = inject(Fhir);
private readonly http = inject(HttpClient);
readonly domain = input.required<string>();
protected readonly cutoff = signal<string>('');
@@ -41,16 +55,44 @@ export class TabRiesgos {
protected readonly horizon = signal(5);
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
/** Completed years at the cut-off, from and to (none: no limit). */
protected readonly ageMin = signal<number | null>(null);
protected readonly ageMax = signal<number | null>(null);
/** The patient whose stages are open under her row. */
protected readonly expanded = signal<string | undefined>(undefined);
/** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly exporting = signal(false);
protected readonly exportMessage = signal('');
protected readonly statuses = STATUSES;
protected readonly name = name;
protected readonly patientLabel = patientLabel;
/** Whole years between 0 and 150, and the minimum not above the maximum; else the range is
* not applied and the page says so. */
protected readonly invalidAge = computed(() => {
const [low, high] = [this.ageMin(), this.ageMax()];
const bad = (n: number | null) => n !== null && (!Number.isInteger(n) || n < 0 || n > 150);
return bad(low) || bad(high) || (low !== null && high !== null && low > high);
});
private readonly ages = computed(() =>
this.invalidAge()
? {}
: {
'follow-up-age-min': this.ageMin() ?? undefined,
'follow-up-age-max': this.ageMax() ?? undefined,
},
);
private readonly first = resource({
params: () => ({
domain: this.domain(),
'follow-up-window': this.window(),
...patientSearch(this.search()),
...this.ages(),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
@@ -59,6 +101,7 @@ export class TabRiesgos {
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined);
this.expanded.set(undefined);
return this.fhir.search(domain, 'Patient', {
...params,
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
@@ -107,6 +150,13 @@ export class TabRiesgos {
protected retry(): void {
this.first.reload();
}
protected toggle(id: string | undefined): void {
this.expanded.set(this.expanded() === id ? undefined : id);
}
protected clearAges(): void {
this.ageMin.set(null);
this.ageMax.set(null);
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
@@ -123,4 +173,145 @@ export class TabRiesgos {
this.loading.set(false);
}
}
/** What an export may not start from: no list yet, a range not applied, or a query in motion. */
protected readonly cannotExport = computed(
() =>
this.exporting() ||
!this.page() ||
this.invalidAge() ||
this.first.isLoading() ||
this.loading(),
);
/** The whole query (not the page on screen) as a PDF or an Excel file, with the filters it
* was asked with. The server's limits are the ones that decide; the list is read again
* whole and must still be the query it was when the button was pressed. */
protected async exportList(format: 'xlsx' | 'pdf'): Promise<void> {
if (this.cannotExport() || !this.applied()) return;
const total = this.page()!.total ?? 0;
const cutoff = this.applied();
const months = this.window();
const horizon = this.horizon();
this.exporting.set(true);
this.exportMessage.set('');
try {
const limits = await firstValueFrom(
this.http.get<{ xlsx_limit: number; pdf_limit: number }>('/api/cacu/exports/capabilities'),
);
const limit = format === 'pdf' ? limits.pdf_limit : limits.xlsx_limit;
if (total > limit) {
this.exportMessage.set(
`La consulta tiene ${total} pacientes; el límite para ${format.toUpperCase()} es ${limit}. Ajuste los filtros.`,
);
return;
}
const params = {
'follow-up-window': months,
'follow-up-cutoff': cutoff,
'follow-up-status': this.status() || undefined,
'risk-horizon': horizon,
_sort: this.sort(),
_count: 200,
...patientSearch(this.search()),
...this.ages(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
};
const pages = await this.fhir.all(this.domain(), 'Patient', params);
const all = pages.flatMap((p) => rows(p, windowStart(cutoff, months), cutoff, horizon));
if (
all.length !== total ||
new Set(all.map((r) => r.patient.id)).size !== total ||
pages.some((p) => p.total !== total)
)
throw new Error('La consulta cambió durante la exportación; vuelva a intentarlo.');
await downloadDocument(this.http, format, this.document(all, cutoff, months, horizon, total));
} catch (error) {
this.exportMessage.set(
error instanceof Error ? error.message : 'No se pudo generar la exportación.',
);
} finally {
this.exporting.set(false);
}
}
/** The document: the parameters of the query and one row per patient, as the list shows her. */
private document(all: Row[], cutoff: string, months: number, horizon: number, total: number) {
const pct = (n?: number) => (n === undefined ? 'No disponible' : `${(100 * n).toFixed(1)} %`);
const years = `${horizon} ${horizon === 1 ? 'año' : 'años'}`;
const routes = all.map((r) =>
stages(
r.cytology?.date,
r.cytology?.result ? r.cytology.reportDate : undefined,
cutoff,
r.stageFacts,
),
);
return {
title: 'Resultados de seguimiento',
parameters: [
['Fecha de corte', cutoff],
[
'Ventana consultada',
`${windowStart(cutoff, months)} al ${cutoff} (${months} ${months === 1 ? 'mes' : 'meses'})`,
],
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
['Orden', SORTS[this.sort()] ?? this.sort()],
['Horizonte de la probabilidad', years],
['Nombre o identificador', this.search().trim() || 'Todos'],
['Edad mínima (años)', String(this.ageMin() ?? 'Sin límite')],
['Edad máxima (años)', String(this.ageMax() ?? 'Sin límite')],
['Registros', String(total)],
],
columns: [
'Paciente',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
`Riesgo LIEAG+ a ${years}`,
`Riesgo de cáncer a ${years}`,
'Días de toma a diagnóstico',
],
row_stages: routes.map((route) =>
route.map((s) => ({
state: s.state,
...(s.provenance ? { provenance: s.provenance } : {}),
...(s.date ? { date: s.date } : {}),
})),
),
rows: all.map((r, i) => [
`${patientLabel(r.patient)}${r.curp ? '\n' + r.curp : ''}`,
r.age === undefined ? 'No disponible' : `${r.age}`,
name(r.status),
routes[i]
.map(
(s) =>
`${s.label}: ${s.state}${s.date ? ' ' + s.date : ''}${s.provenance ? ' (' + s.provenance + ')' : ''}`,
)
.join('\n'),
r.cytology
? `${r.cytology.date} · ${
r.cytology.result
? name(r.cytology.result)
: r.cytology.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}`
: 'No disponible',
r.hpv
? `${r.hpv.positive ? 'Positivo' : 'Negativo'}${r.hpv.types1618 ? ' (16/18)' : ''}`
: 'No disponible',
r.biopsy
? `${r.biopsy.date} · ${name(r.biopsy.histology ?? '') || 'Sin grado'}`
: 'No disponible',
pct(r.risk.cin2),
pct(r.risk.cancer),
String(r.daysToDiagnosis ?? 'No disponible'),
]),
};
}
}
+6 -3
View File
@@ -1,4 +1,5 @@
<form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
@@ -66,9 +67,11 @@
@for (row of rows(); track row.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
row.name ?? row.patient.id!.slice(0, 10)
}}</a>
<a
[routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
[queryParams]="{ ventana: window(), corte: applied() }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
>
@if (row.curp) {
<div class="muted curp">{{ row.curp }}</div>
}
+5
View File
@@ -8,6 +8,7 @@ import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { camaRows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
import { name, PRIORITY } from './measures';
@@ -18,6 +19,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy
@Component({
selector: 'app-tab-seguimiento',
imports: [
PatientSearch,
FormsModule,
Loading,
MatButtonModule,
@@ -37,6 +39,8 @@ export class TabSeguimiento {
protected readonly window = signal(3);
protected readonly status = signal<string>('');
protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES;
@@ -47,6 +51,7 @@ export class TabSeguimiento {
params: () => ({
domain: this.domain(),
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_count: this.size(),
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest';
import { Reading } from './measures';
import { VPH_MODES, vphDonut, vphGenotypes, vphGroups, vphSummary } from './vph';
const n = (count: number) => ({ 'initial-population': count });
const report = (strata: Reading['strata'], population = 10): Reading => ({
populations: { 'initial-population': population },
strata,
});
const base = { category: { negative: n(7), positive: n(3) } };
describe('CACU_VPH readings (patients by their latest HPV result)', () => {
it('summarises the patients and how they split, and does not invent when it does not add up', () => {
expect(vphSummary(report(base))).toEqual({
score: '10 pacientes',
detail: 'Negativo: 7 (70.0 %) · Positivo: 3 (30.0 %).',
});
expect(vphSummary(report({ category: { negative: n(7) } })).score).toBe('Sin dato');
expect(vphSummary(undefined).score).toBe('Sin dato');
// a real zero is a zero, not a missing report
expect(vphSummary(report({ category: {} }, 0)).score).toBe('0 pacientes');
expect(vphDonut(report({ category: {} }, 0))).toBeUndefined();
});
it('draws the whole as negative and positive in the HPV colours of the page', () => {
const fig = vphDonut(report(base))!;
const pie = fig.data[0] as { values: number[]; marker: { colors: string[] } };
expect(pie.values).toEqual([7, 3]);
expect(pie.marker.colors).toEqual(['#42a77e', '#a8c243']);
});
it('gives each group its positives over its patients with a result, in age order', () => {
const rows = vphGroups(
report({
...base,
'age_group-category': {
'45-54|positive': n(2),
'45-54|negative': n(2),
'25-34|negative': n(4),
'<25|positive': n(1),
},
}),
'age_group',
);
expect(rows.map((r) => r.code)).toEqual(['<25', '25-34', '45-54']);
expect(rows[2]).toMatchObject({ numerator: 2, denominator: 4, percent: 50 });
// a group with patients and no positive is a zero rate, not a missing one
expect(rows[1]).toMatchObject({ numerator: 0, denominator: 4, percent: 0 });
expect(vphGroups(report(base), 'age_group')).toEqual([]);
});
it('keeps "no data" neutral and the rounds excluding', () => {
const rows = vphGroups(
report({
...base,
'screening_round-category': {
'no_data|negative': n(1),
'initial|positive': n(1),
'subsequent|negative': n(2),
},
}),
'screening_round',
);
expect(rows.map((r) => r.code)).toEqual(['initial', 'subsequent', 'no_data']);
expect(rows[2]).toMatchObject({ label: 'Sin dato', color: '#C9CDD2' });
});
it('reads each genotype over the patients whose genotype was reported, and skips an unpublished one', () => {
const rows = vphGenotypes(report({ ...base, hpv_16: { negative: n(5), positive: n(2) } }));
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
label: 'VPH 16',
numerator: 2,
denominator: 7,
color: '#df8640',
});
});
it('offers the whole and the four breakdowns the measure publishes', () => {
expect(VPH_MODES.map((m) => m.id)).toEqual(['total', 'age', 'status', 'genotype', 'round']);
expect(VPH_MODES.every((m) => m.caption.length > 20)).toBe(true);
});
});
+188
View File
@@ -0,0 +1,188 @@
import type { Figure } from '../plot';
import { HPV_REPORTS } from './cacu-results';
import { name, Reading } from './measures';
import { PpvMode, PpvRow } from './ppv';
/** CACU_VPH counts patients: each one by her latest sample with an HPV result in the period. It
* is not CACU_VPH_GENOTIPO, which counts reports. Its readings are the ones the report publishes:
* the result (the `category` stratum), that result inside each group of a stratifier (the report's
* `<stratum>-category` cells), and the genotypes 16 and 18 (strata of their own). */
const color = (code: string) => HPV_REPORTS.find((r) => r[0] === code)![2];
const NEGATIVE = color('negative');
const POSITIVE = color('positive_other');
const NEUTRAL = '#C9CDD2';
const STEEL = '#5F7F9A';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
const count = (cell: Record<string, number> | undefined) => cell?.['initial-population'];
/** The patients by result, when the report adds up to its population. */
function results(reading: Reading | undefined) {
const cells = reading?.strata['category'];
const total = reading?.populations['initial-population'];
if (!cells || !whole(total)) return undefined;
const negative = count(cells['negative']) ?? 0;
const positive = count(cells['positive']) ?? 0;
const other = Object.keys(cells).some((c) => c !== 'negative' && c !== 'positive');
return whole(negative) && whole(positive) && !other && negative + positive === total
? { total, negative, positive }
: undefined;
}
const share = (n: number, of: number) => ((100 * n) / of).toFixed(1);
/** The card's heading figures: patients with a result, and how they split. */
export function vphSummary(reading: Reading | undefined): { score: string; detail: string } {
const r = results(reading);
if (!r) return { score: 'Sin dato', detail: '' };
if (!r.total) return { score: '0 pacientes', detail: 'Sin pacientes en el periodo.' };
return {
score: `${r.total} pacientes`,
detail: `Negativo: ${r.negative} (${share(r.negative, r.total)} %) · Positivo: ${r.positive} (${share(r.positive, r.total)} %).`,
};
}
/** The whole: negative and positive patients as a donut. */
export function vphDonut(reading: Reading | undefined): Figure | undefined {
const r = results(reading);
if (!r?.total) return undefined;
return {
data: [
{
type: 'pie',
hole: 0.62,
labels: ['Negativo', 'Positivo'],
values: [r.negative, r.positive],
sort: false,
direction: 'clockwise',
textinfo: 'value+percent',
textposition: 'outside',
marker: { colors: [NEGATIVE, POSITIVE] },
},
],
layout: {
height: 260,
showlegend: true,
margin: { t: 16, r: 8, b: 16, l: 8 },
legend: { orientation: 'h' },
},
};
}
const AGES = ['<25', '25-34', '35-44', '45-54', '55-64', '65+'];
const ORDER: Record<string, [code: string, color: string][]> = {
age_group: AGES.map((c) => [c, STEEL]),
follow_up_status: [
['pre_colposcopy', STEEL],
['post_colposcopy', '#8FA7BB'],
['post_treatment', '#B5C5D3'],
['case', '#9AA3AB'],
],
screening_round: [
['initial', STEEL],
['subsequent', '#8FA7BB'],
['no_data', NEUTRAL],
],
};
const groupLabel = (group: string) =>
group === 'no_data'
? 'Sin dato'
: name(group) === group
? group.replace('-', ' a ')
: name(group);
/** A group's positive patients over its patients with a result, from the report's crossed cells.
* A group the report does not list is not drawn; absent is not a zero. */
export function vphGroups(reading: Reading | undefined, stratum: string): PpvRow[] {
const cells = reading?.strata[`${stratum}-category`];
if (!cells) return [];
const groups = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
const order = ORDER[stratum] ?? [];
const known = order.map(([c]) => c);
return [...known.filter((g) => groups.includes(g)), ...groups.filter((g) => !known.includes(g))]
.map((group) => {
const negative = count(cells[`${group}|negative`]) ?? 0;
const positive = count(cells[`${group}|positive`]) ?? 0;
const denominator = negative + positive;
return {
code: group,
label: groupLabel(group),
color: order.find(([c]) => c === group)?.[1] ?? STEEL,
numerator: positive,
denominator,
percent: denominator ? (100 * positive) / denominator : undefined,
};
})
.filter((row) => whole(row.numerator) && whole(row.denominator));
}
/** Genotype 16 and 18: positives over the patients whose genotype was reported (its own stratum). */
export function vphGenotypes(reading: Reading | undefined): PpvRow[] {
return (
[
['hpv_16', 'VPH 16', color('positive_16')],
['hpv_18', 'VPH 18', color('positive_18')],
] as const
).flatMap(([stratum, label, tone]) => {
const cells = reading?.strata[stratum];
if (!cells) return [];
const negative = count(cells['negative']) ?? 0;
const positive = count(cells['positive']) ?? 0;
if (!whole(negative) || !whole(positive)) return [];
const denominator = negative + positive;
return [
{
code: stratum,
label,
color: tone,
numerator: positive,
denominator,
percent: denominator ? (100 * positive) / denominator : undefined,
},
];
});
}
const POSITIVES = '% positivas';
const OF_RESULT = 'Positivas sobre las pacientes con resultado de VPH del grupo (n/N)';
/** The readings of CACU_VPH: the whole, and each breakdown the measure publishes. */
export const VPH_MODES: PpvMode[] = [
{
id: 'total',
label: 'Total',
figure: vphDonut,
caption:
'Una paciente por periodo, por su última muestra con resultado de VPH: negativas y positivas sobre todas ellas.',
},
{
id: 'age',
label: 'Por grupo de edad',
rows: (r) => vphGroups(r, 'age_group'),
percentLabel: POSITIVES,
caption: `${OF_RESULT}. Los grupos son excluyentes.`,
},
{
id: 'status',
label: 'Por estatus de seguimiento',
rows: (r) => vphGroups(r, 'follow_up_status'),
percentLabel: POSITIVES,
caption: `${OF_RESULT}. El estatus es el de la paciente al inicio del periodo; los grupos son excluyentes.`,
},
{
id: 'genotype',
label: 'Por genotipo',
rows: vphGenotypes,
percentLabel: POSITIVES,
caption:
'Positivas para el genotipo sobre las pacientes con ese genotipo reportado; el denominador cambia por genotipo y una paciente puede ser positiva para ambos.',
},
{
id: 'round',
label: 'Por tamizaje inicial o subsecuente',
rows: (r) => vphGroups(r, 'screening_round'),
percentLabel: POSITIVES,
caption: `${OF_RESULT}. Cada paciente está en un solo grupo; «Sin dato»: sin clasificación de tamizaje inicial o subsecuente.`,
},
];
+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),
})),
);
}
+198 -47
View File
@@ -1,4 +1,14 @@
<section class="page">
@if (domain() === 'cacu' && patient()) {
<div class="export-actions">
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="exportPatient()">
Exportar ficha PDF
</button>
</div>
}
@if (exportError()) {
<p class="muted" role="alert">{{ exportError() }}</p>
}
<a mat-button [routerLink]="['/indicadores', domain()]"
><mat-icon>arrow_back</mat-icon> Regresar</a
>
@@ -6,7 +16,10 @@
<p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) {
<h1>
{{ identity().name ?? 'Paciente' }} <code class="muted">{{ p.id!.slice(0, 10) }}</code>
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
@if (domain() === 'cacu') {
· Edad: {{ age() ?? 'No disponible' }}
}
</h1>
<dl class="summary">
<div>
@@ -27,10 +40,37 @@
{{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }}
</dd>
</div>
<div>
<dt>Estatus de seguimiento</dt>
<dd>{{ status() }}</dd>
</div>
@if (cama(); as c) {
<div>
<dt>Grupo de edad</dt>
<dd>{{ c.ageGroup || 'No disponible' }}</dd>
</div>
<div>
<dt>Escenario clínico</dt>
<dd>{{ c.scenario }}</dd>
</div>
<div>
<dt>Estatus de seguimiento</dt>
<dd>
{{ c.status ?? 'Fuera de la lista (' + c.window + ' meses al ' + c.cutoff + ')' }}
</dd>
</div>
<div>
<dt>Prioridad</dt>
<dd>{{ c.priority ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Días de mastografía a diagnóstico</dt>
<dd>{{ c.days ?? 'No disponible' }}</dd>
</div>
} @else {
@if (status()) {
<div>
<dt>Estatus de seguimiento</dt>
<dd>{{ status() }}</dd>
</div>
}
}
@if (p.deceasedDateTime) {
<div>
<dt>Defunción</dt>
@@ -40,9 +80,57 @@
</dl>
<div class="cards">
@if (cama(); as c) {
<mat-card appearance="outlined" data-section="mastografia">
<mat-card-header><mat-card-title>Mastografía</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Última mastografía</h3>
<dl class="facts">
<div>
<dt>Categoría BI-RADS</dt>
<dd>{{ c.birads ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Fecha</dt>
<dd>{{ c.mammogram ?? 'No disponible' }}</dd>
</div>
</dl>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" data-section="histopatologia">
<mat-card-header><mat-card-title>Histopatología</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Resultado histopatológico</h3>
<dl class="facts">
<div>
<dt>Resultado</dt>
<dd>{{ c.histology ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Fecha de reporte de la biopsia</dt>
<dd>{{ c.biopsy ?? 'No disponible' }}</dd>
</div>
</dl>
</mat-card-content>
</mat-card>
}
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content>
@if (domain() === 'cacu') {
<app-stages
[sample]="sample()"
[report]="sampleReportDate()"
[cutoff]="cutoff()"
[facts]="sampleFacts()"
[detail]="true"
/>
<p class="muted route-note">
Etapas de la citología{{ sample() ? ' del ' + sample() : '' }} a la fecha de corte
{{ cutoff() }}. «Inferida temporalmente» es una asociación por cercanía de fechas, no
un vínculo clínico confirmado; «Desconocida» indica que no hay dato.
</p>
}
<table class="plain">
<thead>
<tr>
@@ -108,6 +196,72 @@
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
@if (domain() === 'cacu') {
<p class="muted">
Divisiones numéricas descriptivas; no representan umbrales clínicos.
</p>
@for (model of riskScales(); track model.model) {
<h3>{{ model.model }} · fecha índice {{ model.index }}</h3>
@for (
scale of [
{ label: 'Riesgo inmediato (al índice)', value: model.immediate },
{ label: 'Riesgo a 5 años', value: model.five },
];
track scale.label
) {
<div class="risk-scale">
<p>
<strong>{{ scale.label }}</strong>
@if (scale.value; as v) {
@if (v.low !== undefined && v.high !== undefined) {
· IC 95 %: {{ v.low * 100 | number: '1.1-2' }}–{{
v.high * 100 | number: '1.1-2'
}}
%
}
} @else {
· No disponible
}
</p>
<div class="risk-plot" [class.unavailable]="!scale.value">
<div class="risk-line" aria-hidden="true"></div>
@if (scale.value; as v) {
<span
class="risk-marker"
[style.left.%]="v.value * 100"
aria-hidden="true"
></span>
<strong
class="risk-value"
[style.left]="'clamp(2.5rem, ' + v.value * 100 + '%, calc(100% - 2.5rem))'"
>{{ v.value * 100 | number: '1.1-2' }} %</strong
>
}
</div>
<div class="risk-labels">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span
><span>100 %</span>
</div>
</div>
}
} @empty {
@for (label of ['Riesgo inmediato', 'Riesgo a 5 años']; track label) {
<div class="risk-scale">
<p>
<strong>{{ label }}</strong> · No disponible
</p>
<div class="risk-plot unavailable">
<div class="risk-line" aria-hidden="true"></div>
</div>
<div class="risk-labels">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span
><span>100 %</span>
</div>
</div>
}
<p class="muted">Ningún modelo vigente la ha evaluado.</p>
}
}
@if (models().length) {
<table class="plain">
<thead>
@@ -142,7 +296,7 @@
</table>
<app-plot [figure]="curve()" [height]="300" />
} @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>
@@ -178,16 +332,14 @@
Estudio del {{ st.study_date }}:
<strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong>
@if (st.level) {
({{ st.level }})
({{ levelNames[st.level] ?? st.level }})
}
</p>
<h3>Alteraciones del EEG</h3>
@if (!st.valid) {
<p class="muted">Un EEG no aceptable no se compara con la norma por edad.</p>
<p class="muted">EEG no aceptable: no se compara con la norma por edad.</p>
} @else if (!scored()) {
<p class="muted">
Ninguna curva por edad vigente ha evaluado este EEG (se promueven en Gobernanza).
</p>
<p class="muted">Sin curva por edad en producción para este EEG.</p>
} @else if (alterations().length) {
<table class="plain">
<thead>
@@ -266,10 +418,7 @@
>
<h3>Relación con el ADOS-2</h3>
@if (!eeg.value()?.analysis?.relation?.length) {
<p class="muted">
Ningún modelo de asociación vigente ha evaluado este EEG (se promueven en
Gobernanza).
</p>
<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
@@ -288,7 +437,7 @@
<th>Aspecto del ADOS-2</th>
<th>Asociación en la cohorte</th>
<th>Probabilidad para este paciente</th>
<th>Lo que muestra su ADOS-2</th>
<th>Resultado en su ADOS-2</th>
</tr>
</thead>
<tbody>
@@ -352,41 +501,13 @@
</mat-card>
}
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header
><mat-card-title>Análisis de supervivencia</mat-card-title></mat-card-header
>
<mat-card-content>
@if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas.
</p>
}
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
}
</mat-card-content>
</mat-card>
}
@if (recurrenceModel(); as rm) {
<mat-card appearance="outlined" class="wide" data-section="recurrencia">
<mat-card-header
><mat-card-title>Análisis de recurrencia</mat-card-title></mat-card-header
><mat-card-title>Pronóstico y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
<h3>Análisis de recurrencia</h3>
<table class="plain">
<thead>
<tr>
@@ -417,15 +538,45 @@
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios tienen menos recaídas de las necesarias para trazar curvas.
Sus escenarios no tienen recaídas suficientes para trazar curvas.
</p>
}
<app-factores [rows]="s.factors" />
} @else if (recurrence.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
}
</mat-card-content>
</mat-card>
}
@if (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()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios no tienen fallecimientos suficientes para trazar curvas.
</p>
}
<app-factores [rows]="s.factors" />
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
}
</mat-card-content>
</mat-card>
}
</div>
} @else if (loading()) {
<app-loading what="el expediente" />
+79 -3
View File
@@ -1,16 +1,19 @@
.summary {
.summary,
.facts {
display: flex;
flex-wrap: wrap;
gap: var(--space-6);
margin: var(--space-3) 0 var(--space-4);
}
.summary dt {
.summary dt,
.facts dt {
color: var(--color-text-secondary);
font-size: 12px;
}
.summary dd {
.summary dd,
.facts dd {
font-weight: 500;
margin: 0;
}
@@ -88,3 +91,76 @@ tr.chosen td {
font-size: 0.8em;
}
}
h1 .id {
font-size: 14px;
font-weight: 400;
margin-left: var(--space-2);
vertical-align: middle;
}
.export-actions {
display: flex;
justify-content: flex-end;
margin-bottom: var(--space-3);
}
.route-note {
font-size: 12px;
margin: var(--space-2) 0 var(--space-3);
}
// the risk scale: four equal numeric parts of 0 to 100 %, descriptive, not clinical thresholds
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
p {
margin: 0;
}
}
.risk-plot {
padding-top: 24px;
position: relative;
}
.risk-line {
background: linear-gradient(
to right,
#42a77e 0 25%,
#a8c243 25% 50%,
#df8640 50% 75%,
#c24269 75% 100%
);
height: 16px;
}
.unavailable .risk-line {
background: repeating-linear-gradient(
to right,
#d9dfe2 0,
#d9dfe2 calc(25% - 1px),
#fff calc(25% - 1px),
#fff 25%
);
}
.risk-marker {
background: #17324d;
bottom: -2px;
height: 20px;
position: absolute;
transform: translateX(-50%);
width: 3px;
}
.risk-value {
color: #17324d;
font-size: 13px;
position: absolute;
top: 1px;
transform: translateX(-50%);
white-space: nowrap;
}
.risk-labels {
display: flex;
font-size: 12px;
justify-content: space-between;
margin-top: 3px;
}
+285 -14
View File
@@ -1,4 +1,5 @@
import { DecimalPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -12,6 +13,7 @@ import type {
Procedure,
RiskAssessment,
} from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { Api } from '../api/api';
import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study';
@@ -19,8 +21,17 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { CURP } from '../indicadores/follow-up';
import { LABELS, name } from '../indicadores/measures';
import { downloadDocument } from '../export-document';
import {
ageGroup,
CAMA_AGE_GROUPS,
camaRows,
CURP,
exactAge,
patientLabel,
patientName,
} from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
import {
BIOMARKER_NAMES,
byDeviation,
@@ -28,10 +39,14 @@ import {
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 { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores';
import { horizonRisk } from './risk-scale';
import { daysBetween, intervalText, routeFacts, stages, Stages } from './stages';
/** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string {
@@ -49,7 +64,17 @@ function shown(o: Observation): string {
* champion models' risks with their curves. Everything read from the FHIR API. */
@Component({
selector: 'app-paciente',
imports: [Loading, DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
imports: [
Factores,
Loading,
Stages,
DecimalPipe,
MatButtonModule,
MatCardModule,
MatIconModule,
RouterLink,
Plot,
],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
})
@@ -58,16 +83,37 @@ export class Paciente {
private readonly api = inject(Api);
readonly domain = input.required<string>();
readonly id = input.required<string>();
/** The follow-up list she was opened from: its window (months) and cut-off. */
readonly ventana = input<string>();
readonly corte = input<string>();
/** CaCu: the sample (its day) whose route the list showed. */
readonly muestra = input<string>();
private readonly http = inject(HttpClient);
protected readonly exporting = signal(false);
protected readonly exportError = signal('');
private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }),
loader: async ({ params: { domain, id } }) => {
params: () => ({ domain: this.domain(), id: this.id(), cutoff: this.corte() }),
loader: async ({ params: { domain, id, cutoff } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 };
const cacu = domain === 'cacu' && !!cutoff;
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
this.fhir.read<Patient>(domain, 'Patient', id),
// opened from the list: her status and age as of its cut-off
cacu
? this.fhir
.search(domain, 'Patient', { _id: id, 'follow-up-cutoff': cutoff })
.then((bundle) => {
const found = resources<Patient>(bundle, 'Patient', 'match')[0];
if (!found) throw new Error('Paciente no encontrada');
return found;
})
: this.fhir.read<Patient>(domain, 'Patient', id),
this.fhir.all(domain, 'Condition', subject),
this.fhir.all(domain, 'Procedure', subject),
this.fhir.all(domain, 'DiagnosticReport', subject),
this.fhir.all(domain, 'DiagnosticReport', {
...subject,
'stage-cutoff': cacu ? cutoff : undefined,
}),
this.fhir.all(domain, 'Observation', subject),
this.fhir.all(domain, 'RiskAssessment', subject),
]);
@@ -94,7 +140,8 @@ export class Paciente {
date: c.recordedDate ?? '',
kind: 'Diagnóstico',
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) => ({
date: p.performedDateTime ?? '',
@@ -116,7 +163,11 @@ export class Paciente {
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
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}`;
}),
};
});
});
@@ -174,7 +225,16 @@ export class Paciente {
const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
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(
@@ -187,6 +247,7 @@ export class Paciente {
};
}
return {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
scenarios: m.scenarios,
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
@@ -303,8 +364,8 @@ export class Paciente {
if (f.observed === null || f.observed === undefined) return undefined;
const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8;
return present === f.probability >= 0.5
? 'Coincide con lo que el modelo esperaba'
: 'No coincide con lo que el modelo esperaba';
? '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 ?? []));
@@ -337,7 +398,7 @@ export class Paciente {
x,
y: m.predictions.map((p) => p.p * 100),
mode: 'lines+markers',
name: m.model.replace('cacu.', ''),
name: m.text.replace(/ v\d+$/, ''),
line: { color },
},
];
@@ -357,12 +418,222 @@ export class Paciente {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
}
protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES;
// ---- CaCu: the screening route of one cytology, her age, and her risks ----
/** The cut-off her route and age are told at: the list's, else today. */
protected readonly cutoff = computed(() => this.corte() ?? new Date().toISOString().slice(0, 10));
protected readonly age = computed(() => exactAge(this.patient()?.birthDate, this.cutoff()));
/** The cytology whose route is drawn: the one the list opened her at, else her latest. */
private readonly routeReport = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
(r) => code(r.code) === 'cervical_cytology',
);
return (
cytologies.find((r) => r.effectiveDateTime === this.muestra()) ??
(this.muestra() ? undefined : cytologies[0])
);
});
protected readonly sample = computed(() => this.routeReport()?.effectiveDateTime);
/** Her report day, only when the cytology has a result. */
protected readonly sampleReportDate = computed(() => {
const d = this.data.value();
const report = this.routeReport();
const hasResult = (report?.result ?? []).some((ref) => {
const o = d?.observations.get(ref.reference?.split('/')[1]);
return code(o?.code) === 'cervical_cytology.result' && !!code(o?.valueCodeableConcept);
});
return hasResult ? ext(report, 'report-date')?.valueDate : undefined;
});
protected readonly sampleFacts = computed(() => routeFacts(this.routeReport()));
/** The route as drawn, for the export too. */
protected readonly route = computed(() =>
stages(this.sample(), this.sampleReportDate(), this.cutoff(), this.sampleFacts()),
);
/** The immediate (index) and five-year risk of each CaCu risk model, by the horizons the
* model published: a horizon it did not publish is absent, never a zero. The title is the
* model's own, so the outcome is the one it predicts. */
protected readonly riskScales = computed(() => {
const latest = new Map<string, RiskAssessment>();
for (const risk of this.data.value()?.risks ?? []) {
const key = code(risk.method) ?? '';
if (!key.startsWith('cacu.cin2') && !key.startsWith('cacu.cancer')) continue;
const known = latest.get(key);
if (!known || (known.occurrenceDateTime ?? '') < (risk.occurrenceDateTime ?? ''))
latest.set(key, risk);
}
return [...latest.entries()].map(([model, risk]) => ({
model: risk.method?.coding?.[0]?.display ?? risk.method?.text ?? model,
index: risk.occurrenceDateTime,
immediate: horizonRisk(risk, 0),
five: horizonRisk(risk, 5),
}));
});
protected readonly daysBetween = daysBetween;
/** Her file as a PDF: identity, the route, history, tests and the risk scales, as on screen. */
protected async exportPatient(): Promise<void> {
const patient = this.patient();
if (!patient) return;
this.exporting.set(true);
this.exportError.set('');
try {
await firstValueFrom(this.http.get('/api/cacu/exports/capabilities'));
const route = this.route();
const inferred = (s?: { provenance?: string }) => s?.provenance === 'Inferida temporalmente';
const timeline = route.map((s, i) => ({
state: s.state,
label: s.label,
...(s.provenance ? { provenance: s.provenance } : {}),
...(s.date ? { date: s.date } : {}),
prev: intervalText(
i ? route[i - 1].date : undefined,
s.date,
inferred(s) || (i > 0 && inferred(route[i - 1])),
),
start: intervalText(route[0].date, s.date, inferred(s)),
}));
const lines = (s: (typeof route)[number], i: number) =>
`${s.label}: ${s.state}${s.provenance ? ' · ' + s.provenance : ''}; fecha ${s.date ?? '—'}; ` +
`desde anterior ${timeline[i].prev}; desde toma ${timeline[i].start}`;
const entries: string[][] = [
['Identificador', patient.id ?? 'No disponible'],
['Paciente', patientLabel(patient)],
['CURP', this.identity().curp ?? 'No disponible'],
['Expedientes', this.identity().numbers.join(', ') || 'No disponible'],
['Nacimiento', patient.birthDate ?? 'No disponible'],
['Edad al corte', String(this.age() ?? 'No disponible')],
['Estatus', this.status() || 'No disponible'],
...route.map((s, i) => ['Etapa', lines(s, i)]),
...this.history().map((h) => [
'Historial',
`${h.date} · ${h.kind} · ${h.text}${h.code && h.code !== h.text ? ' (' + h.code + ')' : ''}`,
]),
...this.tests().map((t) => [
'Pruebas',
`${t.date} · ${t.kind} · ${t.reported ?? 'Pendiente'} · ${t.results.join(' · ') || '—'}`,
]),
];
const percent = (n: number) => `${(n * 100).toFixed(2)} %`;
const scale = (model: string, horizon: string, v: ReturnType<typeof horizonRisk>) => ({
label: `${model} · ${horizon}: ${v ? percent(v.value) : 'No disponible'}`,
outcome: model,
model,
horizon,
...(v
? {
value: v.value,
...(v.low !== undefined && v.high !== undefined ? { low: v.low, high: v.high } : {}),
}
: {}),
});
const scales = this.riskScales().flatMap((r) => [
scale(r.model, 'Inmediato', r.immediate),
scale(r.model, '5 años', r.five),
]);
for (const s of scales) entries.push(['Riesgo', s.label]);
if (!scales.length)
entries.push(['Riesgo', 'Inmediato: No disponible · 5 años: No disponible']);
await downloadDocument(this.http, 'pdf', {
title: 'Ficha individual',
parameters: [
['Corte (edad, estatus y etapas)', this.cutoff()],
[
'Historial y riesgos',
'Información longitudinal disponible; no filtrada por corte histórico',
],
],
columns: ['Sección', 'Información'],
rows: entries,
timeline,
risk_scales: scales.length
? scales
: [
{ label: 'Riesgo inmediato: No disponible' },
{ label: 'Riesgo a 5 años: No disponible' },
],
});
} catch (error) {
this.exportError.set(
error instanceof Error
? `No se pudo generar la ficha PDF: ${error.message}`
: 'No se pudo generar la ficha PDF.',
);
} finally {
this.exporting.set(false);
}
}
protected readonly identity = computed(() => {
const p = this.patient();
return {
name: p?.name?.[0]?.text,
name: patientName(p),
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(() => {
+24
View File
@@ -0,0 +1,24 @@
import type { RiskAssessment } from 'fhir/r4';
/** Only an explicitly published horizon is eligible; zero remains a real value. */
export function horizonRisk(risk: RiskAssessment, years: number) {
const p = (risk.prediction ?? []).find(
(x) =>
x.whenRange?.high?.value === years &&
x.whenRange.high.code === 'a' &&
x.probabilityDecimal !== undefined &&
x.probabilityDecimal >= 0 &&
x.probabilityDecimal <= 1,
);
if (!p) return undefined;
const value = p.probabilityDecimal!;
const get = (suffix: string) =>
p.extension?.find((e) => e.url.endsWith('/' + suffix))?.valueDecimal;
const low = get('ic-bajo'),
high = get('ic-alto');
return {
value,
low: low !== undefined && low >= 0 && low <= 1 ? low : undefined,
high: high !== undefined && high >= 0 && high <= 1 ? high : undefined,
};
}
+54
View File
@@ -0,0 +1,54 @@
import '@angular/compiler';
import { describe, expect, it } from 'vitest';
import type { RiskAssessment } from 'fhir/r4';
import { daysBetween, intervalText, stages } from './stages';
import { horizonRisk } from './risk-scale';
describe('stages and explicit risk horizons', () => {
it('keeps zero day intervals and does not fill later stages', () => {
const s = stages('2026-01-01', '2026-01-01', '2026-02-01');
expect(daysBetween(s[0].date, s[1].date)).toBe(0);
expect(s.slice(2).every((x) => x.date === undefined)).toBe(true);
expect(stages('2026-01-01', '2027-01-01', '2026-02-01')[1].date).toBeUndefined();
});
it('distinguishes inferred, structured, pending and ambiguous stages', () => {
const a = stages('2026-01-01', undefined, '2026-02-01', {
colposcopy: { state: 'inferred', date: '2026-01-03' },
biopsy: { state: 'pending' },
diagnosis: { state: 'ambiguous' },
});
expect(a.map((x) => x.state)).toEqual([
'Registrada',
'Desconocida',
'Registrada',
'Pendiente',
'Ambigua',
]);
expect(a[2].provenance).toBe('Inferida temporalmente');
expect(
stages('2026-01-01', undefined, '2026-02-01', {
biopsy: { state: 'structured', date: '2026-01-04' },
})[3].provenance,
).toBe('Vínculo estructurado');
});
it('says an interval in days, marks an inferred one, and prints a dash for a missing date', () => {
expect(intervalText('2026-01-01', '2026-01-01')).toBe('0 días');
expect(intervalText('2026-01-01', '2026-01-04', true)).toBe('3 días (inferido)');
expect(intervalText(undefined, '2026-01-04')).toBe('—');
expect(intervalText('2026-01-05', '2026-01-04')).toBe('—');
});
it('uses only a published horizon and preserves zero', () => {
const r: RiskAssessment = {
resourceType: 'RiskAssessment',
status: 'final',
subject: {},
prediction: [
{ probabilityDecimal: 0, whenRange: { high: { value: 0, code: 'a' } } },
{ probabilityDecimal: 0.2, whenRange: { high: { value: 3, code: 'a' } } },
],
};
expect(horizonRisk(r, 0)?.value).toBe(0);
expect(horizonRisk(r, 5)).toBeUndefined();
expect(horizonRisk({ ...r, prediction: [] }, 0)).toBeUndefined();
});
});
+23
View File
@@ -0,0 +1,23 @@
<div class="stage-line" [class.detailed]="detail()" [attr.aria-label]="summary()">
@for (s of rows(); track s.label) {
<div class="stage">
<span
class="node"
[class.registered]="s.state === 'Registrada'"
[class.inferred]="s.inferred"
[class.pending]="s.state === 'Pendiente'"
[class.ambiguous]="s.state === 'Ambigua'"
[attr.title]="s.title"
></span>
@if (detail()) {
<div class="stage-detail">
<strong>{{ s.label }}</strong>
<span>{{ s.state }}{{ s.provenance ? ' · ' + s.provenance : '' }}</span>
<span>{{ s.date ?? 'Sin fecha' }}</span>
<span class="interval">Desde anterior: {{ s.sincePrevious }}</span>
<span class="interval">Desde toma: {{ sinceSample(s) }}</span>
</div>
}
</div>
}
</div>
+116
View File
@@ -0,0 +1,116 @@
:host {
display: block;
min-width: 150px;
}
.stage-line {
display: flex;
align-items: flex-start;
}
.stage {
position: relative;
flex: 0 0 37px;
}
.stage:not(:last-child)::after {
content: '';
position: absolute;
top: 9px;
left: 20px;
right: 0;
border-top: 1px solid #667b8a;
}
.stage:last-child {
flex-basis: 18px;
}
.node {
display: block;
width: 18px;
height: 18px;
box-sizing: border-box;
border: 2px dashed #667b8a;
border-radius: 50%;
background: white;
position: relative;
z-index: 1;
}
.registered {
background: #387b66;
border-style: solid;
}
.inferred {
background: #4269a0;
border-style: double;
}
.pending {
background: #fff1c9;
border-style: solid;
}
.ambiguous {
border-style: double;
border-color: #a84460;
}
/* The detailed panel: one column per milestone, across the whole width. */
.detailed {
background: #fff;
border: 1px solid #dce3e7;
border-radius: 8px;
padding: 18px 12px;
}
.detailed .stage,
.detailed .stage:last-child {
flex: 1;
min-width: 0;
text-align: center;
}
.detailed .node {
margin: 0 auto;
}
.detailed .stage:not(:last-child)::after {
left: calc(50% + 9px);
right: calc(-50% + 9px);
}
.stage-detail {
display: flex;
flex-direction: column;
gap: 3px;
padding: 8px 4px 0;
font-size: 12px;
color: #60717d;
overflow-wrap: anywhere;
}
.stage-detail strong {
color: #243d4b;
}
.interval {
font-weight: 600;
color: #365b69;
}
@media (max-width: 700px) {
.node {
flex: none;
}
.detailed {
display: block;
}
.detailed .stage {
display: flex;
gap: 12px;
padding-bottom: 10px;
text-align: left;
}
.detailed .stage::after {
top: 18px;
left: 9px;
bottom: 0;
right: auto;
border-top: 0;
border-left: 1px solid #667b8a;
}
.detailed .node {
margin: 0;
}
.stage-detail {
padding: 0;
}
}
+127
View File
@@ -0,0 +1,127 @@
import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4';
import { ext } from '../fhir';
export type StageFact = { state?: string; date?: string };
export type StageFacts = Record<string, StageFact>;
export function routeFacts(report?: DiagnosticReport): StageFacts {
return Object.fromEntries(
['colposcopy', 'biopsy', 'diagnosis'].map((k) => [
k,
{
state: ext(report, `stage-${k}-state`)?.valueCode,
date: ext(report, `stage-${k}-date`)?.valueDate,
},
]),
);
}
export function stages(sample?: string, report?: string, cutoff?: string, facts: StageFacts = {}) {
const valid = (d?: string) => !!d && !!cutoff && /^\d{4}-\d{2}-\d{2}$/.test(d) && d <= cutoff;
const start = valid(sample) ? sample : undefined;
const result = start && valid(report) && report! >= start ? report : undefined;
const later = (label: string, key: string) => {
const f = facts[key];
const state =
f?.state === 'pending'
? 'Pendiente'
: f?.state === 'ambiguous'
? 'Ambigua'
: (f?.state === 'inferred' || f?.state === 'structured') &&
valid(f.date) &&
start &&
f.date! >= start
? 'Registrada'
: 'Desconocida';
return {
label,
date: state === 'Registrada' ? f.date : undefined,
state,
provenance:
state === 'Registrada'
? f.state === 'inferred'
? 'Inferida temporalmente'
: 'Vínculo estructurado'
: undefined,
};
};
return [
{
label: 'Toma de muestra',
date: start,
state: start ? 'Registrada' : 'Desconocida',
provenance: undefined,
},
{
label: 'Resultado de citología',
date: result,
state: result ? 'Registrada' : 'Desconocida',
provenance: undefined,
},
later('Colposcopia', 'colposcopy'),
later('Reporte de biopsia', 'biopsy'),
later('Diagnóstico', 'diagnosis'),
];
}
export function daysBetween(a?: string, b?: string): number | undefined {
if (!a || !b) return undefined;
const x = Date.parse(a + 'T00:00:00Z'),
y = Date.parse(b + 'T00:00:00Z');
return Number.isFinite(x) && Number.isFinite(y) && y >= x ? (y - x) / 86400000 : undefined;
}
/** One stage as the screens say it, with the intervals the detailed panel prints. */
export interface StageRow {
label: string;
state: string;
provenance?: string;
date?: string;
inferred: boolean;
title: string;
/** "3 días", "3 días (inferido)" or "—": never a zero for a missing date */
sincePrevious: string;
}
/** Days between two stages as text; an interval that rests on an inferred stage says so. */
export function intervalText(from?: string, to?: string, inferred = false): string {
const days = daysBetween(from, to);
return days === undefined ? '—' : `${days} días${inferred ? ' (inferido)' : ''}`;
}
@Component({
selector: 'app-stages',
templateUrl: './stages.html',
styleUrl: './stages.scss',
})
export class Stages {
/** the cytology's sample day, its report day, and the day the route is known by */
readonly sample = input<string>();
readonly report = input<string>();
readonly cutoff = input<string>();
/** the detailed panel (milestones, states, dates, intervals) instead of the compact line */
readonly detail = input(false);
readonly facts = input<StageFacts>({});
protected readonly items = computed(() =>
stages(this.sample(), this.report(), this.cutoff(), this.facts()),
);
protected readonly rows = computed<StageRow[]>(() => {
const items = this.items();
const inferred = (x?: { provenance?: string }) => x?.provenance === 'Inferida temporalmente';
return items.map((s, i) => ({
...s,
inferred: inferred(s),
title: `${s.label}: ${s.state}${s.provenance ? ' · ' + s.provenance : ''}`,
sincePrevious: intervalText(
i ? items[i - 1].date : undefined,
s.date,
inferred(s) || (i > 0 && inferred(items[i - 1])),
),
}));
});
protected readonly summary = computed(() =>
this.rows()
.map((r) => r.title)
.join('; '),
);
protected sinceSample(row: StageRow): string {
return intervalText(this.items()[0].date, row.date, row.inferred);
}
}
+39 -7
View File
@@ -21,8 +21,45 @@ const LAYOUT: Partial<Plotly.Layout> = {
margin: { t: 24, r: 16, b: 48, l: 56 },
paper_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> = {
responsive: true,
displaylogo: false,
@@ -43,12 +80,7 @@ export class Plot implements OnDestroy {
constructor() {
effect(() => {
const { data, layout } = this.figure();
void Plotly.react(
this.host().nativeElement,
data as Plotly.Data[],
{ ...LAYOUT, ...layout },
CONFIG,
);
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG);
});
}
+57 -12
View File
@@ -1,8 +1,8 @@
<section class="page">
<h1>Revisión</h1>
<p class="subtitle">
Lo que la carga retuvo para que una persona decida. Cada decisión queda registrada y se aplica
en la siguiente ejecución.
Registros retenidos durante la carga que requieren una decisión. Cada decisión queda registrada
y se aplica en la siguiente ejecución.
</p>
@if (message()) {
<p class="message" role="status">{{ message() }}</p>
@@ -30,14 +30,14 @@
</tr>
</thead>
<tbody>
@for (row of held.value() ?? []; track row['_record']) {
@for (row of held.value() ?? []; track $index) {
<tr>
<td>{{ row['_pipeline'] }} · {{ row['_target'] }}</td>
<td>{{ reasons(row) }}</td>
<td>{{ said(row) }}</td>
<td class="values">
@for (v of values(row) | keyvalue; track v.key) {
<span
><b>{{ v.key }}</b
><b>{{ title(v.key) }}</b
>: {{ text(v.value) }}</span
>
}
@@ -84,7 +84,7 @@
</tr>
</thead>
<tbody>
@for (row of conflicts.value() ?? []; track row['_record']) {
@for (row of conflicts.value() ?? []; track $index) {
<tr>
<td>
<code>{{ text(row['person_id']).slice(0, 10) }}</code>
@@ -92,7 +92,7 @@
<td class="values">
@for (v of values(row) | keyvalue; track v.key) {
<span
><b>{{ v.key }}</b
><b>{{ title(v.key) }}</b
>: {{ text(v.value) }}</span
>
}
@@ -116,6 +116,51 @@
</table>
</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">
<div class="bar">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -158,7 +203,7 @@
@for (entry of p['to_settle']; track entry['person']) {
<div class="card person">
<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['birth_date']) }}
</div>
@@ -170,7 +215,7 @@
}}
· {{ text(c['full_name']) }} · {{ text(c['birth_date']) }})?
<span class="muted"
>{{ c['reason'] }}
>{{ candidateReason(c['reason']) }}
@if (c['probability'] !== null) {
· p = {{ $any(c['probability']) | number: '1.2-2' }}
}
@@ -194,13 +239,13 @@
}
</div>
} @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>
@for (entry of p['torn']; track entry['person']) {
<div class="card person">
@for (r of records(entry); track r['_record']) {
@for (r of records(entry); track $index) {
<div class="candidate">
<span class="values">
@for (v of values(r) | keyvalue; track v.key) {
@@ -239,7 +284,7 @@
}
</div>
} @empty {
<p class="muted">Nada que decidir.</p>
<p class="muted">Sin decisiones pendientes.</p>
}
}
</mat-tab>
+8
View File
@@ -46,3 +46,11 @@ h2 {
.small {
width: 160px;
}
.preview {
margin: 0;
max-height: 8em;
overflow: auto;
white-space: pre-wrap;
font-size: 12px;
}
+93
View File
@@ -15,6 +15,9 @@ import { conflicts } from '../api/fn/review/conflicts';
import { correct } from '../api/fn/review/correct';
import { decidePersons } from '../api/fn/review/decide-persons';
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 { reject } from '../api/fn/review/reject';
import { runStatus } from '../api/fn/runs/run-status';
@@ -46,6 +49,39 @@ const IDENTITY_FIELDS: Correction['field'][] = [
'birth_date',
'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. */
const HIDDEN = [
'_pipeline',
@@ -64,6 +100,7 @@ const HIDDEN = [
@Component({
selector: 'app-revision',
imports: [
Loading,
DecimalPipe,
KeyValuePipe,
FormsModule,
@@ -115,6 +152,20 @@ export class Revision {
: 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 decided = signal(new Set<string>());
protected readonly run = signal<string>('');
@@ -130,6 +181,48 @@ export class Revision {
const found = row['_held'];
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 {
return typeof value === 'object' && value !== null
? JSON.stringify(value)
+1 -1
View File
@@ -103,7 +103,7 @@ table.plain td {
border-bottom: 1px solid var(--color-border);
padding: 6px 8px;
text-align: left;
vertical-align: top;
vertical-align: middle;
}
table.plain th {