Compare commits

...

34 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 749afe765d CaMa: present diagnostic pathway and biopsy results 2026-12-01 12:27:16 -06:00
Roberto Treviño fe4dd55452 CaCu's page by readings, screening stages, ages and exports 2026-11-30 23:31:58 -06:00
Roberto Treviño 053679c817 Connecting a database no longer freezes the page: the columns field keeps one empty list 2026-11-30 05:17:14 -06:00
Roberto Treviño ffa732df12 The page test follows the pages as they are 2026-11-30 02:14:16 -06:00
Roberto Treviño 786b199203 The generated API client matches the API 2026-11-29 21:15:12 -06:00
Roberto Treviño ca887c29ab Wording: formal, precise, no narrative; the missing reports of a promotion in Spanish 2026-11-29 15:24:25 -06:00
Roberto Treviño bb506c3926 Conectar: Configuración and Avanzado tabs, rows instead of JSON, field titles as keys, captions that fit their nodes 2026-11-29 15:24:24 -06:00
Roberto Treviño b48c025400 Page test: no overlapping, clipped or wrapped labels at 1440 and 820 px 2026-11-29 12:39:07 -06:00
Roberto Treviño a93cd71126 Cosmetic pass: legends above plots, readable hovers and ticks, KPI qualifiers, a header that never wraps 2026-11-29 12:39:07 -06:00
Roberto Treviño 979b7cf34d Gobernanza: the header's domain switcher, model titles, confirmations, a stop button, an upload button 2026-11-29 12:39:07 -06:00
Roberto Treviño cde9b1cfb1 Revisión: documents no route recognises; reasons and fields in Spanish 2026-11-29 12:39:07 -06:00
Roberto Treviño edc32af67e CaMa record as the old card: summary, mammography, histopathology, prognosis, risk of death and its scenarios' risk factors 2026-11-29 12:39:07 -06:00
Roberto Treviño 2216186d26 Patient lists have a search box; TEA alterations by their Spanish names 2026-11-29 12:39:07 -06:00
Roberto Treviño 55c4e0b173 OpenAPI client: model titles, run termination, Patient name and identifier 2026-11-29 12:39:07 -06:00
Roberto Treviño 52cca0a84c Record history shows only ICD-10 codes beside a diagnosis 2026-11-29 07:13:57 -06:00
Roberto Treviño 7e50ff9b90 OpenAPI spec names the configured promotion reports and CaMa's history 2026-11-29 06:58:38 -06:00
Roberto Treviño ac1d8fc4fa Records show the server's names for coded results; risk lists say empty only once loaded 2026-11-29 06:43:10 -06:00
Roberto Treviño d09e8c59ed Proxy waits up to two minutes for the API 2026-11-29 01:32:09 -06:00
Roberto Treviño 4a8e2e22bd Name breast recurrences in Revisión 2026-11-29 01:06:40 -06:00
Roberto Treviño 1655d464e1 Regenerate the API client for breast recurrences 2026-11-28 23:05:21 -06:00
Roberto Treviño e275782198 Recurrence scenarios leave Gobernanza: the record draws them 2026-11-28 21:30:01 -06:00
Roberto Treviño 133092f8c8 Record: Relación con el ADOS-2 and Análisis de recurrencia; Gobernanza draws the association 2026-11-28 21:28:42 -06:00
Roberto Treviño 6ea54d6e6d Trazabilidad, Datos y definiciones and the risk lists as the old app: declared panels, old labels and order; page tests against the capture 2026-11-28 17:24:29 -06:00
Roberto Treviño cbec0d431e Governance figures spec: scenarios are drawn by the record 2026-11-28 17:16:25 -06:00
Roberto Treviño fd19fdaefa TEA record: Zonas más afectadas (head map and zones by deviation); survival scenarios leave Gobernanza 2026-11-28 17:15:43 -06:00
Roberto Treviño 20e26b847a Wizard page test waits for the cancelled dialog to close before saving 2026-11-28 16:05:21 -06:00
Roberto Treviño 37444a25a1 TEA record: ADOS-2 by item, EEG quality and its alterations against the age norm; page tests follow the cards' and dialog's words 2026-11-28 13:29:23 -06:00
Roberto Treviño cb0403affb TEA Análisis de Riesgo as the old page: its filters, the EEG summary of the filtered children and their list; the domain's full name; reports that fail to load can be retried 2026-11-28 10:47:22 -06:00
Roberto Treviño aeb2d4ec84 TEA Indicadores as the old page: the period summary in words, the three timeliness boxes, counts and age-group figures; tab named Resumen 2026-11-28 10:26:24 -06:00
Roberto Treviño 3e096dd03f CaMa Indicadores as the old page: its cards, timeliness boxes with pending ones, BI-RADS 4–6 donuts, malignancy by BI-RADS and the biopsy donut, the confirmation card; page definitions apart from figure builders 2026-11-28 10:09:30 -06:00
Roberto Treviño 9a15ac6fcb CaCu Indicadores as the old page: its cards and words, the route, cytology and biopsy donuts, results by clinical scenario, confirmation rates; the page test compares with the capture; the guard injects before it waits 2026-11-28 10:03:31 -06:00
Roberto Treviño 198aae59da Conectar dialog by kind of source; plain-language canvas; login page and guard; loading indicators as the old app; survival curves of her clinical scenarios in the CaMa record 2026-11-28 09:30:00 -06:00
Roberto Treviño cc22840c3c Client for otherwise routes and unrecognised documents 2026-11-27 19:17:49 -06:00
Roberto Treviño 672091d19a Client for extract fields taken from columns 2026-11-27 16:25:01 -06:00
133 changed files with 11921 additions and 529 deletions
+69
View File
@@ -0,0 +1,69 @@
import { expect, test } from '@playwright/test';
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page,
}) => {
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
+122
View File
@@ -0,0 +1,122 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+263 -13
View File
@@ -1,4 +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[] {
@@ -9,6 +11,32 @@ function watch(page: Page): string[] {
return problems;
}
// The pages show only to someone signed in (the API itself answers everyone).
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
});
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
await page.goto('/conectar');
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page).toHaveURL(/\/conectar$/);
await page.getByRole('button', { name: 'Cuenta' }).click();
await page.getByRole('menuitem', { name: 'Salir' }).click();
await expect(page).toHaveURL(/\/login/);
await page.close();
});
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page,
}) => {
@@ -24,14 +52,17 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population',
).count;
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(String(count));
// the card says it as the old one did: "<n> pacientes"
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
`${count.toLocaleString('es-MX')} pacientes`,
);
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14);
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14);
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
@@ -42,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')).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
@@ -54,13 +85,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
expect(problems).toEqual([]);
});
@@ -71,13 +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 · Patients').click();
await expect(page.locator('formly-form')).toBeVisible();
// a node's caption: its kind, then its name
await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Mapear · cytology', { exact: true }).click();
await expect(page.getByText('Códigos del sitio')).toBeVisible();
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(() =>
page
@@ -90,7 +126,9 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
expect(problems).toEqual([]);
});
test('revision: what the hospital source holds, and a decision through the page', async ({ page }) => {
test('revision: what the hospital source holds, and a decision through the page', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click();
@@ -107,12 +145,224 @@ 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([]);
});
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
page,
}) => {
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
const problems = watch(page);
await page.goto('/conectar');
await page.getByLabel('Nueva canalización').fill('asistente');
await page.getByLabel('Nueva canalización').press('Enter');
await page.getByRole('button', { name: 'Fuente de datos' }).click();
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
await page.locator('[data-type="sqlserver"]').click();
await page.locator('[data-field="host"]').fill(site.hostname);
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
await page.locator('mat-select[data-field="table"]').click();
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
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.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');
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
await page.getByRole('button', { name: 'Cancelar' }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
expect(problems).toEqual([]);
});
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
* opportunity section on, in order, and the kind of each plot (its traces' types). */
function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
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
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ server {
root /usr/share/nginx/html;
location /api/ {
proxy_pass http://api:8000/;
proxy_read_timeout 30s;
proxy_read_timeout 120s;
}
location / {
try_files $uri $uri/ /index.html;
+2229 -65
View File
File diff suppressed because it is too large Load Diff
+285 -2
View File
@@ -25,9 +25,11 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
},
"devDependencies": {
"@angular/build": "^22.3.0",
@@ -38,6 +40,7 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
@@ -2402,6 +2405,30 @@
"@ngx-formly/core": "11.2.0"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.158.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
@@ -3465,6 +3492,12 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
@@ -3570,6 +3603,37 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/node": {
"version": "26.6.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/pdfkit": {
"version": "0.17.7",
"resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz",
"integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/pdfmake": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@types/pdfmake/-/pdfmake-0.3.5.tgz",
"integrity": "sha512-AQI4ISWzt7qmnKaipkikibz9x2XIvU/1zqfEHwKhBU7vP6oIhlGoLB9KsSIAryH7f9uuJebXScldb6F4ebwFxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/pdfkit": "*"
}
},
"node_modules/@types/plotly.js": {
"version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
@@ -3816,6 +3880,15 @@
"node": ">=12"
}
},
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.39",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz",
@@ -3891,6 +3964,35 @@
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": {
"version": "4.29.6",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
@@ -4119,6 +4221,15 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/colorjs.io": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz",
@@ -4326,6 +4437,12 @@
"node": ">=8"
}
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
@@ -4561,7 +4678,6 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-string-truncated-width": {
@@ -4626,6 +4742,12 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/flru": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -4636,6 +4758,23 @@
"node": ">=6"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/fs-extra": {
"version": "11.4.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
@@ -5366,6 +5505,16 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": {
"version": "11.4.1",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz",
@@ -5844,6 +5993,12 @@
"@oxc-parser/binding-win32-x64-msvc": "0.158.0"
}
},
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
@@ -5922,6 +6077,34 @@
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/pdfmake": {
"version": "0.3.14",
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
"license": "MIT",
"dependencies": {
"linebreak": "^1.1.0",
"pdfkit": "^0.20.2",
"xmldoc": "^2.0.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -5990,6 +6173,14 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT"
},
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": {
"version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6165,6 +6356,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz",
@@ -6663,6 +6860,15 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -6852,6 +7058,12 @@
"node": ">=16.0.0"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
@@ -6979,6 +7191,53 @@
"node": ">=22.19.0"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -7676,6 +7935,18 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -7693,6 +7964,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/xxhash-wasm": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+4 -1
View File
@@ -29,9 +29,11 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
},
"devDependencies": {
"@angular/build": "^22.3.0",
@@ -42,6 +44,7 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
+32
View File
@@ -0,0 +1,32 @@
/* 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 { Login } from '../../models/login';
export interface AuthCookieLogin$Params {
body: Login
}
export function authCookieLogin(http: HttpClient, rootUrl: string, params: AuthCookieLogin$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, authCookieLogin.PATH, 'post');
if (params) {
rb.body(params.body, 'application/x-www-form-urlencoded');
}
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>;
})
);
}
authCookieLogin.PATH = '/auth/login';
+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 AuthCookieLogout$Params {
}
export function authCookieLogout(http: HttpClient, rootUrl: string, params?: AuthCookieLogout$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, authCookieLogout.PATH, 'post');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
authCookieLogout.PATH = '/auth/logout';
+18
View File
@@ -24,6 +24,21 @@ 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);
/**
* gt, ge, lt or le and a day (2000-12-31)
*/
birthdate?: Array<string>;
/**
* -recent or -risk-<outcome>
*/
@@ -56,6 +71,9 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-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('birthdate', params.birthdate, {});
rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {});
+32
View File
@@ -0,0 +1,32 @@
/* 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 { Browsed } from '../../models/browsed';
export interface Browse$Params {
path?: (string | null);
}
export function browse(http: HttpClient, rootUrl: string, params?: Browse$Params, context?: HttpContext): Observable<StrictHttpResponse<Browsed>> {
const rb = new RequestBuilder(rootUrl, browse.PATH, 'get');
if (params) {
rb.query('path', params.path, {});
}
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<Browsed>;
})
);
}
browse.PATH = '/ingest/sources/browse';
+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 { SignIn } from '../../models/sign-in';
export interface OauthStart$Params {
provider: string;
origin: string;
}
export function oauthStart(http: HttpClient, rootUrl: string, params: OauthStart$Params, context?: HttpContext): Observable<StrictHttpResponse<SignIn>> {
const rb = new RequestBuilder(rootUrl, oauthStart.PATH, 'get');
if (params) {
rb.path('provider', params.provider, {});
rb.query('origin', params.origin, {});
}
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<SignIn>;
})
);
}
oauthStart.PATH = '/ingest/sources/oauth/{provider}/start';
+30
View File
@@ -0,0 +1,30 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Catalog } from '../../models/catalog';
export interface SourceTypes$Params {
}
export function sourceTypes(http: HttpClient, rootUrl: string, params?: SourceTypes$Params, context?: HttpContext): Observable<StrictHttpResponse<Catalog>> {
const rb = new RequestBuilder(rootUrl, sourceTypes.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<Catalog>;
})
);
}
sourceTypes.PATH = '/ingest/sources/types';
+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';
import { Answers } from '../../models/answers';
import { Tested } from '../../models/tested';
export interface TestSource$Params {
limit?: number;
body: Answers
}
export function testSource(http: HttpClient, rootUrl: string, params: TestSource$Params, context?: HttpContext): Observable<StrictHttpResponse<Tested>> {
const rb = new RequestBuilder(rootUrl, testSource.PATH, 'post');
if (params) {
rb.query('limit', params.limit, {});
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<Tested>;
})
);
}
testSource.PATH = '/ingest/sources/test';
+3 -6
View File
@@ -8,14 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyUpload } from '../../models/body-upload';
import { Uploaded } from '../../models/uploaded';
export interface Upload$Params {
body: BodyUpload
}
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<Uploaded>> {
const rb = new RequestBuilder(rootUrl, upload.PATH, 'post');
if (params) {
rb.body(params.body, 'multipart/form-data');
@@ -26,9 +25,7 @@ export function upload(http: HttpClient, rootUrl: string, params: Upload$Params,
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
return r as StrictHttpResponse<Uploaded>;
})
);
}
+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>>;
})
);
}
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+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 Unrecognised$Params {
pipeline: string;
}
export function unrecognised(http: HttpClient, rootUrl: string, params: Unrecognised$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
[key: string]: any;
}>>> {
const rb = new RequestBuilder(rootUrl, unrecognised.PATH, 'get');
if (params) {
rb.query('pipeline', params.pipeline, {});
}
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<Array<{
[key: string]: any;
}>>;
})
);
}
unrecognised.PATH = '/review/unrecognised';
+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';
+33
View File
@@ -0,0 +1,33 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { UserCreate } from '../../models/user-create';
import { UserRead } from '../../models/user-read';
export interface RegisterRegister$Params {
body: UserCreate
}
export function registerRegister(http: HttpClient, rootUrl: string, params: RegisterRegister$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, registerRegister.PATH, 'post');
if (params) {
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<UserRead>;
})
);
}
registerRegister.PATH = '/users/register';
@@ -0,0 +1,30 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { UserRead } from '../../models/user-read';
export interface UsersCurrentUser$Params {
}
export function usersCurrentUser(http: HttpClient, rootUrl: string, params?: UsersCurrentUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersCurrentUser.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<UserRead>;
})
);
}
usersCurrentUser.PATH = '/users/me';
+31
View File
@@ -0,0 +1,31 @@
/* 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 UsersDeleteUser$Params {
id: string;
}
export function usersDeleteUser(http: HttpClient, rootUrl: string, params: UsersDeleteUser$Params, context?: HttpContext): Observable<StrictHttpResponse<void>> {
const rb = new RequestBuilder(rootUrl, usersDeleteUser.PATH, 'delete');
if (params) {
rb.path('id', params.id, {});
}
return http.request(
rb.build({ responseType: 'text', accept: '*/*', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return (r as HttpResponse<any>).clone({ body: undefined }) as StrictHttpResponse<void>;
})
);
}
usersDeleteUser.PATH = '/users/{id}';
@@ -0,0 +1,33 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { UserRead } from '../../models/user-read';
import { UserUpdate } from '../../models/user-update';
export interface UsersPatchCurrentUser$Params {
body: UserUpdate
}
export function usersPatchCurrentUser(http: HttpClient, rootUrl: string, params: UsersPatchCurrentUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersPatchCurrentUser.PATH, 'patch');
if (params) {
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<UserRead>;
})
);
}
usersPatchCurrentUser.PATH = '/users/me';
+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';
import { UserRead } from '../../models/user-read';
import { UserUpdate } from '../../models/user-update';
export interface UsersPatchUser$Params {
id: string;
body: UserUpdate
}
export function usersPatchUser(http: HttpClient, rootUrl: string, params: UsersPatchUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersPatchUser.PATH, 'patch');
if (params) {
rb.path('id', params.id, {});
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<UserRead>;
})
);
}
usersPatchUser.PATH = '/users/{id}';
+32
View File
@@ -0,0 +1,32 @@
/* 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 { UserRead } from '../../models/user-read';
export interface UsersUser$Params {
id: string;
}
export function usersUser(http: HttpClient, rootUrl: string, params: UsersUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersUser.PATH, 'get');
if (params) {
rb.path('id', params.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<UserRead>;
})
);
}
usersUser.PATH = '/users/{id}';
+28
View File
@@ -1,6 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth/auth-cookie-login';
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 { 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';
@@ -23,10 +27,18 @@ export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
export { startRun as startRun } from './fn/ingest/start-run';
export type { Schema$Params as Schema$Params } from './fn/ingest/schema';
export { schema as schema } from './fn/ingest/schema';
export type { Browse$Params as Browse$Params } from './fn/ingest/browse';
export { browse as browse } from './fn/ingest/browse';
export type { OauthStart$Params as OauthStart$Params } from './fn/ingest/oauth-start';
export { oauthStart as oauthStart } from './fn/ingest/oauth-start';
export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
export { sourcePreview as sourcePreview } from './fn/ingest/source-preview';
export type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
export { sourceResources as sourceResources } from './fn/ingest/source-resources';
export type { TestSource$Params as TestSource$Params } from './fn/ingest/test-source';
export { testSource as testSource } from './fn/ingest/test-source';
export type { SourceTypes$Params as SourceTypes$Params } from './fn/ingest/source-types';
export { sourceTypes as sourceTypes } from './fn/ingest/source-types';
export type { Upload$Params as Upload$Params } from './fn/ingest/upload';
export { upload as upload } from './fn/ingest/upload';
export type { Models$Params as Models$Params } from './fn/models/models';
@@ -59,12 +71,28 @@ export type { DecidePersons$Params as DecidePersons$Params } from './fn/review/d
export { decidePersons as decidePersons } from './fn/review/decide-persons';
export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject';
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { 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';
export { study as study } from './fn/eeg/study';
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
export { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user';
export type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
export { usersPatchCurrentUser as usersPatchCurrentUser } from './fn/users/users-patch-current-user';
export type { RegisterRegister$Params as RegisterRegister$Params } from './fn/users/register-register';
export { registerRegister as registerRegister } from './fn/users/register-register';
export type { UsersUser$Params as UsersUser$Params } from './fn/users/users-user';
export { usersUser as usersUser } from './fn/users/users-user';
export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/users/users-delete-user';
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
+22
View File
@@ -2,30 +2,52 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Analysis } from './models/analysis';
export type { Answers } from './models/answers';
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
export type { BodyUpload } from './models/body-upload';
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 { Domain } from './models/domain';
export type { Entry } from './models/entry';
export type { ErrorModel } from './models/error-model';
export type { Extract } from './models/extract';
export type { Fhir } from './models/fhir';
export type { FieldSpec } from './models/field-spec';
export type { Group } from './models/group';
export type { Guided } from './models/guided';
export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join';
export type { Link } from './models/link';
export type { Listing } from './models/listing';
export type { Login } from './models/login';
export type { Map } from './models/map';
export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
export type { Position } from './models/position';
export type { Provider } from './models/provider';
export type { Read } from './models/read';
export type { Rejection } from './models/rejection';
export type { Relation } from './models/relation';
export type { Route } from './models/route';
export type { RunRequest } from './models/run-request';
export type { SavedPipeline } from './models/saved-pipeline';
export type { SignIn } from './models/sign-in';
export type { Site } from './models/site';
export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type';
export type { Study } from './models/study';
export type { Target } from './models/target';
export type { Tested } from './models/tested';
export type { Training } from './models/training';
export type { Uploaded } from './models/uploaded';
export type { UserCreate } from './models/user-create';
export type { UserRead } from './models/user-read';
export type { UserUpdate } from './models/user-update';
export type { ValidationError } from './models/validation-error';
export type { Version } from './models/version';
+2
View File
@@ -2,10 +2,12 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Metric } from '../models/metric';
import { Relation } from '../models/relation';
export interface Analysis {
age_months: (number | null);
id: string;
level: (string | null);
metrics: Array<Metric>;
relation?: Array<Relation>;
valid: (boolean | null);
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Answers {
answers?: {
[key: string]: any;
};
node?: (string | null);
pipeline?: (string | null);
type: string;
}
+2 -1
View File
@@ -2,5 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUpload {
file: string;
files: Array<string>;
folder?: (string | null);
}
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Entry } from '../models/entry';
export interface Browsed {
entries: Array<Entry>;
parent: (string | null);
path: (string | null);
}
+19
View File
@@ -0,0 +1,19 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Group } from '../models/group';
import { Option } from '../models/option';
import { Provider } from '../models/provider';
import { SourceType } from '../models/source-type';
export interface Catalog {
formats: Array<Option>;
groups: {
[key: string]: Group;
};
providers: {
[key: string]: Provider;
};
types: {
[key: string]: SourceType;
};
}
+8
View File
@@ -2,7 +2,15 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Condition {
/**
* Por ejemplo «text», el texto leído del documento.
*/
column: string;
op: 'equals' | 'contains' | 'matches' | 'present';
/**
* Lo que se busca; por ejemplo «citología».
*/
value?: string;
}
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Entry {
kind: 'folder' | 'file';
name: string;
path: string;
size?: (number | null);
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface ErrorModel {
detail: (string | {
[key: string]: string;
});
}
+24 -1
View File
@@ -13,17 +13,40 @@ import { Position } from '../models/position';
*/
export interface Extract {
column: (string | Array<string>);
/**
* Dato → columna, sin leer el texto.
*/
columns?: {
[key: string]: string;
};
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
/**
* Para el modelo de lenguaje.
*/
hints?: string;
id: string;
inputs?: Array<string>;
kind?: 'extract';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
method?: 'auto' | 'llm' | 'patterns';
/**
* Dato → expresión con un grupo ( ).
*/
patterns?: {
[key: string]: string;
};
+5 -1
View File
@@ -11,10 +11,14 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'fhir';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+15
View File
@@ -0,0 +1,15 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Option } from '../models/option';
export interface FieldSpec {
advanced?: boolean;
default?: any;
help?: string;
label: string;
options?: Array<Option>;
placeholder?: string;
provider?: (string | null);
required?: boolean;
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format' | 'columns';
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Group {
description: string;
title: string;
}
+14
View File
@@ -0,0 +1,14 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* How the Conectar dialog drew a source: its type (core.sources) and the answers given.
* The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none.
*/
export interface Guided {
answers?: {
[key: string]: any;
};
type: string;
}
+8
View File
@@ -11,7 +11,15 @@ export interface Join {
id: string;
inputs?: Array<string>;
kind?: 'join';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
/**
* Columna de la primera entrada = columna de la segunda.
*/
on: Array<[string, string]>;
position?: (Position | null);
}
+12
View File
@@ -16,8 +16,20 @@ export interface Link {
id: string;
inputs?: Array<string>;
kind?: 'link';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Parecidos por encima de esto los ve un revisor.
*/
review?: number;
/**
* Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).
*/
rules?: Array<string>;
}
+15
View File
@@ -0,0 +1,15 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* What "Probar conexión" shows: a database's tables (the resources of `source`, built
* from `args`), or the first rows the type's own node reads (files, records).
*/
export interface Listing {
args?: {
[key: string]: any;
};
kind: 'tables' | 'rows';
source?: (string | null);
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Login {
client_id?: (string | null);
client_secret?: (string | null);
grant_type?: (string | null);
password: string;
scope?: string;
username: string;
}
+20
View File
@@ -8,18 +8,38 @@ import { Position } from '../models/position';
* (core.concept_map), and its date formats.
*/
export interface Map {
/**
* La tabla de códigos del sitio.
*/
concept_map?: (string | null);
/**
* Dato de la plataforma → columna del sitio.
*/
fields: {
[key: string]: string;
};
/**
* Por ejemplo %d/%m/%Y.
*/
formats?: {
[key: string]: string;
};
id: string;
inputs?: Array<string>;
kind?: 'map';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Un dato igual para todas las filas.
*/
values?: {
[key: string]: string;
};
+6
View File
@@ -1,10 +1,16 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric {
code: string;
electrodes?: Array<Site>;
median?: (number | null);
model: (string | null);
outside: (number | null);
p5?: (number | null);
p95?: (number | null);
value: number;
z: (number | null);
zones?: Array<Site>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Model {
name: string;
title: string;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Option {
label: string;
value: any;
}
+17
View File
@@ -0,0 +1,17 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* A sign-in button's OAuth 2.0 provider (authorization code flow).
*/
export interface Provider {
authorize_params?: {
[key: string]: string;
};
authorize_url: string;
env: string;
scope: string;
title: string;
token_url: string;
}
+8
View File
@@ -7,10 +7,18 @@ import { Position } from '../models/position';
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
*/
export interface Read {
/**
* Donde la entrada trae cada documento.
*/
column: string;
id: string;
inputs?: Array<string>;
kind?: 'read';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
+25
View File
@@ -0,0 +1,25 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
+13 -2
View File
@@ -5,13 +5,24 @@ import { Condition } from '../models/condition';
import { Position } from '../models/position';
/**
* Only the rows where every condition holds (e.g. reports titled "Citología").
* Only the rows where every condition holds (e.g. reports titled "Citología"). An
* `otherwise` route takes the rows of its input that none of the other routes on that
* input take (documents nobody recognises, for a reviewer), then its own conditions.
*/
export interface Route {
id: string;
inputs?: Array<string>;
kind?: 'route';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
/**
* Recoge lo que nadie reconoce, para revisarlo.
*/
otherwise?: boolean;
position?: (Position | null);
when: Array<Condition>;
when?: Array<Condition>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface SignIn {
state: string;
url: string;
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Site {
site: string;
value: number;
z: (number | null);
}
+22
View File
@@ -0,0 +1,22 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { FieldSpec } from '../models/field-spec';
import { Listing } from '../models/listing';
export interface SourceType {
args?: {
[key: string]: any;
};
description: string;
fields: {
[key: string]: FieldSpec;
};
group: string;
icon: string;
listing?: (Listing | null);
primary_key?: Array<string>;
resource?: (string | null);
source: string;
then?: (string | null);
title: string;
}
+26
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Guided } from '../models/guided';
import { Position } from '../models/position';
/**
@@ -8,16 +9,41 @@ import { Position } from '../models/position';
* own primary key or `primary_key`; replaced whole when it has none.
*/
export interface Source {
/**
* Los de la fuente dlt.
*/
args?: {
[key: string]: any;
};
guided?: (Guided | null);
id: string;
inputs?: Array<string>;
kind?: 'source';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Columnas que identifican una fila.
*/
primary_key?: Array<string>;
/**
* Cuál, si la fuente ofrece varios (una tabla).
*/
resource?: (string | null);
/**
* Módulo:función de la fuente dlt.
*/
source: string;
/**
* Transformador dlt para los archivos.
*/
then?: (string | null);
}
+9 -1
View File
@@ -8,10 +8,18 @@ import { Position } from '../models/position';
* one `link` node among the inputs. Rule breaks are held for review.
*/
export interface Target {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
/**
* En qué estudio de la plataforma se guarda.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'target';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+12
View File
@@ -0,0 +1,12 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Tested {
detail?: (string | null);
message: string;
ok: boolean;
rows?: Array<{
[key: string]: any;
}>;
tables?: Array<string>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Uploaded {
bucket_url: string;
files: Array<string>;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserCreate {
domains?: Array<Domain>;
email: string;
is_active?: (boolean | null);
is_superuser?: (boolean | null);
is_verified?: (boolean | null);
name?: string;
password: string;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserRead {
domains?: Array<Domain>;
email: string;
id: string;
is_active?: boolean;
is_superuser?: boolean;
is_verified?: boolean;
name?: string;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserUpdate {
domains?: (Array<Domain> | null);
email?: (string | null);
is_active?: (boolean | null);
is_superuser?: (boolean | null);
is_verified?: (boolean | null);
name?: (string | null);
password?: (string | null);
}
+21 -8
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,18 +18,29 @@
</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 {
<span class="title"></span>
}
<nav class="sections" aria-label="Secciones">
<a routerLink="/indicadores/cacu" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
</nav>
@if (!onLogin()) {
<nav class="sections" aria-label="Secciones">
<a [routerLink]="home()" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
</nav>
@if (auth.user(); as u) {
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
<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>
<button mat-menu-item (click)="logout()"><mat-icon>logout</mat-icon> Salir</button>
</mat-menu>
}
}
</header>
<main class="main">
+32 -15
View File
@@ -1,21 +1,38 @@
import { Routes } from '@angular/router';
import { domainAllowed, signedIn } from './auth/auth';
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{ path: 'login', loadComponent: () => import('./auth/login').then((m) => m.Login) },
{
path: 'indicadores/:domain',
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
path: '',
canActivateChild: [signedIn],
children: [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{
path: 'indicadores/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
},
{
path: 'indicadores/:domain/pacientes/:id',
canActivate: [domainAllowed],
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
},
{
path: 'conectar',
loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar),
},
{
path: 'revision',
loadComponent: () => import('./revision/revision').then((m) => m.Revision),
},
{ path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
{
path: 'gobernanza/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
},
{ path: '**', redirectTo: 'indicadores/cacu' },
],
},
{
path: 'indicadores/:domain/pacientes/:id',
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
},
{ path: 'conectar', loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar) },
{ path: 'revision', loadComponent: () => import('./revision/revision').then((m) => m.Revision) },
{ path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
{
path: 'gobernanza/:domain',
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
},
{ path: '**', redirectTo: 'indicadores/cacu' },
];
+43 -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,8 +79,38 @@
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 {
color: var(--color-text-secondary);
font-weight: 600;
}
+20 -6
View File
@@ -8,11 +8,12 @@ import { filter, map } from 'rxjs';
import { Api } from './api/api';
import { domains } from './api/fn/operations/domains';
import { Domain } from './api/models/domain';
import { Auth } from './auth/auth';
export const DOMAINS: Record<Domain, string> = {
cacu: 'Cáncer cervicouterino',
cama: 'Cáncer de mama',
tea: 'TEA',
tea: 'Trastorno del espectro autista',
};
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
@@ -32,6 +33,7 @@ export const DOMAINS: Record<Domain, string> = {
export class App {
private readonly api = inject(Api);
private readonly router = inject(Router);
protected readonly auth = inject(Auth);
protected readonly labels = DOMAINS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly url = toSignal(
@@ -41,11 +43,23 @@ 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.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
);
/** The sign-in page shows only the brand. */
protected readonly onLogin = computed(() => this.url().startsWith('/login'));
/** Where "Indicadores" goes: the first domain this user may see. */
protected readonly home = computed(
() => `/indicadores/${this.auth.user()?.domains[0] ?? 'cacu'}`,
);
protected async logout(): Promise<void> {
await this.auth.logout();
await this.router.navigateByUrl('/login');
}
}
+82
View File
@@ -0,0 +1,82 @@
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Injectable, computed, inject, signal } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import type { Domain } from '../api/models/domain';
/** Who is signed in, and the domains the app shows them. */
export interface User {
id: string;
email: string;
name: string;
is_superuser: boolean;
domains: Domain[];
}
/** The web app's sign-in (the API's fastapi-users, a session cookie). It decides only what
* the app shows: the API answers without a session. */
@Injectable({ providedIn: 'root' })
export class Auth {
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
/** undefined: not asked yet; null: nobody signed in. */
private readonly current = signal<User | null | undefined>(undefined);
readonly user = this.current.asReadonly();
readonly signedIn = computed(() => !!this.current());
/** Whether the signed-in user may see the domain (an administrator sees every one). */
canSee(domain: string): boolean {
const u = this.current();
return !!u && (u.is_superuser || u.domains.includes(domain as Domain));
}
async load(): Promise<User | null> {
try {
this.current.set(await firstValueFrom(this.http.get<User>(`${this.root}/users/me`)));
} catch {
this.current.set(null);
}
return this.current() ?? null;
}
/** Signs in; a wrong user or password comes back as words for the form. */
async login(email: string, password: string): Promise<string | null> {
const body = new HttpParams().set('username', email.trim()).set('password', password);
try {
await firstValueFrom(this.http.post(`${this.root}/auth/login`, body));
} catch (e) {
if (e instanceof HttpErrorResponse && e.status === 400) {
return 'Usuario o contraseña incorrectos.';
}
return 'No hay conexión con la plataforma. Intente de nuevo.';
}
await this.load();
return null;
}
async logout(): Promise<void> {
try {
await firstValueFrom(this.http.post(`${this.root}/auth/logout`, null));
} finally {
this.current.set(null);
}
}
}
/** Pages show only to someone signed in; the others go to the sign-in page and come back. */
export const signedIn: CanActivateFn = async (_route, state) => {
const auth = inject(Auth);
const router = inject(Router); // before any await: inject works only in the guard's first turn
const user = auth.user() === undefined ? await auth.load() : auth.user();
return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
};
/** A domain's pages show only to whom may see it. */
export const domainAllowed: CanActivateFn = (route) => {
const auth = inject(Auth);
const domain = route.paramMap.get('domain');
if (!domain || auth.canSee(domain)) return true;
const first = auth.user()?.domains[0];
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
};
+49
View File
@@ -0,0 +1,49 @@
<section class="login" aria-labelledby="login-title">
<div class="box">
<img class="logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
<h1 class="title" id="login-title">Inicio de sesión</h1>
<form class="form" (ngSubmit)="enter()" novalidate>
<mat-form-field appearance="outline" class="field" subscriptSizing="dynamic">
<input
matInput
name="email"
[(ngModel)]="email"
placeholder="Usuario"
aria-label="Usuario"
autocomplete="username"
autocapitalize="none"
spellcheck="false"
/>
</mat-form-field>
<mat-form-field appearance="outline" class="field" subscriptSizing="dynamic">
<input
matInput
name="password"
[(ngModel)]="password"
[type]="show() ? 'text' : 'password'"
placeholder="Contraseña"
aria-label="Contraseña"
autocomplete="current-password"
/>
<button
mat-icon-button
matSuffix
type="button"
class="eye"
(click)="show.set(!show())"
[attr.aria-label]="show() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="show()"
>
<mat-icon>{{ show() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</mat-form-field>
@if (error(); as message) {
<p class="error" role="alert">{{ message }}</p>
}
<button type="submit" class="enter" [disabled]="!email.trim() || !password || sending()">
{{ sending() ? 'Ingresando…' : 'Ingresar' }}
</button>
</form>
<p class="legal">©{{ year }} Todos los derechos reservados.</p>
</div>
</section>
+141
View File
@@ -0,0 +1,141 @@
:host {
display: flex;
flex: 1;
min-width: 0;
--login-background: #f8f9fa;
--login-border: #e9ecef;
}
.login {
align-items: center;
display: flex;
flex: 1;
justify-content: center;
padding: 72px 24px 56px;
}
.box {
display: flex;
flex-direction: column;
gap: 16px;
max-width: 340px;
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it. */
.logo {
align-self: center;
animation: logo-in 600ms ease-out both;
display: block;
width: 260px;
}
@keyframes logo-in {
from {
opacity: 0;
transform: translateY(-8px);
}
}
@media (prefers-reduced-motion: reduce) {
.logo {
animation: none;
}
}
/* The title between two rules. */
.title {
align-items: center;
color: var(--color-text);
display: flex;
font-family: var(--font-heading);
font-size: 1.375rem;
font-weight: 600;
gap: 16px;
margin: 0 0 8px;
white-space: nowrap;
&::before,
&::after {
background: var(--color-border);
content: '';
flex: 1;
height: 1px;
}
}
.form {
display: flex;
flex-direction: column;
gap: 12px;
}
.field {
--mat-form-field-container-height: 44px;
--mat-form-field-container-vertical-padding: 12px;
width: 100%;
}
.eye {
color: var(--color-text-secondary);
}
.error {
color: var(--mat-sys-error);
font-size: 0.875rem;
margin: -4px 0 0;
}
/* One column with the fields; its border turns to the action color once the form is complete. */
.enter {
align-items: center;
background: var(--login-background);
border: 1px solid var(--login-border);
border-radius: 10px;
color: var(--color-text-secondary);
cursor: default;
display: flex;
font: inherit;
font-size: 0.9375rem;
font-weight: 500;
justify-content: center;
margin-top: 8px;
min-height: 46px;
transition:
background-color 260ms ease,
border-color 260ms ease,
color 260ms ease;
width: 100%;
&:not(:disabled) {
border-color: var(--color-action);
color: var(--color-text);
cursor: pointer;
}
&:hover:not(:disabled) {
background: var(--color-action-hover);
}
&:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
}
.legal {
color: var(--color-text-secondary);
font-size: 0.8125rem;
margin: 16px 0 0;
text-align: center;
}
@media (max-width: 600px) {
.login {
padding: 48px 16px;
}
.logo {
width: 208px;
}
}
+42
View File
@@ -0,0 +1,42 @@
import { Component, inject, input, 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';
import { Router } from '@angular/router';
import { Auth } from './auth';
/** "Inicio de sesión": the brand, two fields and one button. */
@Component({
selector: 'app-login',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
templateUrl: './login.html',
styleUrl: './login.scss',
})
export class Login {
private readonly auth = inject(Auth);
private readonly router = inject(Router);
/** Where to go once signed in (the page that asked for it). */
readonly next = input<string>('');
protected email = '';
protected password = '';
protected readonly show = signal(false);
protected readonly sending = signal(false);
protected readonly error = signal('');
protected readonly year = new Date().getFullYear();
protected async enter(): Promise<void> {
if (!this.email.trim() || !this.password || this.sending()) return;
this.sending.set(true);
this.error.set('');
const problem = await this.auth.login(this.email, this.password);
this.sending.set(false);
if (problem) {
this.error.set(problem);
return;
}
const first = this.auth.user()?.domains[0] ?? 'cacu';
await this.router.navigateByUrl(this.next() || `/indicadores/${first}`);
}
}
+68 -15
View File
@@ -29,7 +29,9 @@
</span>
@if (pipelineId()) {
@for (k of kinds; track k[0]) {
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
<button mat-stroked-button (click)="add(k[0])" [matTooltip]="help[k[0]]">
<mat-icon>add</mat-icon>{{ k[1] }}
</button>
}
<span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button>
@@ -70,10 +72,7 @@
<mat-icon>delete</mat-icon>
</button>
</div>
<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>
<p class="help">{{ help[d.kind ?? 'source'] }}</p>
@if (d.inputs?.length) {
<div class="inputs">
Entradas:
@@ -84,17 +83,71 @@
}
</div>
} @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
<p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
}
<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>
<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>
</mat-tab>
</mat-tab-group>
<button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) {
<div class="preview">
+83
View File
@@ -109,3 +109,86 @@ h2 {
width: auto;
}
}
.help {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.source-summary {
align-items: center;
background: var(--color-background, #f7f8f6);
border: 1px solid var(--color-border);
border-radius: 8px;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
justify-content: space-between;
margin-bottom: var(--space-2);
padding: var(--space-2);
p {
align-items: center;
display: flex;
font-weight: 500;
gap: 6px;
margin: 0;
}
p mat-icon {
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);
}
+150 -12
View File
@@ -1,12 +1,23 @@
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';
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 { 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';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material';
@@ -24,6 +35,7 @@ import type { Pipeline } from '../api/models/pipeline';
import type { Source } from '../api/models/source';
import { ConceptMapEditor } from './concept-map-editor';
import { FORMLY_TYPES, nodeSchema } from './schema-form';
import { SourceDialog, SourceDialogData, SourceDialogResult } from './source-dialog';
type Doc = Pipeline['nodes'][number];
type Kind = NonNullable<Doc['kind']>;
@@ -47,16 +59,29 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
export const KINDS: Record<Kind, string> = {
source: 'Fuente',
read: 'Leer',
route: 'Filtrar',
map: 'Mapear',
extract: 'Extraer',
fhir: 'FHIR',
source: 'Fuente de datos',
read: 'Leer documentos',
route: 'Separar por tipo',
map: 'Traducir códigos',
extract: 'Extraer datos',
fhir: 'Leer FHIR',
join: 'Unir',
link: 'Vincular',
target: 'Destino',
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: '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: '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.',
};
const ID = /^[a-z][a-z0-9_]*$/;
@@ -73,7 +98,9 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule,
MatInputModule,
MatListModule,
MatTabsModule,
MatTableModule,
MatTooltipModule,
Vflow,
ConceptMapEditor,
],
@@ -85,7 +112,12 @@ const ID = /^[a-z][a-z0-9_]*$/;
export class Conectar {
private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema);
private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP;
/** "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) });
@@ -109,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. */
@@ -158,10 +204,47 @@ export class Conectar {
}
protected add(kind: Kind): void {
if (kind === 'source') {
void this.connectSource();
return;
}
this.place(kind, {});
}
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
protected async connectSource(id?: string): Promise<void> {
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
const data: SourceDialogData = {
pipeline: this.pipelineId(),
node: doc?.id,
guided: doc?.guided ?? null,
label: doc?.label ?? '',
};
const ref = this.dialog.open<SourceDialog, SourceDialogData, SourceDialogResult>(SourceDialog, {
data,
width: '760px',
maxWidth: '96vw',
maxHeight: '92vh',
autoFocus: false,
});
const result = await new Promise<SourceDialogResult | undefined>((done) =>
ref.afterClosed().subscribe(done),
);
if (!result) return;
if (doc) {
this.update(doc.id, (d) => ({ ...d, guided: result.guided, label: result.label }) as Doc);
this.select(doc.id);
} else {
this.place('source', { guided: result.guided, label: result.label });
}
this.message.set('Fuente lista. Guarde la canalización para conservarla.');
}
private place(kind: Kind, fields: Record<string, unknown>): void {
let n = 1;
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
const id = `${kind}_${n}`;
const doc = { id, kind, inputs: [] } as unknown as Doc;
const doc = { id, kind, inputs: [], ...fields } as unknown as Doc;
this.docs.update((ds) => [...ds, doc]);
this.nodes.update((ns) => [
...ns,
@@ -204,6 +287,13 @@ export class Conectar {
);
this.form = new UntypedFormGroup({});
this.preview.set(undefined);
this.rawDraft.set(undefined);
this.rawError.set('');
}
/** A source the dialog drew (its answers make its dlt fields). */
protected guided(d: Doc): Source['guided'] {
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
}
/** The form's values into the selected node. */
@@ -219,6 +309,40 @@ export class Conectar {
);
}
/** 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;
@@ -296,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));
}
@@ -322,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. */
@@ -349,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' } } },
+388
View File
@@ -0,0 +1,388 @@
@if (!type()) {
<h2 mat-dialog-title>¿Dónde están los datos?</h2>
<mat-dialog-content>
@if (catalog.isLoading()) {
<div class="loading" role="status">
<mat-spinner diameter="32" /> <span>Cargando opciones…</span>
</div>
}
@for (g of groups(); track g.id) {
<section class="group">
<h3>{{ g.title }}</h3>
<p class="hint">{{ g.description }}</p>
<div class="types">
@for (t of g.types; track t.id) {
<button type="button" class="type" (click)="pick(t.id)" [attr.data-type]="t.id">
<mat-icon>{{ icon(t.icon) }}</mat-icon>
<span class="type-title">{{ t.title }}</span>
<span class="type-text">{{ t.description }}</span>
</button>
}
</div>
</section>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Cancelar</button>
</mat-dialog-actions>
} @else {
<h2 mat-dialog-title class="with-icon">
<mat-icon>{{ icon(type()!.icon) }}</mat-icon> {{ type()!.title }}
</h2>
<mat-dialog-content>
<p class="hint">{{ type()!.description }}</p>
<ng-template #field let-name let-f="f">
@switch (f.type === 'server_file' ? 'folder' : f.type) {
@case ('password') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[type]="showPassword()[name] ? 'text' : 'password'"
[ngModel]="isMasked(name) ? '' : text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="isMasked(name) ? 'Guardada (escriba para cambiarla)' : f.placeholder"
[attr.data-field]="name"
autocomplete="off"
/>
<button
mat-icon-button
matSuffix
type="button"
(click)="togglePassword(name)"
[attr.aria-label]="showPassword()[name] ? 'Ocultar' : 'Mostrar'"
>
<mat-icon>{{ showPassword()[name] ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('number') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
type="number"
[ngModel]="text(name)"
(ngModelChange)="setNumber(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('select') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select [ngModel]="value(name)" (ngModelChange)="set(name, $event)">
@for (o of f.options; track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('format') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
>
@for (o of formats(); track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('table') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
@if (tables().length) {
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event); test()"
[attr.data-field]="name"
>
@for (t of tables(); track t) {
<mat-option [value]="t">{{ t }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
}
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</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">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
<button mat-stroked-button type="button" (click)="openFolder(name, text(name) || null)">
<mat-icon>folder_open</mat-icon> Examinar…
</button>
</div>
@if (browsing(); as b) {
@if (b.field === name) {
<div class="browser" role="group" aria-label="Carpetas del servidor">
<div class="browser-head">
@if (b.at.path) {
<button
mat-icon-button
type="button"
(click)="openFolder(name, b.at.parent)"
aria-label="Subir"
>
<mat-icon>arrow_upward</mat-icon>
</button>
<code>{{ b.at.path }}</code>
} @else {
<span class="hint">Carpetas habilitadas en el servidor</span>
}
</div>
<ul>
@for (e of b.at.entries; track e.path) {
<li>
@if (e.kind === 'folder') {
<button type="button" class="entry" (click)="openFolder(name, e.path)">
<mat-icon>folder</mat-icon> {{ e.name }}
</button>
} @else if (browsingFiles()) {
<button type="button" class="entry" (click)="chooseFile(e.path)">
<mat-icon>description</mat-icon> {{ e.name }}
</button>
} @else {
<span class="entry file"
><mat-icon>description</mat-icon> {{ e.name }}</span
>
}
</li>
} @empty {
<li class="hint">Vacía.</li>
}
</ul>
<div class="browser-actions">
<button mat-button type="button" (click)="browsing.set(undefined)">Cerrar</button>
@if (!browsingFiles()) {
<button
mat-flat-button
type="button"
[disabled]="!b.at.path"
(click)="chooseFolder()"
>
Elegir esta carpeta
</button>
}
</div>
</div>
}
}
}
@case ('upload') {
<div
class="drop"
(dragover)="$event.preventDefault()"
(drop)="dropped(name, $event)"
[attr.data-field]="name"
>
<mat-icon>cloud_upload</mat-icon>
<p>Arrastre aquí los archivos, o</p>
<div class="drop-buttons">
<button mat-stroked-button type="button" (click)="files.click()">
Elegir archivos
</button>
<button mat-stroked-button type="button" (click)="folder.click()">
Elegir una carpeta
</button>
</div>
<input #files type="file" multiple hidden (change)="upload(name, files.files)" />
<input
#folder
type="file"
webkitdirectory
hidden
(change)="upload(name, folder.files)"
/>
@if (uploading(); as u) {
@if (u.field === name) {
<mat-progress-bar mode="determinate" [value]="u.percent" />
<span class="hint">Subiendo… {{ u.percent }} %</span>
}
}
@if (uploaded()[name]?.length) {
<p class="ok">
<mat-icon>check_circle</mat-icon> {{ uploaded()[name].length }} archivos subidos
</p>
} @else if (text(name)) {
<p class="ok"><mat-icon>check_circle</mat-icon> Archivos ya subidos</p>
}
</div>
}
@case ('oauth') {
<div class="signin">
@if (account(name); as who) {
<p class="ok"><mat-icon>check_circle</mat-icon> Conectado como {{ who }}</p>
<button mat-button type="button" (click)="signIn(name, f.provider)">
Usar otra cuenta
</button>
} @else {
<button mat-flat-button type="button" (click)="signIn(name, f.provider)">
<mat-icon>login</mat-icon>
Iniciar sesión con {{ catalog.value()?.providers?.[f.provider]?.title }}
</button>
}
@if (f.help) {
<p class="hint">{{ f.help }}</p>
}
</div>
}
@default {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="f.placeholder"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
}
</ng-template>
<div class="fields">
@for (e of fields(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
@if (more().length) {
<mat-expansion-panel class="more">
<mat-expansion-panel-header>Más opciones</mat-expansion-panel-header>
<div class="fields">
@for (e of more(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
</mat-expansion-panel>
}
<div class="test">
<button
mat-stroked-button
type="button"
(click)="test()"
[disabled]="testing() || missing().length > 0"
>
<mat-icon>network_check</mat-icon> Probar conexión
</button>
@if (testing()) {
<mat-spinner diameter="24" /> <span role="status">Conectando…</span>
} @else if (missing().length) {
<span class="hint">Falta: {{ missing().join(', ') }}</span>
}
</div>
@if (problem()) {
<p class="error" role="alert"><mat-icon>error</mat-icon> {{ problem() }}</p>
}
@if (tested(); as t) {
<div class="result" [class.bad]="!t.ok" role="status">
<p>
<mat-icon>{{ t.ok ? 'check_circle' : 'error' }}</mat-icon> {{ t.message }}
</p>
@if (t.detail) {
<details>
<summary>Respuesta de la fuente</summary>
<pre>{{ t.detail }}</pre>
</details>
}
@if (t.tables?.length) {
<p class="hint">Elija una tabla arriba para ver sus primeras filas.</p>
}
@if (t.rows?.length) {
<p class="hint">
{{
t.rows!.length === 1
? 'La primera fila:'
: 'Las primeras ' + t.rows!.length + ' filas:'
}}
</p>
<div class="rows">
<table mat-table [dataSource]="t.rows!">
@for (c of columns(); track c) {
<ng-container [matColumnDef]="c">
<th mat-header-cell *matHeaderCellDef>{{ c }}</th>
<td mat-cell *matCellDef="let row">{{ cell(row[c]) }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
<tr mat-row *matRowDef="let row; columns: columns()"></tr>
</table>
</div>
}
</div>
}
<mat-form-field appearance="outline" class="full name">
<mat-label>Nombre de esta fuente</mat-label>
<input matInput [ngModel]="label()" (ngModelChange)="label.set($event)" />
<mat-hint>Cómo se verá en el diagrama.</mat-hint>
</mat-form-field>
</mat-dialog-content>
<mat-dialog-actions>
@if (!data.guided) {
<button mat-button type="button" (click)="back()">
<mat-icon>arrow_back</mat-icon> Otro tipo
</button>
}
<span class="spacer"></span>
<button mat-button mat-dialog-close>Cancelar</button>
<button mat-flat-button type="button" (click)="save()" [disabled]="!ready()">Guardar</button>
</mat-dialog-actions>
}
+230
View File
@@ -0,0 +1,230 @@
:host {
display: block;
}
.with-icon {
align-items: center;
display: flex;
gap: var(--space-2);
}
.hint {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.loading,
.test {
align-items: center;
display: flex;
gap: var(--space-2);
margin: var(--space-2) 0;
}
.group h3 {
font-size: 15px;
font-weight: 600;
margin: var(--space-3) 0 2px;
}
.types {
display: grid;
gap: var(--space-2);
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
}
.type {
align-items: start;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 10px;
cursor: pointer;
display: grid;
font: inherit;
gap: 2px 10px;
grid-template-columns: auto 1fr;
padding: 12px;
text-align: left;
&:hover,
&:focus-visible {
border-color: var(--color-primary);
box-shadow: 0 0 0 1px var(--color-primary);
}
mat-icon {
color: var(--color-primary);
grid-row: span 2;
}
}
.type-title {
font-weight: 600;
}
.type-text {
color: var(--color-text-secondary);
font-size: 12.5px;
line-height: 1.35;
}
.fields {
display: flex;
flex-direction: column;
gap: 12px;
}
.full,
.grow {
width: 100%;
}
.picker {
align-items: start;
display: flex;
gap: var(--space-2);
.grow {
flex: 1;
}
button {
margin-top: 10px;
}
}
.browser {
border: 1px solid var(--color-border);
border-radius: 8px;
padding: var(--space-2);
ul {
list-style: none;
margin: 0;
max-height: 220px;
overflow-y: auto;
padding: 0;
}
}
.browser-head,
.browser-actions {
align-items: center;
display: flex;
gap: var(--space-2);
}
.browser-actions {
justify-content: flex-end;
}
.entry {
align-items: center;
background: none;
border: 0;
cursor: pointer;
display: flex;
font: inherit;
gap: 6px;
padding: 4px 2px;
text-align: left;
width: 100%;
&.file {
color: var(--color-text-secondary);
cursor: default;
}
&:not(.file):hover {
color: var(--color-primary);
}
}
.drop {
align-items: center;
border: 2px dashed var(--color-border);
border-radius: 10px;
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
padding: var(--space-3);
text-align: center;
mat-progress-bar {
width: 100%;
}
}
.drop-buttons {
display: flex;
gap: var(--space-2);
}
.signin {
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
align-items: flex-start;
}
.ok,
.error,
.result p {
align-items: center;
display: flex;
gap: 6px;
margin: var(--space-1, 4px) 0;
}
.ok mat-icon,
.result mat-icon {
color: var(--color-success, #2e7d32);
}
.error,
.result.bad p {
color: var(--color-error, #b3261e);
mat-icon {
color: inherit;
}
}
.result {
border: 1px solid var(--color-border);
border-radius: 8px;
margin-top: var(--space-2);
padding: var(--space-2);
pre {
font-size: 12px;
white-space: pre-wrap;
}
}
.rows {
max-height: 260px;
overflow: auto;
td,
th {
font-size: 12px;
max-width: 260px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.more {
margin: var(--space-2) 0;
}
.name {
margin-top: var(--space-3);
}
.spacer {
flex: 1;
}
+361
View File
@@ -0,0 +1,361 @@
import { NgTemplateOutlet } from '@angular/common';
import { HttpClient, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { Component, computed, inject, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTableModule } from '@angular/material/table';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { browse } from '../api/fn/ingest/browse';
import { oauthStart } from '../api/fn/ingest/oauth-start';
import { sourceTypes } from '../api/fn/ingest/source-types';
import { testSource } from '../api/fn/ingest/test-source';
import type { Browsed } from '../api/models/browsed';
import type { FieldSpec } from '../api/models/field-spec';
import type { Guided } from '../api/models/guided';
import type { SourceType } from '../api/models/source-type';
import type { Tested } from '../api/models/tested';
import type { Uploaded } from '../api/models/uploaded';
/** What the dialog is opened with: the source being edited, if any. */
export interface SourceDialogData {
pipeline?: string;
node?: string;
guided?: Guided | null;
label?: string;
}
const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult {
guided: Guided;
label: string;
}
/** The catalog's generic icon words, as Material Symbols. */
const ICONS: Record<string, string> = {
database: 'database',
upload: 'upload_file',
folder: 'folder_open',
link: 'link',
'folder-network': 'lan',
server: 'dns',
cloud: 'cloud',
onedrive: 'cloud',
sharepoint: 'groups',
'google-drive': 'add_to_drive',
web: 'api',
fhir: 'local_hospital',
};
const MASK = '********';
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
@Component({
selector: 'app-source-dialog',
imports: [
FormsModule,
NgTemplateOutlet,
MatButtonModule,
MatDialogModule,
MatExpansionModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSlideToggleModule,
MatTableModule,
],
templateUrl: './source-dialog.html',
styleUrl: './source-dialog.scss',
})
export class SourceDialog {
private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
private readonly ref = inject(MatDialogRef<SourceDialog, SourceDialogResult>);
protected readonly data = inject<SourceDialogData>(MAT_DIALOG_DATA, { optional: true }) ?? {};
protected readonly catalog = resource({ loader: () => this.api.invoke(sourceTypes) });
protected readonly groups = computed(() => {
const c = this.catalog.value();
if (!c) return [];
return Object.entries(c.groups).map(([id, g]) => ({
id,
...g,
types: Object.entries(c.types)
.filter(([, t]) => t.group === id)
.map(([tid, t]) => ({ id: tid, ...t })),
}));
});
protected readonly typeId = signal<string | undefined>(this.data.guided?.type);
protected readonly type = computed<SourceType | undefined>(() => {
const id = this.typeId();
return id ? this.catalog.value()?.types[id] : undefined;
});
protected readonly answers = signal<Record<string, unknown>>({
...(this.data.guided?.answers ?? {}),
});
protected readonly label = signal(this.data.label ?? '');
protected readonly fields = computed(() => entries(this.type()).filter(([, f]) => !f.advanced));
protected readonly more = computed(() => entries(this.type()).filter(([, f]) => f.advanced));
protected readonly showPassword = signal<Record<string, boolean>>({});
protected readonly testing = signal(false);
/** The tables the last listing found: kept while one is picked and its rows shown. */
protected readonly tableList = signal<string[]>([]);
protected readonly tested = signal<Tested | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
protected readonly browsing = signal<{ field: string; at: Browsed } | undefined>(undefined);
protected readonly uploading = signal<{ field: string; percent: number } | undefined>(undefined);
protected readonly uploaded = signal<Record<string, string[]>>({});
protected readonly problem = signal('');
icon(name: string): string {
return ICONS[name] ?? 'input';
}
protected pick(id: string): void {
const t = this.catalog.value()!.types[id];
this.typeId.set(id);
this.answers.set(
Object.fromEntries(
Object.entries(t.fields)
.filter(([, f]) => f.default !== null && f.default !== undefined)
.map(([k, f]) => [k, f.default]),
),
);
if (!this.label()) this.label.set(t.title);
this.tested.set(undefined);
this.problem.set('');
}
protected back(): void {
this.typeId.set(undefined);
this.tested.set(undefined);
this.problem.set('');
}
protected value(name: string): unknown {
return this.answers()[name];
}
protected text(name: string): string {
const v = this.answers()[name];
return v === null || v === undefined ? '' : String(v);
}
protected set(name: string, value: unknown): void {
this.answers.update((a) => ({ ...a, [name]: value }));
if (this.type()?.fields[name]?.type === 'table') return;
this.tested.set(undefined); // another connection: test again
this.tableList.set([]);
}
protected setNumber(name: string, value: string): void {
this.set(name, value === '' ? null : Number(value));
}
protected togglePassword(name: string): void {
this.showPassword.update((s) => ({ ...s, [name]: !s[name] }));
}
protected isMasked(name: string): boolean {
return this.answers()[name] === MASK;
}
protected formats() {
return this.catalog.value()?.formats ?? [];
}
protected account(name: string): string | undefined {
const a = this.answers()[name] as { user?: string } | undefined;
return a ? (a.user ?? 'cuenta conectada') : undefined;
}
/** "Probar conexión": what the source holds, in plain words. */
protected async test(): Promise<void> {
const type = this.typeId();
if (!type) return;
this.testing.set(true);
this.problem.set('');
try {
const found = await this.api.invoke(testSource, {
limit: 20,
body: {
type,
answers: this.cleaned(),
pipeline: this.data.pipeline,
node: this.data.node,
},
});
this.tested.set(found);
if (found.tables?.length) this.tableList.set(found.tables);
} catch (e) {
this.problem.set(message(e));
} finally {
this.testing.set(false);
}
}
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
/** The tables a database listed, for its table field. */
protected tables(): string[] {
return this.tableList();
}
/** Server folders, under the roots the operator mounted. */
protected async openFolder(field: string, path?: string | null): Promise<void> {
try {
const at = await this.api.invoke(browse, path ? { path } : {});
this.browsing.set({ field, at });
} catch (e) {
this.problem.set(message(e));
}
}
protected chooseFolder(): void {
const b = this.browsing();
if (b?.at.path) this.set(b.field, b.at.path);
this.browsing.set(undefined);
}
protected chooseFile(path: string): void {
const b = this.browsing();
if (b) this.set(b.field, path);
this.browsing.set(undefined);
}
/** Whether the field being browsed takes a file (else a folder). */
protected readonly browsingFiles = computed(() => {
const b = this.browsing();
return !!b && this.type()?.fields[b.field]?.type === 'server_file';
});
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
* subfolders. More files can be added to the same set. */
protected upload(field: string, list: FileList | null): void {
if (!list?.length) return;
const body = new FormData();
for (const file of Array.from(list)) {
body.append('files', file, file.webkitRelativePath || file.name);
}
const folder = this.answers()[field];
if (typeof folder === 'string' && folder) body.append('folder', folder);
this.uploading.set({ field, percent: 0 });
this.problem.set('');
this.http
.post<Uploaded>(`${this.root}/ingest/uploads`, body, {
reportProgress: true,
observe: 'events',
})
.subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
this.uploading.set({ field, percent: Math.round((100 * event.loaded) / event.total) });
} else if (event.type === HttpEventType.Response && event.body) {
this.set(field, event.body.bucket_url);
this.uploaded.update((u) => ({
...u,
[field]: [...(u[field] ?? []), ...event.body!.files],
}));
}
},
error: (e) => {
this.uploading.set(undefined);
this.problem.set(message(e));
},
complete: () => this.uploading.set(undefined),
});
}
protected dropped(field: string, event: DragEvent): void {
event.preventDefault();
this.upload(field, event.dataTransfer?.files ?? null);
}
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
protected async signIn(field: string, provider: string): Promise<void> {
this.problem.set('');
let started;
try {
started = await this.api.invoke(oauthStart, { provider, origin: location.origin });
} catch (e) {
this.problem.set(message(e));
return;
}
const popup = window.open(started.url, 'isssteleon-oauth', 'width=520,height=680');
const listen = (event: MessageEvent) => {
const m = event.data as { type?: string; state?: string; account?: unknown; error?: string };
if (event.origin !== location.origin || m?.type !== 'isssteleon-oauth') return;
if (m.state !== started.state) return;
window.removeEventListener('message', listen);
if (m.error) this.problem.set(m.error);
else this.set(field, m.account);
popup?.close();
};
window.addEventListener('message', listen);
}
protected cell(v: unknown): string {
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
}
/** Answers without empty ones (a default takes their place on the server). */
private cleaned(): Record<string, unknown> {
return Object.fromEntries(
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
);
}
protected readonly missing = computed(() =>
entries(this.type())
.filter(([k, f]) => f.required && f.type !== 'table' && isEmpty(this.answers()[k]))
.filter(([, f]) => f.default === null || f.default === undefined)
.map(([, f]) => f.label),
);
protected readonly ready = computed(
() =>
!this.missing().length &&
entries(this.type())
.filter(([, f]) => f.type === 'table' && f.required)
.every(([k]) => !isEmpty(this.answers()[k])),
);
protected save(): void {
const type = this.typeId();
if (!type || !this.ready()) return;
this.ref.close({
guided: { type, answers: this.cleaned() },
label: this.label() || this.type()!.title,
});
}
}
function entries(t: SourceType | undefined): [string, FieldSpec][] {
return Object.entries(t?.fields ?? {});
}
function isEmpty(v: unknown): boolean {
return v === '' || v === null || v === undefined;
}
function message(e: unknown): string {
if (e instanceof HttpErrorResponse) {
const d = e.error?.detail;
if (typeof d === 'string') return d;
if (e.status === 0) return 'No hay conexión con la plataforma. Intente de nuevo.';
return JSON.stringify(d ?? e.message);
}
return String(e);
}
+144
View File
@@ -0,0 +1,144 @@
import type { Figure } from './plot';
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
export const METRIC_NAMES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal media',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
/** The association's biomarkers (core.tea.association.BIOMARKERS). */
export const BIOMARKER_NAMES: Record<string, string> = {
spikes: 'Picos paroxísticos',
spindles: 'Husos de sueño N2',
posterior_rhythm: 'Ritmo posterior',
gradient: 'Gradiente anteroposterior',
};
/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */
export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_01: 'Vocalización espontánea dirigida a otros',
ados2_item_02: 'Señalar',
ados2_item_03: 'Gestos',
ados2_item_04: 'Contacto visual inusual',
ados2_item_05: 'Expresiones faciales dirigidas a otros',
ados2_item_06: 'Integración de la mirada con otras conductas',
ados2_item_07: 'Disfrute compartido en la interacción',
ados2_item_08: 'Respuesta al nombre',
ados2_item_09: 'Búsqueda de atención cuando se le ignora',
ados2_item_10: 'Pedir',
ados2_item_11: 'Mostrar',
ados2_item_12: 'Iniciación espontánea de la atención conjunta',
ados2_item_13: 'Respuesta a la atención conjunta',
ados2_item_14: 'Calidad de los acercamientos sociales',
ados2_item_15: 'Cantidad de acercamientos sociales al cuidador',
ados2_item_16: 'Cantidad de comunicación social recíproca',
ados2_item_17: 'Calidad general de la relación',
ados2_item_18: 'Entonación de vocalizaciones o verbalizaciones',
ados2_item_19: 'Uso estereotipado o idiosincrático de palabras',
ados2_item_20: 'Interés sensorial inusual',
ados2_item_21: 'Manierismos de manos y dedos',
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
CSS: 'Puntuación de severidad (CSS)',
};
/** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */
const AT: Record<string, [number, number]> = {
Fp1: [-0.31, 0.95], Fp2: [0.31, 0.95],
F7: [-0.81, 0.59], F3: [-0.4, 0.53], Fz: [0, 0.5], F4: [0.4, 0.53], F8: [0.81, 0.59],
T3: [-1, 0], C3: [-0.5, 0], Cz: [0, 0], C4: [0.5, 0], T4: [1, 0],
T5: [-0.81, -0.59], P3: [-0.4, -0.53], Pz: [0, -0.5], P4: [0.4, -0.53], T6: [0.81, -0.59],
O1: [-0.31, -0.95], O2: [0.31, -0.95],
}; // prettier-ignore
export interface Site {
site: string;
value: number;
z?: number | null;
}
/** Her electrodes on the head, coloured by how far each is from its age curve (z, blue
* below and red above), or by her own value where no curve scores electrodes. */
export function headMap(electrodes: Site[]): Figure {
const placed = electrodes.filter((e) => AT[e.site]);
const scored = placed.some((e) => e.z !== null && e.z !== undefined);
const colour = placed.map((e) => (scored ? (e.z ?? 0) : e.value));
const ring = Array.from({ length: 73 }, (_, i) => (i * 2 * Math.PI) / 72);
return {
data: [
{
x: ring.map((t) => 1.12 * Math.sin(t)),
y: ring.map((t) => 1.12 * Math.cos(t)),
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: [-0.12, 0, 0.12],
y: [1.1, 1.24, 1.1],
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: placed.map((e) => AT[e.site][0]),
y: placed.map((e) => AT[e.site][1]),
text: placed.map((e) => e.site),
customdata: colour,
mode: 'markers+text',
textposition: 'top center',
marker: {
size: 22,
color: colour,
colorscale: 'RdBu',
reversescale: true,
...(scored ? { cmin: -3, cmax: 3, cmid: 0 } : {}),
colorbar: { title: { text: scored ? 'z' : 'valor' }, thickness: 10 },
line: { color: '#ffffff', width: 1 },
},
hovertemplate: scored ? '%{text}: z = %{customdata:.2f}<extra></extra>'
: '%{text}: %{customdata:.3f}<extra></extra>', // prettier-ignore
showlegend: false,
},
],
layout: {
xaxis: { visible: false, range: [-1.35, 1.35], scaleanchor: 'y' },
yaxis: { visible: false, range: [-1.25, 1.35] },
margin: { l: 10, r: 10, t: 10, b: 10 },
},
} as Figure;
}
/** The zones, most affected first: by how far from the age curve, else by value. */
export function byDeviation(zones: Site[]): Site[] {
const scored = zones.some((z) => z.z !== null && z.z !== undefined);
return [...zones].sort((a, b) =>
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
);
}
/** An EEG's quality level (models.tea.eeg.checks): how much of it the analysis could use. */
export const LEVEL_NAMES: Record<string, string> = {
complete: 'registro completo',
partial: 'registro parcial: menos de la mitad limpio',
no_ear_reference: 'sin referencia auricular',
not_analyzable: 'no analizable',
};
+69
View File
@@ -0,0 +1,69 @@
import type { Content, TDocumentDefinitions } from 'pdfmake/interfaces';
/** A table to save, as the page shows it: its headers and rows, and what it was asked with. */
export interface Sheet {
title: string;
query?: [string, string][];
head: string[];
rows: string[][];
}
/** Every cell is text: nothing in it runs as a formula. */
export async function saveExcel(sheet: Sheet, file: string): Promise<void> {
const { default: write } = await import('write-excel-file/browser');
const text = (value: string) => ({ value, type: String });
const head = sheet.head.map((value) => ({ ...text(value), fontWeight: 'bold' as const }));
await write([
{ sheet: 'Resultados', data: [head, ...sheet.rows.map((r) => r.map(text))] },
{ sheet: 'Consulta', data: (sheet.query ?? []).map((q) => q.map(text)) },
]).toFile(`${file}.xlsx`);
}
/** The tables on the institutional page: logo, date and page numbers. */
export async function savePdf(sheets: Sheet[], file: string, wide = false): Promise<void> {
const [pdfmake, fonts, logo] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
fetch('assets/branding/isssteleon-logo.png').then((r) => r.blob()),
]);
const image = await new Promise<string>((done, fail) => {
const reader = new FileReader();
reader.onload = () => done(reader.result as string);
reader.onerror = () => fail(reader.error);
reader.readAsDataURL(logo);
});
const made = new Date().toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
const definition: TDocumentDefinitions = {
pageSize: 'LETTER',
pageOrientation: wide ? 'landscape' : 'portrait',
pageMargins: [36, 60, 36, 40],
defaultStyle: { fontSize: 7.5 },
header: { image, width: 110, margin: [36, 18, 0, 0] },
footer: (page, pages) => ({
columns: [
`Generado: ${made}`,
{ text: 'Confidencial, uso interno', alignment: 'center' },
{ text: `Página ${page} de ${pages}`, alignment: 'right' },
],
margin: [36, 12],
fontSize: 7,
}),
content: sheets.flatMap((s): Content[] => [
{ text: s.title, fontSize: 13, bold: true, margin: [0, 10, 0, 4] },
...(s.query ?? []).map(([k, v]) => ({ text: [{ text: `${k}: `, bold: true }, v] })),
s.rows.length
? {
layout: 'lightHorizontalLines',
margin: [0, 6, 0, 0],
table: {
headerRows: 1,
dontBreakRows: true,
body: [s.head.map((text) => ({ text, bold: true })), ...s.rows],
},
}
: 'Sin registros.',
]),
};
pdfmake.default.addVirtualFileSystem(fonts.default);
await pdfmake.default.createPdf(definition).download(`${file}.pdf`);
}
+9 -9
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures } from './figures';
import { interpretabilityFigures, scenarioFigure } from './figures';
describe('governance figures', () => {
it('draws a survival report as curves with bands and the model points', () => {
@@ -13,7 +13,7 @@ describe('governance figures', () => {
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
});
it("draws each survival scenario after the cohort's curves, titled with its deaths", () => {
it('leaves the survival scenarios to the patient record, which draws them whole', () => {
const scenario = {
escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)',
n: 1142,
@@ -30,14 +30,14 @@ describe('governance figures', () => {
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
escenarios: [scenario],
});
expect(found.length).toBe(2);
expect(found[1].title).toContain('fallecidos = 308');
expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]);
expect(found.length).toBe(1); // the cohort's curves only
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
});
it('draws a recurrence scenario: KM band, both Weibulls and the model points', () => {
const [found] = interpretabilityFigures({
it('leaves recurrence scenarios to the patient record', () => {
const found = interpretabilityFigures({
kind: 'scenarios',
recurrencia: {
horizons_months: [12, 36],
@@ -55,7 +55,7 @@ describe('governance figures', () => {
],
},
});
expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect(found).toEqual([]);
});
it('draws an age curve with its centile band', () => {
+66 -24
View File
@@ -1,5 +1,6 @@
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them. */
interface Band {
@@ -70,15 +71,7 @@ export function interpretabilityFigures(
},
},
},
// Its clinical scenarios, those with enough deaths to draw.
...((report['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
];
}
case 'subgroups':
@@ -147,17 +140,8 @@ export function interpretabilityFigures(
},
];
}
case 'scenarios':
return (report['recurrencia']['escenarios'] as any[])
.slice(0, 6)
.map((e) =>
scenarioFigure(
`${e.cohorte_nombre} · ${e.escenario} (n = ${e.n}, ${e.recaidas} recaídas)`,
e,
report['recurrencia']['horizons_months'],
'Supervivencia libre de recaída',
),
);
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return [];
case 'age_curves': {
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
@@ -205,14 +189,70 @@ export function interpretabilityFigures(
},
];
}
case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
const label = (r: any) =>
`${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${
OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code
}`;
return [
{
title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${
report['level'] === 'item' ? 'reactivo' : 'dominio'
})`,
figure: {
data: [
{
type: 'scatter',
mode: 'markers',
x: rows.map((r) => r.odds_ratio),
y: rows.map(label),
error_x: {
type: 'data',
symmetric: false,
array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio),
arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)),
},
marker: {
color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')),
size: 9,
},
customdata: rows.map((r) => r.q),
hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}<extra>%{y}</extra>',
showlegend: false,
},
],
layout: {
xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' },
yaxis: { automargin: true, autorange: 'reversed' },
shapes: [
{
type: 'line',
x0: 1,
x1: 1,
yref: 'paper',
y0: 0,
y1: 1,
line: { color: '#9aa0a6', dash: 'dot' },
},
],
height: Math.max(320, 22 * rows.length + 80),
},
},
},
];
}
default:
return [];
}
}
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band. */
function scenarioFigure(
* and the model's points with their bootstrap band (also a patient's, in her record). */
export function scenarioFigure(
title: string,
e: any,
horizons: number[],
@@ -246,8 +286,10 @@ 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%' },
},
},
};
+68 -34
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()) {
@@ -31,19 +58,21 @@
}
@if (models.isLoading()) {
<p class="muted">Cargando modelos…</p>
<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;
}
+64 -18
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { HttpErrorResponse } from '@angular/common/http';
import { DatePipe, DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
@@ -5,7 +6,6 @@ import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { 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';
@@ -16,15 +16,16 @@ 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';
import { DOMAINS } from '../app';
import { Plot } from '../plot';
import { interpretabilityFigures } from './figures';
import { Loading } from '../loading';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
@@ -38,13 +39,13 @@ const REPORTS: Record<string, string> = {
@Component({
selector: 'app-gobernanza',
imports: [
Loading,
DatePipe,
DecimalPipe,
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
RouterLink,
Plot,
],
templateUrl: './gobernanza.html',
@@ -57,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 }),
})),
);
@@ -91,15 +92,43 @@ export class Gobernanza {
params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
});
protected readonly metricNames: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
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 {
@@ -120,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'}`,
);
}
}
@@ -143,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'
+114
View File
@@ -0,0 +1,114 @@
import { bars } from './bars';
import { Reading } from './measures';
describe('bars', () => {
it('list every category, so the shares add up', () => {
const r: Reading = {
populations: {},
strata: {
category: { a: { 'initial-population': 3 }, other: { 'initial-population': 1 } },
},
};
const catalog = [{ code: 'a', label: 'A', color: '#000' }];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '75.0 %'],
['1', '25.0 %'],
]);
});
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: {},
strata: { s: { initial: { numerator: 0, denominator: 0 } } },
};
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
it('a proportion split into its parts shows both in units and shares', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const t = bars({ kind: 'split', label: 'x', measure: 'M', yes: 'Con', no: 'Sin' }, () => r)!;
expect(t.rows.map((x) => [x.label, ...x.cells])).toEqual([
['Con', '1', '25.0 %'],
['Sin', '3', '75.0 %'],
]);
});
it('rows with patients and no biopsy are not rows with no patients; malignant counts only graded', () => {
const r: Reading = {
populations: {},
strata: {
birads: {
'4A': { 'initial-population': 3 },
'5': { 'initial-population': 4 },
'6': { 'initial-population': 2 },
},
'birads-category': {
'4A|no_biopsy': { 'initial-population': 3 },
'5|benign': { 'initial-population': 1 },
'5|invasive': { 'initial-population': 1 },
'5|no_data': { 'initial-population': 2 },
'6|no_data': { 'initial-population': 2 },
},
},
};
const results = [
{ code: 'benign', label: 'Benigno', color: '#1' },
{ code: 'invasive', label: 'Invasor', color: '#2' },
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#3' },
{ code: 'no_data', label: 'Sin dato', color: '#4' },
];
const rows = ['4A', '5', '6', '4B'].map((code) => ({ code, label: code, color: '#0' }));
const mode = {
kind: 'outcomes',
label: 'x',
measure: 'M',
stratum: 'birads',
rows,
results,
malignant: ['invasive'],
};
const t = bars(mode as any, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '0', '0', '3', '0', 'Sin biopsias'],
['4', '1', '1', '0', '2', '1/2 (50.0 %)'],
['2', '0', '0', '0', '2', 'Sin biopsias clasificables'],
['0', '—', '—', '—', '—', '—'],
]);
expect(t.rows.map((x) => x.none)).toEqual([
undefined,
undefined,
undefined,
'Sin pacientes en el periodo',
]);
expect(t.rows[1].segments!.map((x) => x.width)).toEqual([25, 25, 0, 50]);
});
it('bars on a percent scale are as long as the shares shown', () => {
const r: Reading = {
populations: {},
strata: { category: { a: { 'initial-population': 1 }, b: { 'initial-population': 3 } } },
};
const catalog = [
{ code: 'a', label: 'A', color: '#0' },
{ code: 'b', label: 'B', color: '#1' },
{ code: 'c', label: 'C', color: '#2' },
];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, percent: true }, () => r)!;
expect(t.rows.map((x) => x.width)).toEqual([25, 75, 0]);
expect(t.rows.map((x) => x.cells)).toEqual([
['1', '25.0 %'],
['3', '75.0 %'],
['0', '0.0 %'],
]);
});
it('a split takes the colours it is given', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const mode = {
kind: 'split',
label: 'x',
measure: 'M',
yes: 'Con',
no: 'Sin',
colors: ['#a', '#b'],
};
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
});
});
+231
View File
@@ -0,0 +1,231 @@
import { CIE10 } from './cie10';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = {
label: string;
caption?: string;
/** said above the table: what its rows count (patients, reported biopsies…) */
heading?: string;
} &
/** `percent`: every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
(
| { kind: 'counts'; measure: string; catalog: Category[]; percent?: boolean }
| { kind: 'shares'; measure: string; stratum: string; order: string[] }
| { kind: 'positives'; measure: string; stratum: string; order: string[] }
| { kind: 'signs'; measure: string; strata: string[] }
| { kind: 'days'; steps: { label: string; measure: string }[] }
| { kind: 'days-by'; measure: string; stratum: string }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
/** Each row's units by result (a bar in segments), and the share of the row's units with a
* result that are `malignant`; a row with units and no result is not a row with none */
| {
kind: 'outcomes';
measure: string;
stratum: string;
rows: Category[];
results: Category[];
malignant: string[];
}
| { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] }
);
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar {
label: string;
color?: string;
width: number;
marks: number[];
cells: string[];
/** the bar in parts (in % of the bar), each with what it says when hovered */
segments?: { width: number; color: string; title: string }[];
/** said in place of the bar (a row with nothing to draw) */
none?: string;
}
export interface Bars {
head: string[];
rows: Bar[];
/** the colours of the segments */
legend?: { label: string; color: string }[];
}
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) {
case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
if (!total) return undefined;
// a category outside the catalog is listed after it, so the shares add up
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c));
const all = [
...mode.catalog,
...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
];
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return {
head: ['n', '%'],
rows: all.map(({ code, label, color }) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
};
}
case 'shares': {
const cells = of(mode.measure)?.strata[mode.stratum] ?? {};
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]),
);
}
case 'positives': {
const cells = of(mode.measure)?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`])];
}),
);
}
case 'signs': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative'])];
}),
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
);
}
case 'split': {
const { numerator = 0, denominator = 0 } = of(mode.measure)?.populations ?? {};
if (!denominator) return undefined;
const parts: [string, number][] = [
[mode.yes, numerator],
[mode.no, denominator - numerator],
];
return {
head: ['n', '%'],
rows: parts.map(([label, n], i) => ({
label,
color: mode.colors?.[i],
width: (100 * n) / denominator,
marks: [],
cells: [`${n}`, pct(n, denominator)],
})),
};
}
case 'outcomes': {
const r = of(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
return {
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'],
legend: mode.results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]);
const by = mode.results.map((x) => size(cells[`${code}|${x.code}`]));
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0);
const bad = by.reduce(
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0),
0,
);
return {
label,
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: mode.results.map((x, i) => ({
width: n ? (100 * by[i]) / n : 0,
color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
})),
cells: [
`${n}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? den
? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')]
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
}),
};
}
default:
return undefined;
}
}
function ratios(rows: [string, number, number][]): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', '%'],
rows: rows.map(([label, n, total]) => ({
label,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = { score?: number; low?: number; high?: number };
function medians(rows: { label: string; n: number; score?: Score }[]): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
};
}),
};
}
+19
View File
@@ -0,0 +1,19 @@
/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
+55
View File
@@ -0,0 +1,55 @@
import { durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
describe('durationRows', () => {
const reads: Record<string, Reading> = {
A: reading(0, 3, 0, 1),
B: reading(6, 20, 4, 8),
C: reading(undefined, 0),
};
const rows = durationRows(
[
{ label: 'zero', measure: 'A' },
{ label: 'value', measure: 'B' },
{ label: 'nothing measured', measure: 'C' },
{ label: 'no report', measure: 'D' },
{ label: 'not in the catalog', measure: 'E' },
{ label: 'no measure' },
],
(m) => reads[m],
(m) => m !== 'E',
);
it('keeps a real zero as a value', () => {
expect(rows[0]).toEqual({
label: 'zero',
status: 'value',
median: 0,
observations: 3,
low: 0,
high: 1,
});
});
it('tells no measurements from an unpublished measure', () => {
expect(rows.map((r) => r.status)).toEqual([
'value',
'value',
'empty',
'empty',
'unpublished',
'unpublished',
]);
});
it('scales from zero to the largest median or third quartile', () => {
expect(durationMax(rows)).toBe(8);
expect(durationMax([])).toBe(0);
});
});
+46
View File
@@ -0,0 +1,46 @@
import { Reading } from './measures';
/** One step of a route: its name and the measure that times it. A step with no measure is
* not published yet. */
export interface RouteStep {
label: string;
measure?: string;
}
/** One row of a duration table: the median days, how many measurements and the quartiles.
* `empty` (published, nothing measured in the period) is not `unpublished` (no measure), and
* neither is a zero: a median of 0 days is a value. */
export interface DurationRow {
label: string;
status: 'value' | 'empty' | 'unpublished';
median?: number;
observations?: number;
low?: number;
high?: number;
}
/** The rows of a route in one reading; every step keeps its row. `published` says which
* measures the catalog has. */
export function durationRows(
steps: RouteStep[],
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' };
const r = read(measure);
if (r?.score === undefined) return { label, status: 'empty' };
return {
label,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
low: r.low,
high: r.high,
};
});
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
+448
View File
@@ -0,0 +1,448 @@
import { type Figure, PALETTE } from '../plot';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
// 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)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
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);
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)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
ticksuffix: ' %',
range: [0, 100.5],
dtick: 20,
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
},
};
}
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record<string, string> = {
n: count(p['initial-population'] ?? 0),
obs: count(p['measure-observation'] ?? 0),
median: r.score === undefined ? '' : decimal(r.score),
q1: decimal(r.low ?? r.score ?? 0),
q3: decimal(r.high ?? r.score ?? 0),
num: count(p['numerator'] ?? 0),
den: count(p['denominator'] ?? 0),
pct: r.score === undefined ? '' : percent(r.score * 100),
};
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
/** A duration's quartile box in the period. */
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
return {
data: [
{
type: 'box',
name: 'Total',
x: [period],
q1: [q1],
median: [r.score!],
q3: [q3],
lowerfence: [q1],
upperfence: [q3],
marker: { color: '#4269C2' },
fillcolor: 'rgba(66,105,194,0.55)',
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
};
}
/** One ring: the categories' shares, the total in the centre. */
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
return {
data: [
{
type: 'pie',
hole: 0.54,
sort: false,
direction: 'clockwise',
labels: catalog.categories.map((c) => c.label),
values,
marker: {
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 30, l: 60, r: 60, b: 30 },
annotations: [
{
text: `<b>${count(total)}</b><br>${center}`,
showarrow: false,
x: 0.5,
y: 0.5,
xref: 'paper',
yref: 'paper',
},
],
},
};
}
/** A category's count per bar, one bar each, in the period. */
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label);
return {
data: [
{
type: 'bar',
orientation: 'h',
name: period,
y,
x: catalog.categories.map((c) => counted(r, c.code)),
marker: { color: catalog.categories.map((c) => c.color) },
texttemplate: '%{x}',
textposition: 'outside',
hovertemplate: '%{y}: %{x}<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: axis }, rangemode: 'tozero' },
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
},
};
}
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2'];
/** "16-23" as the screens say it: "16 a 23 meses". */
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
function ages(r: Reading): [string, Record<string, number>][] {
return Object.entries(r.strata['age_group'] ?? {}).sort(
([a], [b]) => parseInt(a, 10) - parseInt(b, 10),
);
}
/** By age group: the numerator and the rest of the denominator, stacked. */
export function ageStack(r: Reading, names: [string, string]): Figure {
const rows = ages(r);
const x = rows.map(([a]) => ageLabel(a));
return {
data: [
{
type: 'bar',
name: names[0],
x,
y: rows.map(([, c]) => c['numerator'] ?? 0),
marker: { color: AGE_COLORS[0] },
},
{
type: 'bar',
name: names[1],
x,
y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)),
marker: { color: AGE_COLORS[1] },
},
] as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' },
},
};
}
/** By age group: the numerator's share of the denominator, one bar each. */
export function ageShare(r: Reading, axis: string): Figure {
const rows = ages(r);
return {
data: [
{
type: 'bar',
x: rows.map(([a]) => ageLabel(a)),
y: rows.map(([, c]) =>
c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0,
),
marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) },
texttemplate: '%{y:.1f} %',
textposition: 'outside',
hovertemplate: '%{x}: %{y:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
},
};
}
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
* closed shape. */
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
return {
data: named.map((c) => ({
type: 'bar',
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
})),
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
mode: 'lines',
fill: 'toself',
fillcolor: line + '33',
line: { width: 0 },
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => at(s.r?.score)),
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
};
}
+52
View File
@@ -0,0 +1,52 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
const HEAD = [
'Paciente',
'CURP',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
'LIEAG+',
'Cáncer',
'Días a diagnóstico',
];
/** A cytology's result, or why it has none. */
export function cytologyResult(c: NonNullable<Row['cytology']>): string {
if (c.result) return name(c.result);
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */
export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
return {
title: 'Resultados de seguimiento',
query: [...query, ['Registros', `${rows.length}`]],
head: HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
`${r.age ?? NONE}`,
name(r.status),
r.stages
.filter((s) => s.state !== 'unknown')
.map((s) => `${s.label}: ${s.day ?? STATES[s.state]}`)
.join('\n'),
r.cytology ? `${cytologyResult(r.cytology)} (${r.cytology.date})` : NONE,
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'} (${r.hpv.date})` : NONE,
r.biopsy ? `${name(r.biopsy.histology ?? '') || 'Sin grado'} (${r.biopsy.date})` : NONE,
percent(r.risk.cin2),
percent(r.risk.cancer),
`${r.daysToDiagnosis ?? NONE}`,
]),
};
}
+12 -1
View File
@@ -1,5 +1,5 @@
import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart } from './follow-up';
import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures';
describe('follow-up list', () => {
@@ -45,3 +45,14 @@ describe('follow-up list', () => {
]);
});
});
describe('ages', () => {
it('ask for the birth dates whose completed years fall in the range', () => {
expect(bornFor('2026-06-30', 36, 40)).toEqual(['le1990-06-30', 'gt1985-06-30']);
expect(bornFor('2026-06-30', null, null)).toEqual([]);
expect(bornFor('2024-02-29', 1, null)).toEqual(['le2023-02-28']);
expect([ageAt('1990-06-30', '2026-06-30'), ageAt('1990-07-01', '2026-06-30')]).toEqual([
36, 35,
]);
});
});
+34 -6
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
import { route, Stage } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
@@ -8,6 +9,8 @@ export interface Row {
curp?: string;
status: string;
ageGroup: string;
age?: number;
stages: Stage[];
cytology?: { date: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number;
@@ -24,15 +27,36 @@ const AGE_GROUPS: [number, number][] = [
[55, 64],
];
/** Completed years at a day. */
export function ageAt(birth: string | undefined, at: string): number | undefined {
if (!birth) return undefined;
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
return y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
}
/** The birth dates of who has completed between `from` and `to` years at a day, as FHIR's
* `birthdate` parameter. */
export function bornFor(at: string, from: number | null, to: number | null): string[] {
const back = (years: number) => `${Number(at.slice(0, 4)) - years}${at.slice(4)}`;
return [
...(from === null ? [] : [`le${valid(back(from))}`]),
...(to === null ? [] : [`gt${valid(back(to + 1))}`]),
];
}
/** February 29th in a year without one: the 28th. */
const valid = (day: string) =>
day.endsWith('-02-29') && new Date(`${day}T00:00:00Z`).getUTCMonth() !== 1
? `${day.slice(0, 8)}28`
: day;
export function ageGroup(
birth: string | undefined,
at: string,
groups: [number, number][] = AGE_GROUPS,
): string {
if (!birth) return 'Sin dato';
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const age = ageAt(birth, at);
if (age === undefined) return 'Sin dato';
const found = groups.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`;
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
@@ -103,6 +127,8 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
age: ageAt(patient.birthDate, cutoff),
stages: route(last, cutoff),
cytology: last && {
date: last.effectiveDateTime!,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
@@ -146,11 +172,12 @@ export interface CamaRow {
status: string;
priority: string;
ageGroup: string;
mammogram: { date: string; birads?: string };
/** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string };
}
const CAMA_AGE_GROUPS: [number, number][] = [
export const CAMA_AGE_GROUPS: [number, number][] = [
[40, 49],
[50, 59],
[60, 69],
@@ -196,6 +223,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
birads: mammogram
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
: undefined,
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
},
biopsy: biopsy && {
date: reported(biopsy)!,
+33 -9
View File
@@ -6,35 +6,37 @@ import { Fhir, resources } from '../fhir';
import { TabDefiniciones } from './tab-definiciones';
import { TabIndicadores } from './tab-indicadores';
import { TabRiesgos } from './tab-riesgos';
import { TabRiesgosTea } from './tab-riesgos-tea';
import { TabSeguimiento } from './tab-seguimiento';
import { TabTrazabilidad } from './tab-trazabilidad';
import { Loading } from '../loading';
/** A domain's indicator page: four tabs over its FHIR measures and patients. */
@Component({
selector: 'app-indicadores',
imports: [
Loading,
MatTabsModule,
TabIndicadores,
TabTrazabilidad,
TabRiesgos,
TabRiesgosTea,
TabSeguimiento,
TabDefiniciones,
],
template: `
<section class="page">
<h1>{{ title() }}</h1>
<p class="subtitle">
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
</p>
<p class="subtitle">Explora los indicadores de {{ title().toLowerCase() }}.</p>
@if (measures.isLoading()) {
<p class="muted">Cargando indicadores…</p>
<app-loading what="los indicadores" />
} @else if (measures.error()) {
<p class="muted" role="alert">No se pudieron leer los indicadores.</p>
} @else if (!measures.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab label="Indicadores">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab>
<mat-tab label="Trazabilidad">
@@ -48,8 +50,14 @@ import { TabTrazabilidad } from './tab-trazabilidad';
<app-tab-riesgos [domain]="domain()" />
</ng-template>
</mat-tab>
} @else if (domain() === 'tea') {
<mat-tab label="Análisis de Riesgo">
<ng-template matTabContent>
<app-tab-riesgos-tea [domain]="domain()" />
</ng-template>
</mat-tab>
} @else if (domain() === 'cama') {
<mat-tab label="Seguimiento">
<mat-tab label="Análisis de riesgos">
<ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" />
</ng-template>
@@ -57,7 +65,7 @@ import { TabTrazabilidad } from './tab-trazabilidad';
}
<mat-tab label="Datos y definiciones">
<ng-template matTabContent>
<app-tab-definiciones [measures]="measures.value()!" />
<app-tab-definiciones [domain]="domain()" [measures]="measures.value()!" />
</ng-template>
</mat-tab>
</mat-tab-group>
@@ -68,11 +76,27 @@ import { TabTrazabilidad } from './tab-trazabilidad';
:host {
display: block;
}
/* As the old page: the domain's name and a line under it, then a white tab bar under
an olive rule. */
h1 {
text-align: center;
font-size: 28px;
font-weight: 500;
margin: 16px 0 8px;
}
.subtitle {
text-align: center;
font-size: 16px;
margin: 0 0 24px;
}
::ng-deep .mat-mdc-tab-header {
background: var(--color-surface);
border-top: 2px solid var(--color-primary);
}
::ng-deep .mat-mdc-tab .mdc-tab__text-label {
font-size: 16px;
font-weight: 400;
}
::ng-deep .mat-mdc-tab.mdc-tab--active .mdc-tab__text-label {
font-weight: 700;
}
.empty {
padding: 48px 0;
+45 -6
View File
@@ -50,6 +50,8 @@ export interface Reading {
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
/** A stratum value's own score (a median and its quartiles). */
scores?: Record<string, Record<string, { score?: number; low?: number; high?: number }>>;
}
function counts(group: {
@@ -65,11 +67,25 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined;
const score = group.measureScore;
const strata: Reading['strata'] = {};
const scores: NonNullable<Reading['scores']> = {};
for (const s of group.stratifier ?? []) {
const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? '';
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [x.value?.text ?? '', counts(x)]),
(s.stratum ?? []).map((x) => [
x.component?.length
? x.component.map((c) => c.value?.text ?? '').join('|')
: (x.value?.text ?? ''),
counts(x),
]),
);
for (const { value, measureScore: own } of s.stratum ?? [])
if (own)
(scores[name] ??= {})[value?.text ?? ''] = {
score: own.value,
low: ext(own, 'q1')?.valueDecimal,
high: ext(own, 'q3')?.valueDecimal,
};
}
return {
populations: counts(group),
@@ -78,11 +94,12 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit,
strata,
scores,
};
}
/** Codes as the screens name them. */
const LABELS: Record<string, string> = {
export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)',
LSIL: 'LIEBG',
HSIL: 'LIEAG',
@@ -116,6 +133,21 @@ const LABELS: Record<string, string> = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Inicial',
subsequent: 'Subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
@@ -128,6 +160,13 @@ 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',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
};
export const name = (value: string) => LABELS[value] ?? value;
@@ -143,14 +182,14 @@ export function formatScore(measure: Measure, r: Reading | undefined): string {
}
}
export function detail(measure: Measure, r: Reading | undefined): string {
export function detail(measure: Measure, r: Reading | undefined, unit = 'pacientes'): string {
if (!r) return '';
const p = r.populations;
switch (scoring(measure)) {
case 'proportion':
return r.score === undefined
? 'Sin pacientes en el periodo.'
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
? `Sin ${unit} en el periodo.`
: `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable':
return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
+280
View File
@@ -0,0 +1,280 @@
import type { Mode } from './bars';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
],
faded: ['normal', 'LSIL'],
};
/** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#A8C243' },
{ code: 'positive_16', label: 'VPH 16', color: '#C24269' },
{ code: 'positive_18', label: 'VPH 18', color: '#9C42C2' },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' },
{ code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' },
{ code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' },
];
const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: '#C24269' },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' },
{ code: 'pending', label: 'Pendiente', color: '#C9CDD2' },
{ code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' },
];
/** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
kind: 'readings',
title,
headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut' },
{
kind: 'shares',
label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure,
stratum: 'cytology',
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
},
{
kind: 'shares',
label: 'VPH previo',
caption: 'Los grupos se traslapan.',
measure,
stratum: 'hpv',
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
},
{
kind: 'shares',
label: 'Nivel de histología',
measure,
stratum: 'level',
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
},
{
kind: 'shares',
label: 'Tamizaje',
measure,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
...more,
],
});
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
export const CACU: Page = {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempos de la ruta del tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [
{
kind: 'days',
label: 'Acumulado desde la toma',
steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
],
},
{
kind: 'days',
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
],
},
{
kind: 'days-by',
label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
stratum: 'diagnosis_code',
},
],
},
],
clinical: [
{
kind: 'columns',
title: 'Resultados de citología, VPH y biopsia',
sections: [
{
kind: 'readings',
title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
},
{
kind: 'figure',
label: 'Por escenario clínico',
measure: 'CACU_EU7',
figure: 'scenarios',
catalog: CYTOLOGY.categories,
},
],
},
{
kind: 'readings',
title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.',
modes: [{ kind: 'counts', label: 'General', measure: 'CACU_VPH_GENOTIPO', catalog: HPV }],
},
{
kind: 'readings',
title: 'Resultados de biopsia cervical',
note: 'Reportes, por fecha de reporte.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories,
},
],
},
],
},
{
kind: 'readings',
title: 'Pacientes evaluadas por resultado de VPH',
headline: 'CACU_VPH',
note: 'Una vez cada paciente, por su última muestra con resultado.',
modes: [
{ kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' },
{
kind: 'positives',
label: 'Por grupo de edad',
measure: 'CACU_VPH',
stratum: 'age_group',
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
},
{
kind: 'positives',
label: 'Por estatus de seguimiento',
measure: 'CACU_VPH',
stratum: 'follow_up_status',
order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
},
{
kind: 'signs',
label: 'Por genotipo',
measure: 'CACU_VPH',
strata: ['hpv_16', 'hpv_18'],
},
{
kind: 'positives',
label: 'Por tamizaje',
measure: 'CACU_VPH',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
],
},
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
choices: [
{
label: 'Colposcopía',
section: ppv(
'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
},
),
},
],
},
],
};

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