Compare commits

...

33 Commits

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

Co-authored-by: edgar <edgar.hinojosas@uanl.edu.mx>
2026-11-30 16:02:00 -06:00
Angel Capetillo Zavala bc621f34f9 Regenerate client for CaCu exports and follow-up contracts 2026-11-30 16:01:58 -06:00
Angel Capetillo Zavala c5da898265 Regenerate API client for the existing rebuild contract 2026-11-30 15:59:46 -06:00
Roberto Treviño ca887c29ab Wording: formal, precise, no narrative; the missing reports of a promotion in Spanish 2026-11-29 15:24:25 -06:00
Roberto Treviño bb506c3926 Conectar: Configuración and Avanzado tabs, rows instead of JSON, field titles as keys, captions that fit their nodes 2026-11-29 15:24:24 -06:00
Roberto Treviño b48c025400 Page test: no overlapping, clipped or wrapped labels at 1440 and 820 px 2026-11-29 12:39:07 -06:00
Roberto Treviño a93cd71126 Cosmetic pass: legends above plots, readable hovers and ticks, KPI qualifiers, a header that never wraps 2026-11-29 12:39:07 -06:00
Roberto Treviño 979b7cf34d Gobernanza: the header's domain switcher, model titles, confirmations, a stop button, an upload button 2026-11-29 12:39:07 -06:00
Roberto Treviño cde9b1cfb1 Revisión: documents no route recognises; reasons and fields in Spanish 2026-11-29 12:39:07 -06:00
Roberto Treviño edc32af67e CaMa record as the old card: summary, mammography, histopathology, prognosis, risk of death and its scenarios' risk factors 2026-11-29 12:39:07 -06:00
Roberto Treviño 2216186d26 Patient lists have a search box; TEA alterations by their Spanish names 2026-11-29 12:39:07 -06:00
Roberto Treviño 55c4e0b173 OpenAPI client: model titles, run termination, Patient name and identifier 2026-11-29 12:39:07 -06:00
Roberto Treviño 52cca0a84c Record history shows only ICD-10 codes beside a diagnosis 2026-11-29 07:13:57 -06:00
Roberto Treviño 7e50ff9b90 OpenAPI spec names the configured promotion reports and CaMa's history 2026-11-29 06:58:38 -06:00
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
136 changed files with 13480 additions and 515 deletions
+122
View File
@@ -0,0 +1,122 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+563 -11
View File
@@ -1,4 +1,6 @@
import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test'; import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */ /** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] { function watch(page: Page): string[] {
@@ -9,6 +11,32 @@ function watch(page: Page): string[] {
return problems; 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 ({ test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page, page,
}) => { }) => {
@@ -24,7 +52,10 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
const count = eu7.entry[0].resource.group[0].population.find( const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population', (p: any) => p.code.coding[0].code === 'initial-population',
).count; ).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 expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).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).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first); await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click(); await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(`21–`)).toBeVisible(); await expect(page.getByText(/Página 2 de \d+, \d+ registros/)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click(); await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click(); await rows.first().locator('a').first().click();
@@ -54,13 +85,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama'); await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr'); const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS'); await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea'); await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
expect(problems).toEqual([]); expect(problems).toEqual([]);
}); });
@@ -71,13 +102,19 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar'); await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click(); await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible(); await expect(page.locator('vflow')).toBeVisible();
await page.getByText('Fuente · Patients').click(); // a node's caption: its kind, then its name
await expect(page.locator('formly-form')).toBeVisible(); await page.locator('.node-caption', { hasText: 'Pacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click(); await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible(); await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows. // A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Mapear · cytology', { exact: true }).click(); await page;
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 await expect
.poll(() => .poll(() =>
page page
@@ -90,7 +127,9 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
expect(problems).toEqual([]); 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); const problems = watch(page);
await page.goto('/revision'); await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click(); await page.getByRole('tab', { name: 'Personas' }).click();
@@ -107,12 +146,525 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
}) => { }) => {
const problems = watch(page); const problems = watch(page);
await page.goto('/gobernanza/cama'); await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' }); const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible(); await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click(); await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible(); await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click(); await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('clinical_validation'); await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]); expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
}); });
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');
const old = items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
return domain === 'cacu' ? rearranged(old) : old;
}
/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the
* opportunity section, under its cards, and the cytology distribution is a table in the joint
* results card (its nested donut is not drawn any more). Nothing else of the old page moves. */
function rearranged(old: any[]) {
const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje');
const moved = old.splice(route, 2); // its heading and its plot
old.splice(
old.findIndex((i) => i.text === 'Indicadores clínicos'),
0,
moved[0],
moved[1],
);
// the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the
// cytology section, under another title) are not headings of this page any more
return old.filter(
(i) =>
!/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test(
i.text ?? '',
),
);
}
/** Sections this platform adds to an old page, by domain, in the order they appear. The old
* headings still have to appear, in their order; nothing else may appear (a figure's own
* `h3.figure-title` inside a measure's card is the card's, not a section). */
const ADDED: Record<string, string[]> = {
cacu: [
'Resultados de citología, VPH y biopsia',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
'VPP tras colposcopía registrada',
],
};
/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */
function oldThenAdded(actual: string[], old: string[], added: string[]) {
const extra: string[] = [];
let found = 0;
for (const heading of actual) {
if (found < old.length && heading === old[found]) found++;
else extra.push(heading);
}
return { allOldInOrder: found === old.length, extra, added };
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const old = captured(domain);
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 });
// textContent: a heading inside a collapsed section (CaCu's original confirmation measure)
// is still a heading of the page, though the browser gives it no rendered text.
const headings = await tab
.locator('h2, h3:not(.figure-title)')
.evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()));
const from = headings.indexOf('Indicadores de oportunidad');
const seen = oldThenAdded(
headings.slice(from).map(period),
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
ADDED[domain] ?? [],
);
expect(seen.allOldInOrder).toBe(true);
expect(seen.extra).toEqual(seen.added);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.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();
});
}
test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({
page,
}) => {
const asked: string[] = [];
page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url()));
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// cumulative (the default), step by step with its warning and quartiles, and by ICD-10
// the route's times are in the opportunity section, after its cards and before the clinical ones
const opportunity = tab.locator('section.opportunity');
await expect(opportunity.locator('.route-card')).toBeVisible();
await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0);
expect(
await opportunity.evaluate((el) => {
const kpis = el.querySelector('.kpis')!;
const card = el.querySelector('.route-card')!;
return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING);
}),
).toBe(true);
await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible();
await tab.getByRole('radio', { name: 'Por pasos' }).click();
// by steps: independent bars from zero in a table, every step kept, and the medians not added
const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' });
await expect(steps).toBeVisible();
await expect(steps.locator('tbody tr')).toHaveCount(4);
await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible();
await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0);
await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click();
await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible();
await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click();
await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible();
await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible();
// the sections of the new measures: each one in the place of its subject
for (const measure of [
'CACU_VPH_GENOTIPO',
'CACU_VPH',
'CACU_BIOPSIA_RESULTADOS',
'CACU_VPP_COLPOSCOPIA',
])
await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible();
// a PPV says what it is and what it is not
await expect(
tab
.locator('[data-measure="CACU_VPP_COLPOSCOPIA"]')
.getByText('no un vínculo clínico confirmado'),
).toBeVisible();
// the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut
const joint = tab.locator('.results-card');
const [cyto, hpv, biopsy] = await Promise.all(
['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) =>
joint.locator(`section[data-measure="${m}"]`).boundingBox(),
),
);
expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2);
expect(cyto!.x).toBeLessThan(hpv!.x);
expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1);
expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8);
await expect(
joint.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(joint.getByText('Menor que LIEAG')).toBeVisible();
await expect(joint.getByText('LIEAG o más')).toBeVisible();
// three HPV categories are not listed, and the page says so only when it has such reports
const hpvRows = await joint
.locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th')
.allInnerTexts();
for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable'])
expect(hpvRows.join('|')).not.toContain(hidden);
// the cytology column reads one way at a time: the general table, or the clinical scenarios
const cytology = joint.locator('section[data-measure="CACU_EU7"]');
await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked();
await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0);
await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click();
await expect(cytology.locator('.js-plotly-plot')).toBeVisible();
await expect(cytology.getByRole('table')).toHaveCount(0);
await expect(
cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'),
).toBeVisible();
await expect(cytology.locator('.legend li')).toHaveCount(6);
await cytology.getByRole('radio', { name: 'Distribución general' }).click();
await expect(
cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(
joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'),
).toHaveCount(0);
await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0);
// the confirmation card: one perspective at a time, each with its own PPV and its readings
const confirmation = tab.locator('.confirmation-card');
await expect(
confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }),
).toBeVisible();
await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible();
await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked();
for (const [perspective, measure, title] of [
['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'],
['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'],
]) {
await confirmation.getByRole('radio', { name: perspective, exact: true }).click();
await expect(confirmation.locator('app-ppv-card')).toHaveCount(1);
const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`);
await expect(ppv.getByRole('heading', { name: title })).toBeVisible();
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
await expect(ppv.locator('.ppv-rows')).toHaveCount(0);
for (const mode of [
'Citología previa',
'VPH previo',
'Nivel de histología',
'Ronda de tamizaje',
]) {
await ppv.getByRole('radio', { name: mode, exact: true }).click();
await expect(ppv.getByRole('table', { name: mode })).toBeVisible();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0);
await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
// the score line and the methodological note stay in view in every reading
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
}
await ppv.getByRole('radio', { name: 'Total' }).click();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
}
// the biopsy requests are one more reading of the biopsy perspective, with their own heading
const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]');
await expect(
biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }),
).toBeVisible();
await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }),
).toBeVisible();
await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount(
0,
);
await expect(biopsyPpv.locator('.measure-score')).toContainText(
'solicitudes registradas (no pacientes)',
);
await expect(
biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'),
).toBeVisible();
await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible();
await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible();
await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos');
await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0);
await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }),
).toBeVisible();
// the original confirmation measure is not shown on this tab any more
await expect(confirmation.locator('details')).toHaveCount(0);
await expect(tab.getByText('medida original')).toHaveCount(0);
await expect(tab.getByText('Denominador: ')).toHaveCount(0);
// the tabs are short and the full explanation is in the tab's content
await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = confirmation.locator('app-ppv-card');
await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click();
await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas');
await expect(colposcopy.getByRole('radio')).toHaveCount(5);
const tops = await colposcopy
.locator('mat-button-toggle')
.evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size);
expect(tops).toBe(1); // one line on desktop
// the patients by HPV result: the whole as a donut, then one breakdown at a time
const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible();
await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
for (const mode of [
'Por grupo de edad',
'Por estatus de seguimiento',
'Por genotipo',
'Por tamizaje inicial o subsecuente',
]) {
await vph.getByRole('radio', { name: mode, exact: true }).click();
await expect(vph.getByRole('table', { name: mode })).toBeVisible();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(0);
await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
}
await vph.getByRole('radio', { name: 'Total' }).click();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
// the two HPV measures are told apart: reports against patients
await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText(
'Pacientes evaluadas por resultado de VPH',
);
await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText(
'Cuenta reportes, no pacientes',
);
expect(asked).toEqual([]);
});
test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const rows = page.locator('table.worklist tbody tr:not(.stage-panel)');
await expect(rows.first().locator('a')).toBeVisible();
const total = async () =>
Number(
/(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0,
);
// her age at the cut-off, and the stages: a compact line with a chevron that opens the panel
await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible();
await expect(rows.first().locator('app-stages .node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click();
const panel = page.locator('tr.stage-panel');
await expect(panel).toContainText('Toma de muestra');
await expect(panel).toContainText('Desde anterior');
await expect(panel.locator('.node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click();
await expect(panel).toHaveCount(0);
// the age filters apply before the page is cut; the name search of Rebuild is still there
const all = await total();
await page.getByLabel('Edad mínima').fill('200');
await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible();
await page.getByLabel('Edad mínima').fill('45');
await expect(async () => expect(await total()).toBeLessThan(all)).toPass();
await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible();
await page.getByRole('button', { name: 'Limpiar edades' }).click();
await expect(async () => expect(await total()).toBe(all)).toPass();
// the whole query, as the two files
const [pdf] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar PDF' }).click(),
]);
expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf');
expect(
readFileSync((await pdf.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
const [xlsx] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(),
]);
expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx');
expect(
readFileSync((await xlsx.path())!)
.subarray(0, 2)
.toString(),
).toBe('PK');
// her record: age, the detailed stages, the scales, and the file
await rows.first().locator('a').first().click();
await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:');
await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5);
await expect(page.getByText('Desde toma:').first()).toBeVisible();
await expect(page.getByText('Riesgo inmediato')).toBeVisible();
await expect(page.getByText('Riesgo a 5 años')).toBeVisible();
const [ficha] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar ficha PDF' }).click(),
]);
expect(
readFileSync((await ficha.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
expect(problems).toEqual([]);
});
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ server {
root /usr/share/nginx/html; root /usr/share/nginx/html;
location /api/ { location /api/ {
proxy_pass http://api:8000/; proxy_pass http://api:8000/;
proxy_read_timeout 30s; proxy_read_timeout 120s;
} }
location / { location / {
try_files $uri $uri/ /index.html; try_files $uri $uri/ /index.html;
+2421 -64
View File
File diff suppressed because it is too large Load Diff
+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';
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface Capabilities$Params {
}
export function capabilities(http: HttpClient, rootUrl: string, params?: Capabilities$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, capabilities.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
capabilities.PATH = '/cacu/exports/capabilities';
+34
View File
@@ -0,0 +1,34 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Document } from '../../models/document';
export interface Export$Params {
kind: string;
body: Document
}
export function export$(http: HttpClient, rootUrl: string, params: Export$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, export$.PATH, 'post');
if (params) {
rb.path('kind', params.kind, {});
rb.body(params.body, 'application/json');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
export$.PATH = '/cacu/exports/{kind}';
@@ -16,6 +16,7 @@ export interface SearchDiagnosticReport$Params {
* Patient/<id>, comma-separated * Patient/<id>, comma-separated
*/ */
subject?: (string | null); subject?: (string | null);
'stage-cutoff'?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
} }
@@ -26,6 +27,7 @@ export function searchDiagnosticReport(http: HttpClient, rootUrl: string, params
if (params) { if (params) {
rb.path('domain', params.domain, {}); rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {}); rb.query('subject', params.subject, {});
rb.query('stage-cutoff', params['stage-cutoff'], {});
rb.query('_count', params['_count'], {}); rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {}); rb.query('_offset', params['_offset'], {});
} }
+24
View File
@@ -24,6 +24,26 @@ export interface SearchPatient$Params {
'follow-up-cutoff'?: (string | null); 'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null); 'follow-up-status'?: (string | null);
/**
* each word starts a word of her name (case and accents ignored)
*/
name?: (string | null);
/**
* [system|]value: a CURP or record number (case ignored)
*/
identifier?: (string | null);
/**
* CaCu: completed years at the cut-off
*/
'follow-up-age-min'?: (number | null);
/**
* CaCu: completed years at the cut-off
*/
'follow-up-age-max'?: (number | null);
/** /**
* -recent or -risk-<outcome> * -recent or -risk-<outcome>
*/ */
@@ -56,6 +76,10 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {}); rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {}); rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {}); rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('follow-up-age-min', params['follow-up-age-min'], {});
rb.query('follow-up-age-max', params['follow-up-age-max'], {});
rb.query('_sort', params['_sort'], {}); rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {}); rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {}); rb.query('_revinclude', params['_revinclude'], {});
+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 { RequestBuilder } from '../../request-builder';
import { BodyUpload } from '../../models/body-upload'; import { BodyUpload } from '../../models/body-upload';
import { Uploaded } from '../../models/uploaded';
export interface Upload$Params { export interface Upload$Params {
body: BodyUpload body: BodyUpload
} }
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<{ export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<Uploaded>> {
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, upload.PATH, 'post'); const rb = new RequestBuilder(rootUrl, upload.PATH, 'post');
if (params) { if (params) {
rb.body(params.body, 'multipart/form-data'); rb.body(params.body, 'multipart/form-data');
@@ -26,9 +25,7 @@ export function upload(http: HttpClient, rootUrl: string, params: Upload$Params,
).pipe( ).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse), filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => { map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{ return r as StrictHttpResponse<Uploaded>;
[key: string]: string;
}>;
}) })
); );
} }
+3 -2
View File
@@ -8,12 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder'; import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain'; import { Domain } from '../../models/domain';
import { Model } from '../../models/model';
export interface Models$Params { export interface Models$Params {
domain: Domain; domain: Domain;
} }
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> { export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Model>>> {
const rb = new RequestBuilder(rootUrl, models.PATH, 'get'); const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
if (params) { if (params) {
rb.path('domain', params.domain, {}); rb.path('domain', params.domain, {});
@@ -24,7 +25,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
).pipe( ).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse), filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => { map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<string>>; return r as StrictHttpResponse<Array<Model>>;
}) })
); );
} }
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params { export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params { export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+35
View File
@@ -0,0 +1,35 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface 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}';
+32
View File
@@ -1,6 +1,14 @@
/* eslint-disable */ /* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* 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 { Capabilities$Params as Capabilities$Params } from './fn/exports/capabilities';
export { capabilities as capabilities } from './fn/exports/capabilities';
export type { Export$Params as Export$Params } from './fn/exports/export';
export { export$ as export$ } from './fn/exports/export';
export type { Domains$Params as Domains$Params } from './fn/operations/domains'; export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains'; export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health'; export type { Health$Params as Health$Params } from './fn/operations/health';
@@ -23,10 +31,18 @@ export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
export { startRun as startRun } 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 type { Schema$Params as Schema$Params } from './fn/ingest/schema';
export { schema as schema } 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 type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
export { sourcePreview as sourcePreview } 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 type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
export { sourceResources as sourceResources } 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 type { Upload$Params as Upload$Params } from './fn/ingest/upload';
export { upload as upload } from './fn/ingest/upload'; export { upload as upload } from './fn/ingest/upload';
export type { Models$Params as Models$Params } from './fn/models/models'; export type { Models$Params as Models$Params } from './fn/models/models';
@@ -59,12 +75,28 @@ export type { DecidePersons$Params as DecidePersons$Params } from './fn/review/d
export { decidePersons as decidePersons } from './fn/review/decide-persons'; export { decidePersons as decidePersons } from './fn/review/decide-persons';
export type { Reject$Params as Reject$Params } from './fn/review/reject'; export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } 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 type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status'; export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies'; export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies'; export { studies as studies } from './fn/eeg/studies';
export type { Study$Params as Study$Params } from './fn/eeg/study'; export type { Study$Params as Study$Params } from './fn/eeg/study';
export { study as study } 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 type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle'; export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition'; export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
+23
View File
@@ -2,30 +2,53 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Analysis } from './models/analysis'; export type { Analysis } from './models/analysis';
export type { Answers } from './models/answers';
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation'; export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
export type { BodyUpload } from './models/body-upload'; 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 { Condition } from './models/condition';
export type { Correction } from './models/correction'; export type { Correction } from './models/correction';
export type { Document } from './models/document';
export type { Domain } from './models/domain'; 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 { Extract } from './models/extract';
export type { Fhir } from './models/fhir'; 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 { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join'; export type { Join } from './models/join';
export type { Link } from './models/link'; 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 { Map } from './models/map';
export type { Metric } from './models/metric'; export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision'; export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline'; export type { Pipeline } from './models/pipeline';
export type { Position } from './models/position'; export type { Position } from './models/position';
export type { Provider } from './models/provider';
export type { Read } from './models/read'; export type { Read } from './models/read';
export type { Rejection } from './models/rejection'; export type { Rejection } from './models/rejection';
export type { Relation } from './models/relation';
export type { Route } from './models/route'; export type { Route } from './models/route';
export type { RunRequest } from './models/run-request'; export type { RunRequest } from './models/run-request';
export type { SavedPipeline } from './models/saved-pipeline'; export type { SavedPipeline } from './models/saved-pipeline';
export type { SignIn } from './models/sign-in';
export type { Site } from './models/site';
export type { Source } from './models/source'; export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref'; export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type';
export type { Study } from './models/study'; export type { Study } from './models/study';
export type { Target } from './models/target'; export type { Target } from './models/target';
export type { Tested } from './models/tested';
export type { Training } from './models/training'; 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 { ValidationError } from './models/validation-error';
export type { Version } from './models/version'; export type { Version } from './models/version';
+2
View File
@@ -2,10 +2,12 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Metric } from '../models/metric'; import { Metric } from '../models/metric';
import { Relation } from '../models/relation';
export interface Analysis { export interface Analysis {
age_months: (number | null); age_months: (number | null);
id: string; id: string;
level: (string | null); level: (string | null);
metrics: Array<Metric>; metrics: Array<Metric>;
relation?: Array<Relation>;
valid: (boolean | null); valid: (boolean | null);
} }
+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. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUpload { 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. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Condition { export interface Condition {
/**
* Por ejemplo «text», el texto leído del documento.
*/
column: string; column: string;
op: 'equals' | 'contains' | 'matches' | 'present'; op: 'equals' | 'contains' | 'matches' | 'present';
/**
* Lo que se busca; por ejemplo «citología».
*/
value?: string; 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). * field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/ */
export interface Correction { export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string; field: string;
record: string; record: string;
value: string; value: string;
+18
View File
@@ -0,0 +1,18 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Document {
columns: Array<string>;
parameters: Array<Array<string>>;
risk_scales?: Array<{
[key: string]: any;
}>;
row_stages?: Array<Array<{
[key: string]: string;
}>>;
rows: Array<Array<string>>;
timeline?: Array<{
[key: string]: string;
}>;
title: string;
}
+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 { export interface Extract {
column: (string | Array<string>); column: (string | Array<string>);
/**
* Dato → columna, sin leer el texto.
*/
columns?: {
[key: string]: string;
};
concept_map?: (string | null); concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
/**
* 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?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
/**
* Para el modelo de lenguaje.
*/
hints?: string; hints?: string;
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'extract'; kind?: 'extract';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
method?: 'auto' | 'llm' | 'patterns'; method?: 'auto' | 'llm' | 'patterns';
/**
* Dato → expresión con un grupo ( ).
*/
patterns?: { patterns?: {
[key: string]: string; [key: string]: string;
}; };
+5 -1
View File
@@ -11,10 +11,14 @@ import { Position } from '../models/position';
export interface Fhir { export interface Fhir {
column?: string; column?: string;
concept_map?: (string | null); concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'fhir'; kind?: 'fhir';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); 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; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'join'; kind?: 'join';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
/**
* Columna de la primera entrada = columna de la segunda.
*/
on: Array<[string, string]>; on: Array<[string, string]>;
position?: (Position | null); position?: (Position | null);
} }
+12
View File
@@ -16,8 +16,20 @@ export interface Link {
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'link'; kind?: 'link';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
/**
* Parecidos por encima de esto los ve un revisor.
*/
review?: number; review?: number;
/**
* Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).
*/
rules?: Array<string>; 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. * (core.concept_map), and its date formats.
*/ */
export interface Map { export interface Map {
/**
* La tabla de códigos del sitio.
*/
concept_map?: (string | null); concept_map?: (string | null);
/**
* Dato de la plataforma → columna del sitio.
*/
fields: { fields: {
[key: string]: string; [key: string]: string;
}; };
/**
* Por ejemplo %d/%m/%Y.
*/
formats?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'map'; kind?: 'map';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
/**
* Un dato igual para todas las filas.
*/
values?: { values?: {
[key: string]: string; [key: string]: string;
}; };
+6
View File
@@ -1,10 +1,16 @@
/* eslint-disable */ /* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric { export interface Metric {
code: string; code: string;
electrodes?: Array<Site>;
median?: (number | null);
model: (string | null); model: (string | null);
outside: (number | null); outside: (number | null);
p5?: (number | null);
p95?: (number | null);
value: number; value: number;
z: (number | null); z: (number | null);
zones?: Array<Site>;
} }
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Model {
name: string;
title: string;
}
+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). * Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
*/ */
export interface Read { export interface Read {
/**
* Donde la entrada trae cada documento.
*/
column: string; column: string;
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'read'; kind?: 'read';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
} }
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection { export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string; reason: string;
record: string; record: string;
} }
+25
View File
@@ -0,0 +1,25 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
+13 -2
View File
@@ -5,13 +5,24 @@ import { Condition } from '../models/condition';
import { Position } from '../models/position'; 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 { export interface Route {
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'route'; kind?: 'route';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
/**
* Recoge lo que nadie reconoce, para revisarlo.
*/
otherwise?: boolean;
position?: (Position | null); 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 */ /* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Guided } from '../models/guided';
import { Position } from '../models/position'; 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. * own primary key or `primary_key`; replaced whole when it has none.
*/ */
export interface Source { export interface Source {
/**
* Los de la fuente dlt.
*/
args?: { args?: {
[key: string]: any; [key: string]: any;
}; };
guided?: (Guided | null);
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'source'; kind?: 'source';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
/**
* Columnas que identifican una fila.
*/
primary_key?: Array<string>; primary_key?: Array<string>;
/**
* Cuál, si la fuente ofrece varios (una tabla).
*/
resource?: (string | null); resource?: (string | null);
/**
* Módulo:función de la fuente dlt.
*/
source: string; source: string;
/**
* Transformador dlt para los archivos.
*/
then?: (string | null); 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. * one `link` node among the inputs. Rule breaks are held for review.
*/ */
export interface Target { 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; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'target'; kind?: 'target';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); 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);
}
+16 -3
View File
@@ -4,7 +4,9 @@
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" /> <img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a> </a>
@if (domain(); as current) { @if (domain(); as current) {
<span class="title">Plataforma de Indicadores</span> <span class="title">{{
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
}}</span>
<button <button
mat-flat-button mat-flat-button
class="domain" class="domain"
@@ -16,18 +18,29 @@
</button> </button>
<mat-menu #menu="matMenu"> <mat-menu #menu="matMenu">
@for (d of others(); track d) { @for (d of others(); track d) {
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a> <a mat-menu-item [routerLink]="['/' + section(), d]">{{ labels[d] }}</a>
} }
</mat-menu> </mat-menu>
} @else { } @else {
<span class="title"></span> <span class="title"></span>
} }
@if (!onLogin()) {
<nav class="sections" aria-label="Secciones"> <nav class="sections" aria-label="Secciones">
<a routerLink="/indicadores/cacu" routerLinkActive="active">Indicadores</a> <a [routerLink]="home()" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a> <a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a> <a routerLink="/revision" routerLinkActive="active">Revisión</a>
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a> <a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
</nav> </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> </header>
<main class="main"> <main class="main">
+19 -2
View File
@@ -1,21 +1,38 @@
import { Routes } from '@angular/router'; import { Routes } from '@angular/router';
import { domainAllowed, signedIn } from './auth/auth';
export const routes: Routes = [ export const routes: Routes = [
{ path: 'login', loadComponent: () => import('./auth/login').then((m) => m.Login) },
{
path: '',
canActivateChild: [signedIn],
children: [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' }, { path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{ {
path: 'indicadores/:domain', path: 'indicadores/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores), loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
}, },
{ {
path: 'indicadores/:domain/pacientes/:id', path: 'indicadores/:domain/pacientes/:id',
canActivate: [domainAllowed],
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente), 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: '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', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
{ {
path: 'gobernanza/:domain', path: 'gobernanza/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza), loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
}, },
{ path: '**', redirectTo: 'indicadores/cacu' }, { path: '**', redirectTo: 'indicadores/cacu' },
],
},
]; ];
+43 -1
View File
@@ -21,10 +21,22 @@
.title { .title {
flex: 1; flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.25rem; font-size: 1.25rem;
font-weight: 500; font-weight: 500;
} }
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain,
.sections a,
.user {
flex-shrink: 0;
white-space: nowrap;
}
.domain { .domain {
--mat-button-filled-container-color: var(--color-primary); --mat-button-filled-container-color: var(--color-primary);
--mat-button-filled-label-text-color: var(--color-text); --mat-button-filled-label-text-color: var(--color-text);
@@ -67,8 +79,38 @@
width: clamp(155px, 15vw, 185px); width: clamp(155px, 15vw, 185px);
} }
@media (max-width: 720px) { @media (max-width: 1100px) {
.title { .title {
display: none; display: none;
} }
.header {
justify-content: space-between;
gap: var(--space-3);
}
.sections {
gap: var(--space-3);
}
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name {
display: none;
}
.domain {
max-width: 15rem;
}
.domain ::ng-deep .mdc-button__label {
overflow: hidden;
text-overflow: ellipsis;
}
}
@media (max-width: 720px) {
.header {
flex-wrap: wrap;
padding-block: var(--space-2);
}
}
.user {
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 { Api } from './api/api';
import { domains } from './api/fn/operations/domains'; import { domains } from './api/fn/operations/domains';
import { Domain } from './api/models/domain'; import { Domain } from './api/models/domain';
import { Auth } from './auth/auth';
export const DOMAINS: Record<Domain, string> = { export const DOMAINS: Record<Domain, string> = {
cacu: 'Cáncer cervicouterino', cacu: 'Cáncer cervicouterino',
cama: 'Cáncer de mama', 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. */ /** 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 { export class App {
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly router = inject(Router); private readonly router = inject(Router);
protected readonly auth = inject(Auth);
protected readonly labels = DOMAINS; protected readonly labels = DOMAINS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly url = toSignal( private readonly url = toSignal(
@@ -41,11 +43,23 @@ export class App {
), ),
{ initialValue: '' }, { initialValue: '' },
); );
/** The domain of an indicator page, if this is one. */ /** The section and domain of a page that has one (indicators, governance): the switcher
protected readonly domain = computed( * moves between that section's domains. */
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined, private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
); protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
protected readonly others = computed(() => protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain()), (this.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}`);
}
}
+59 -6
View File
@@ -29,7 +29,9 @@
</span> </span>
@if (pipelineId()) { @if (pipelineId()) {
@for (k of kinds; track k[0]) { @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> <span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button> <button mat-stroked-button (click)="save()">Guardar</button>
@@ -70,10 +72,7 @@
<mat-icon>delete</mat-icon> <mat-icon>delete</mat-icon>
</button> </button>
</div> </div>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full"> <p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) { @if (d.inputs?.length) {
<div class="inputs"> <div class="inputs">
Entradas: Entradas:
@@ -84,17 +83,71 @@
} }
</div> </div>
} @else if (d.kind !== 'source') { } @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p> <p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
}
<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 <formly-form
[form]="form" [form]="form"
[fields]="fields()" [fields]="fields()"
[model]="model" [model]="model"
[options]="formOptions"
(modelChange)="edited($event)" (modelChange)="edited($event)"
/> />
@if (conceptMap(d); as cm) { @if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="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> <button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) { @if (preview(); as rows) {
<div class="preview"> <div class="preview">
+83
View File
@@ -109,3 +109,86 @@ h2 {
width: auto; 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 { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core'; import {
Component,
computed,
effect,
inject,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list'; 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 { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core'; import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema'; import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material'; 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 type { Source } from '../api/models/source';
import { ConceptMapEditor } from './concept-map-editor'; import { ConceptMapEditor } from './concept-map-editor';
import { FORMLY_TYPES, nodeSchema } from './schema-form'; import { FORMLY_TYPES, nodeSchema } from './schema-form';
import { SourceDialog, SourceDialogData, SourceDialogResult } from './source-dialog';
type Doc = Pipeline['nodes'][number]; type Doc = Pipeline['nodes'][number];
type Kind = NonNullable<Doc['kind']>; 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> = { export const KINDS: Record<Kind, string> = {
source: 'Fuente', source: 'Fuente de datos',
read: 'Leer', read: 'Leer documentos',
route: 'Filtrar', route: 'Separar por tipo',
map: 'Mapear', map: 'Traducir códigos',
extract: 'Extraer', extract: 'Extraer datos',
fhir: 'FHIR', fhir: 'Leer FHIR',
join: 'Unir', join: 'Unir',
link: 'Vincular', link: 'Identificar a la persona',
target: 'Destino', 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_]*$/; const ID = /^[a-z][a-z0-9_]*$/;
@@ -73,7 +98,9 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule, MatIconModule,
MatInputModule, MatInputModule,
MatListModule, MatListModule,
MatTabsModule,
MatTableModule, MatTableModule,
MatTooltipModule,
Vflow, Vflow,
ConceptMapEditor, ConceptMapEditor,
], ],
@@ -85,7 +112,12 @@ const ID = /^[a-z][a-z0-9_]*$/;
export class Conectar { export class Conectar {
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema); private readonly jsonschema = inject(FormlyJsonschema);
private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][]; protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP;
/** "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) }); protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) }); private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -109,6 +141,20 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
}); });
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({}); protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {}; protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */ /** The selected node's form, generated from its kind's JSON Schema. */
@@ -158,10 +204,47 @@ export class Conectar {
} }
protected add(kind: Kind): void { 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; let n = 1;
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++; while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
const id = `${kind}_${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.docs.update((ds) => [...ds, doc]);
this.nodes.update((ns) => [ this.nodes.update((ns) => [
...ns, ...ns,
@@ -204,6 +287,13 @@ export class Conectar {
); );
this.form = new UntypedFormGroup({}); this.form = new UntypedFormGroup({});
this.preview.set(undefined); 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. */ /** 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 { protected rename(to: string): void {
const from = this.selected(); const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return; if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
@@ -296,7 +420,7 @@ export class Conectar {
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source }) ? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 }); : await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows); this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.'); this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
} catch (e) { } catch (e) {
this.message.set(problem(e)); this.message.set(problem(e));
} }
@@ -322,7 +446,14 @@ export class Conectar {
} }
function text(d: Doc): string { function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`; // ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
`<div class="node-caption" title="${kind} · ${name}">` +
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
);
} }
/** Each node's distance from the sources: its column when it has no saved position. */ /** Each node's distance from the sources: its column when it has no saved position. */
@@ -349,3 +480,10 @@ function problem(e: unknown): string {
} }
return String(e); return String(e);
} }
function escape(text: string): string {
return text.replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!,
);
}
+15 -3
View File
@@ -16,6 +16,12 @@ const PIPELINE = {
when: { type: 'array', items: { $ref: '#/$defs/Condition' } }, when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' }, resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' }, values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
on: {
type: 'array',
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
},
extra: { type: 'object', title: 'Extra' },
source: { type: 'string', advanced: true },
}, },
}, },
}, },
@@ -25,7 +31,7 @@ describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any; const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => { it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']); expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
expect(schema.required).toEqual(['when']); expect(schema.required).toEqual(['when']);
}); });
@@ -34,7 +40,13 @@ describe('node forms from the pipeline schema', () => {
expect(schema.properties.resource.type).toBe('string'); expect(schema.properties.resource.type).toBe('string');
}); });
it('edits maps as JSON', () => { it('edits maps of texts and pairs as rows', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json'); expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
});
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
expect(schema.properties.extra).toBeUndefined();
expect(schema.properties.source).toBeUndefined();
}); });
}); });
+236 -2
View File
@@ -3,6 +3,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { import {
ConfigOption, ConfigOption,
@@ -27,11 +28,29 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!; )!;
const node = structuredClone(defs[name]); const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field]; for (const field of CANVAS_FIELDS) delete node.properties?.[field];
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f)); // The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
delete node.properties![field];
}
node.required = (node.required ?? []).filter(
(f) => !CANVAS_FIELDS.includes(f) && f in (node.properties ?? {}),
);
delete node.additionalProperties; delete node.additionalProperties;
return simplify(node, defs); return simplify(node, defs);
} }
function isJson(schema: Schema): boolean {
return (
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
'json'
);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema { function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) { if (schema.$ref) {
const { $ref, ...rest } = schema; const { $ref, ...rest } = schema;
@@ -45,6 +64,34 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return simplify({ ...kept[0], ...rest }, defs); return simplify({ ...kept[0], ...rest }, defs);
} }
} }
const values = schema.additionalProperties as Schema | boolean | undefined;
if (
schema.type === 'object' &&
!schema.properties &&
typeof values === 'object' &&
values.type === 'string'
) {
const byField = (schema as { keys?: string }).keys === 'field';
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
} as Schema;
}
const pair = schema.items as Schema | undefined;
if (
schema.type === 'array' &&
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'pairs' } },
} as Schema;
}
const isMap = schema.type === 'object' && !schema.properties; const isMap = schema.type === 'object' && !schema.properties;
const isTuple = const isTuple =
schema.type === 'array' && schema.type === 'array' &&
@@ -117,7 +164,7 @@ export class ArrayType extends FieldArrayType {}
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule], imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: ` template: `
<mat-form-field appearance="outline" class="json"> <mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }} (JSON)</mat-label> <mat-label>{{ props.label }}</mat-label>
<textarea <textarea
matInput matInput
rows="4" rows="4"
@@ -152,11 +199,198 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
} }
} }
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
@if (props['fieldKeys']) {
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
@for (o of keyOptions(row[0]); track o[0]) {
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[value]="row[0]"
(change)="edit(i, $any($event.target).value, row[1])"
/>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
<mat-label>Valor</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
column-gap: 4px;
row-gap: 6px;
padding: 8px 0;
border-bottom: 1px solid var(--color-border);
}
.key,
.value {
min-width: 0;
grid-column: 1;
}
.row button {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
string | undefined;
const titles: Record<string, string> = entity
? (all[entity] ?? {})
: Object.assign({}, ...Object.values(all));
const options = Object.entries(titles);
if (current && !(current in titles)) options.unshift([current, current]);
return options;
}
protected rows(): [string, string][] {
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
this.formControl.markAsDirty();
}
protected edit(i: number, key: string, value: string): void {
const rows = this.rows();
rows[i] = [key.trim(), value];
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
: undefined;
let n = rows.length + 1;
while (used.has(`campo_${n}`)) n++;
this.save([...rows, [free ?? `campo_${n}`, '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Primera entrada</mat-label>
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
</mat-form-field>
<span>=</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Segunda entrada</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 6px;
}
.half {
flex: 1;
min-width: 0;
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(rows);
this.formControl.markAsDirty();
}
protected edit(i: number, side: 0 | 1, value: string): void {
const rows = this.rows();
rows[i][side] = value.trim();
this.save(rows);
}
protected add(): void {
this.save([...this.rows(), ['', '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
export const FORMLY_TYPES: ConfigOption = { export const FORMLY_TYPES: ConfigOption = {
types: [ types: [
{ name: 'object', component: ObjectType }, { name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType }, { name: 'array', component: ArrayType },
{ name: 'json', component: JsonType }, { name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ name: 'enum', extends: 'select' }, { name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' }, { name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } }, { name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
+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;
}
+359
View File
@@ -0,0 +1,359 @@
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;
}
/** 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);
}
}
/** The tables a database listed, for its table field. */
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : [];
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
protected tables(): string[] {
return this.tableList();
}
/** 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',
};
+57
View File
@@ -0,0 +1,57 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
export interface ExportStage {
state: string;
provenance?: string;
label?: string;
date?: string;
prev?: string;
start?: string;
}
export interface ExportRiskScale {
label: string;
value?: number;
low?: number;
high?: number;
outcome?: string;
model?: string;
horizon?: string;
}
export interface ExportDocument {
title: string;
parameters: string[][];
columns: string[];
rows: string[][];
timeline?: ExportStage[];
row_stages?: ExportStage[][];
risk_scales?: ExportRiskScale[];
}
export async function downloadDocument(
http: HttpClient,
format: 'pdf' | 'xlsx',
doc: ExportDocument,
) {
let blob: Blob;
try {
blob = await firstValueFrom(
http.post(`/api/cacu/exports/${format}`, doc, { responseType: 'blob' }),
);
} catch (error) {
if (error instanceof HttpErrorResponse && error.error instanceof Blob) {
try {
const body = JSON.parse(await error.error.text());
if (typeof body.detail === 'string') throw new Error(body.detail);
} catch (parsed) {
if (parsed instanceof Error && !(parsed instanceof SyntaxError)) throw parsed;
}
}
throw error;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cacu-${format === 'pdf' ? 'reporte.pdf' : 'seguimiento.xlsx'}`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
}
+9 -9
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures } from './figures'; import { interpretabilityFigures, scenarioFigure } from './figures';
describe('governance figures', () => { describe('governance figures', () => {
it('draws a survival report as curves with bands and the model points', () => { it('draws a survival report as curves with bands and the model points', () => {
@@ -13,7 +13,7 @@ describe('governance figures', () => {
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05); expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
}); });
it("draws each survival scenario after the cohort's curves, titled with its deaths", () => { it('leaves the survival scenarios to the patient record, which draws them whole', () => {
const scenario = { const scenario = {
escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)', escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)',
n: 1142, n: 1142,
@@ -30,14 +30,14 @@ describe('governance figures', () => {
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] }, predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
escenarios: [scenario], escenarios: [scenario],
}); });
expect(found.length).toBe(2); expect(found.length).toBe(1); // the cohort's curves only
expect(found[1].title).toContain('fallecidos = 308'); const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]); expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
}); });
it('draws a recurrence scenario: KM band, both Weibulls and the model points', () => { it('leaves recurrence scenarios to the patient record', () => {
const [found] = interpretabilityFigures({ const found = interpretabilityFigures({
kind: 'scenarios', kind: 'scenarios',
recurrencia: { recurrencia: {
horizons_months: [12, 36], horizons_months: [12, 36],
@@ -55,7 +55,7 @@ describe('governance figures', () => {
], ],
}, },
}); });
expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points expect(found).toEqual([]);
}); });
it('draws an age curve with its centile band', () => { it('draws an age curve with its centile band', () => {
+66 -24
View File
@@ -1,5 +1,6 @@
import type { Figure } from '../plot'; import type { Figure } from '../plot';
import { PALETTE } from '../plot'; import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them. */ /** A curve with its band, as the reports give them. */
interface Band { interface Band {
@@ -70,15 +71,7 @@ export function interpretabilityFigures(
}, },
}, },
}, },
// Its clinical scenarios, those with enough deaths to draw. // Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
...((report['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
]; ];
} }
case 'subgroups': case 'subgroups':
@@ -147,17 +140,8 @@ export function interpretabilityFigures(
}, },
]; ];
} }
case 'scenarios': case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return (report['recurrencia']['escenarios'] as any[]) return [];
.slice(0, 6)
.map((e) =>
scenarioFigure(
`${e.cohorte_nombre} · ${e.escenario} (n = ${e.n}, ${e.recaidas} recaídas)`,
e,
report['recurrencia']['horizons_months'],
'Supervivencia libre de recaída',
),
);
case 'age_curves': { case 'age_curves': {
// The metric's own curve; a topography has only electrodes: its first one. // The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0]; const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
@@ -205,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: default:
return []; return [];
} }
} }
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull, /** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band. */ * and the model's points with their bootstrap band (also a patient's, in her record). */
function scenarioFigure( export function scenarioFigure(
title: string, title: string,
e: any, e: any,
horizons: number[], horizons: number[],
@@ -246,8 +286,10 @@ function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB), points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
], ],
layout: { layout: {
xaxis: { title: { text: 'Meses desde el diagnóstico' } }, // One label per month with every curve's survival there, as percentages.
yaxis: { title: { text: yTitle } }, hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
}, },
}, },
}; };
+53 -19
View File
@@ -1,10 +1,6 @@
<section class="page"> <section class="page">
<h1>Gobernanza de modelos</h1> <h1>{{ labels[domain()] ?? domain() }}</h1>
<nav class="domains" aria-label="Dominios"> <p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
@for (d of domains.value() ?? []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<form class="card actions" (submit)="$event.preventDefault()"> <form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -17,13 +13,44 @@
name="asOf" name="asOf"
/> />
</mat-form-field> </mat-form-field>
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button> @if (confirming(); as c) {
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button> <span class="confirm" role="alert">
{{
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') { @if (domain() === 'tea') {
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button> <button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
Analizar EEG
</button>
}
} }
@if (run(); as r) { @if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span> <span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
@if (running()) {
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
}
} }
</form> </form>
@if (message()) { @if (message()) {
@@ -31,19 +58,21 @@
} }
@if (models.isLoading()) { @if (models.isLoading()) {
<p class="muted">Cargando modelos…</p> <app-loading what="los modelos" />
} @else if (!models.value()?.length) { } @else if (!models.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p> <p class="muted empty">Sin modelos entrenados en este dominio.</p>
} }
@for (m of models.value() ?? []; track m.name) { @for (m of models.value() ?? []; track m.name) {
<div class="card model"> <div class="card model">
<h2>{{ m.name }}</h2> <h2>
{{ m.title }} <code class="muted code">{{ m.name }}</code>
</h2>
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
<th>Versión</th> <th>Versión</th>
<th>Creada</th> <th>Creada</th>
<th>Entrenamiento / prueba</th> <th>Datos</th>
<th>Informes</th> <th>Informes</th>
<th>Validación clínica</th> <th>Validación clínica</th>
<th></th> <th></th>
@@ -59,10 +88,9 @@
} }
</td> </td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td> <td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num"> <td class="nowrap">{{ sizes(v) }}</td>
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td> <td>
<div class="reports">
@for (r of v.reports; track r) { @for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{ <a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r reportNames[r] ?? r
@@ -77,14 +105,20 @@
Ver gráficas Ver gráficas
</button> </button>
} }
</div>
</td> </td>
<td> <td>
@if (!v.reports.includes('clinical_validation')) { @if (!v.reports.includes('clinical_validation')) {
<input <input
#file
type="file" type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version" hidden
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
(change)="upload(m.name, v.version, $event)" (change)="upload(m.name, v.version, $event)"
/> />
<button mat-stroked-button type="button" (click)="file.click()">
Subir validación clínica
</button>
} @else { } @else {
Agregada Agregada
} }
@@ -105,7 +139,7 @@
@if (chosen(); as c) { @if (chosen(); as c) {
<div class="card"> <div class="card">
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2> <h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) { @for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3> <h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" /> <app-plot [figure]="f.figure" [height]="360" />
+32 -12
View File
@@ -1,18 +1,8 @@
:host { :host {
display: block; display: block;
} }
h1 { .subtitle {
text-align: center; margin: 4px 0 var(--space-4);
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
} }
.actions { .actions {
display: flex; display: flex;
@@ -30,6 +20,7 @@ h1 {
white-space: nowrap; white-space: nowrap;
} }
.badge { .badge {
white-space: nowrap;
margin-left: var(--space-2); margin-left: var(--space-2);
padding: 2px 8px; padding: 2px 8px;
border-radius: 999px; border-radius: 999px;
@@ -45,3 +36,32 @@ td a {
padding: 48px 0; padding: 48px 0;
text-align: center; text-align: center;
} }
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
}
.reports a {
margin-right: 0;
}
h2 .code {
font-size: 12px;
font-weight: 400;
margin-left: var(--space-2);
}
.confirm {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: 4px 4px 4px 12px;
border-radius: 8px;
background: var(--color-surface-warning, #fdf3dc);
}
td button {
white-space: nowrap;
}
+64 -18
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { DatePipe, DecimalPipe } from '@angular/common'; import { DatePipe, DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
@@ -5,7 +6,6 @@ import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration'; import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
@@ -16,15 +16,16 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import { score } from '../api/fn/models/score'; import { score } from '../api/fn/models/score';
import { train } from '../api/fn/models/train'; import { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions'; import { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import { studies } from '../api/fn/eeg/studies'; import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study'; import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status'; import { runStatus } from '../api/fn/runs/run-status';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import type { Version } from '../api/models/version'; import type { Version } from '../api/models/version';
import { DOMAINS } from '../app'; import { DOMAINS } from '../app';
import { Plot } from '../plot'; import { Plot } from '../plot';
import { interpretabilityFigures } from './figures'; import { interpretabilityFigures } from './figures';
import { Loading } from '../loading';
const REPORTS: Record<string, string> = { const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica', technical_validation: 'Validación técnica',
@@ -38,13 +39,13 @@ const REPORTS: Record<string, string> = {
@Component({ @Component({
selector: 'app-gobernanza', selector: 'app-gobernanza',
imports: [ imports: [
Loading,
DatePipe, DatePipe,
DecimalPipe, DecimalPipe,
FormsModule, FormsModule,
MatButtonModule, MatButtonModule,
MatFormFieldModule, MatFormFieldModule,
MatInputModule, MatInputModule,
RouterLink,
Plot, Plot,
], ],
templateUrl: './gobernanza.html', templateUrl: './gobernanza.html',
@@ -57,15 +58,15 @@ export class Gobernanza {
protected readonly labels = DOMAINS as Record<string, string>; protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS; protected readonly reportNames = REPORTS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly refreshed = signal(0); private readonly refreshed = signal(0);
protected readonly models = resource({ protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }), params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
loader: async ({ params: { domain } }) => { loader: async ({ params: { domain } }) => {
const names = await this.api.invoke(models, { domain }); const found = await this.api.invoke(models, { domain });
return Promise.all( return Promise.all(
names.map(async (name) => ({ found.map(async ({ name, title }) => ({
name, name,
title,
versions: await this.api.invoke(versions, { domain, name }), versions: await this.api.invoke(versions, { domain, name }),
})), })),
); );
@@ -91,15 +92,43 @@ export class Gobernanza {
params: () => this.eeg(), params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }), loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
}); });
protected readonly metricNames: Record<string, string> = { protected readonly metricNames = METRIC_NAMES;
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
protected readonly asOf = signal(''); protected readonly asOf = signal('');
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined); protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
undefined,
);
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
protected readonly running = computed(() => {
const r = this.run();
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
});
protected readonly STATUS: Record<string, string> = {
QUEUED: 'en cola',
NOT_STARTED: 'por iniciar',
STARTING: 'iniciando',
STARTED: 'en curso',
SUCCESS: 'terminado',
FAILURE: 'con error',
CANCELING: 'deteniéndose',
CANCELED: 'detenido',
};
/** A model's title by its name, for messages. */
protected titleOf(name: string): string {
return this.models.value()?.find((m) => m.name === name)?.title ?? name;
}
/** What a version learned from, as its metrics say it (each kind of model its own). */
protected sizes(v: Version): string {
const m = v.metrics;
const n = (x: number) => x.toLocaleString('es-MX');
if (m['n_train'] !== undefined)
return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`;
if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`;
if (m['children'] !== undefined) return `${n(m['children'])} niños`;
const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox'));
if (c) return `C-index ${c[1].toFixed(3)}`;
return '—';
}
protected readonly message = signal(''); protected readonly message = signal('');
protected champion(v: Version): boolean { protected champion(v: Version): boolean {
@@ -120,18 +149,27 @@ export class Gobernanza {
// OpenAPI's binary is typed as a string; the request builder sends the File as is. // OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string }, body: { file: file as unknown as string },
}); });
this.message.set(`Validación clínica agregada a ${name} v${version}.`); this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} }
protected async promote(name: string, version: number): Promise<void> { protected async promote(name: string, version: number): Promise<void> {
try { try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${name} v${version} es ahora la versión en producción.`); this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} catch (e) { } catch (e) {
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
this.message.set(`No se promovió: ${detail ?? 'error'}`); // "<model> v1 has no clinical_validation, interpretability": the reports it lacks
const missing = /has no (.+)$/.exec(String(detail ?? ''))?.[1];
this.message.set(
missing
? `No se promovió: faltan informes (${missing
.split(', ')
.map((r) => this.reportNames[r] ?? r)
.join(', ')}).`
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
);
} }
} }
@@ -143,14 +181,22 @@ export class Gobernanza {
private async follow(run_id: string, label: string): Promise<void> { private async follow(run_id: string, label: string): Promise<void> {
for (;;) { for (;;) {
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
this.run.set({ kind: label, status }); this.run.set({ id: run_id, kind: label, status });
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
await new Promise((r) => setTimeout(r, 2000)); await new Promise((r) => setTimeout(r, 2000));
} }
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} }
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
}
protected async start(kind: 'train' | 'score'): Promise<void> { protected async start(kind: 'train' | 'score'): Promise<void> {
this.confirming.set(undefined);
const domain = this.domain() as Domain; const domain = this.domain() as Domain;
const { run_id } = const { run_id } =
kind === 'train' kind === 'train'
+157
View File
@@ -0,0 +1,157 @@
import { describe, expect, it } from 'vitest';
import {
BIOPSY_REPORTS,
CYTOLOGY_REPORTS,
distribution,
durationMax,
durationRows,
HPV_REPORTS,
icdRows,
requests,
withoutHidden,
} from './cacu-results';
import { PAGES } from './pages';
import { PPV_NOTES, Reading, STRATA, name } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: {
category: Object.fromEntries(
Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
describe('distributions of reports', () => {
it('counts HPV reports and keeps inconsistent and zero categories', () => {
const d = distribution(
report(4, { negative: 2, positive_16: 1, inconsistent: 1 }),
HPV_REPORTS,
)!;
expect(d.total).toBe(4);
expect(d.rows.map((r) => r.count)).toEqual([2, 1, 0, 0, 0, 0, 1]);
expect(d.outside).toBe(0);
});
it('leaves what the table does not list outside it and says how much is without data', () => {
const d = distribution(
report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }),
BIOPSY_REPORTS,
)!;
expect(d.total).toBe(3);
expect(d.noData).toBe(1);
expect(d.outside).toBe(2);
});
it('does not invent a report: missing, or counts that do not add up, draw nothing; zero is zero', () => {
expect(distribution(undefined, HPV_REPORTS)).toBeUndefined();
expect(distribution(report(2, { normal: 1 }), BIOPSY_REPORTS)).toBeUndefined();
expect(distribution(report(0, {}), HPV_REPORTS)).toMatchObject({
total: 0,
max: 0,
outside: 0,
});
});
});
describe('the categories a table leaves out', () => {
const hidden = ['positive_incomplete', 'inconsistent'];
it('lists the rest, keeps the total and the percentage denominator, and counts what it hides', () => {
const d = distribution(
report(10, { negative: 5, positive_16: 2, positive_incomplete: 2, inconsistent: 1 }),
HPV_REPORTS,
)!;
const v = withoutHidden(d, hidden);
expect(d.total).toBe(10);
expect(v.shown.map((r) => r.code)).not.toContain('positive_incomplete');
expect(v.shown.map((r) => r.code)).not.toContain('inconsistent');
expect(v.hiddenCount).toBe(3);
expect(v.max).toBe(5);
// nothing hidden: the rows are all of them and the count is zero (the page adds no note)
expect(withoutHidden(d).shown).toHaveLength(HPV_REPORTS.length);
expect(withoutHidden(d).hiddenCount).toBe(0);
});
it('is the page choice for HPV; cytology and biopsy keep every category', () => {
const results = PAGES['cacu'].clinical.find((s) => s.kind === 'results')!;
if (results.kind !== 'results') throw new Error('no joint card');
expect(results.hpv.hide).toEqual(hidden);
expect(results.cytology.hide).toBeUndefined();
expect(results.biopsy.hide).toBeUndefined();
expect(CYTOLOGY_REPORTS.map((r) => r[0])).toEqual([
'NILM',
'ASC-US',
'LSIL',
'ASC-H',
'HSIL',
'CIS',
]);
});
});
describe('biopsy requests', () => {
it('reads every state of the request and keeps them apart from patients', () => {
const r = requests(
report(9, { high_grade: 3, below_high_grade: 2, pending: 2, no_grade: 1, ambiguous: 1 }),
)!;
expect(r).toMatchObject({ total: 9, high: 3, below: 2, pending: 2, noGrade: 1, ambiguous: 1 });
expect(r.unclassified + r.inconsistent).toBe(0);
});
it('is none for a missing, failed or inconsistent report, and a zero total is a real zero', () => {
expect(requests(undefined)).toBeUndefined();
expect(requests({ ...report(1, { pending: 1 }), error: true })).toBeUndefined();
expect(requests(report(3, { pending: 1 }))).toBeUndefined();
expect(requests(report(0, {}))?.total).toBe(0);
});
});
describe('ICD-10 breakdown', () => {
it('lists each code with its median and quartiles, most frequent first', () => {
const r: Reading = {
populations: { 'initial-population': 3, 'measure-observation': 3 },
strata: {
diagnosis_code: {
C53: { 'measure-observation': 2 },
sin_codigo: { 'measure-observation': 1 },
},
},
stratumScores: {
diagnosis_code: {
C53: { median: 30, low: 25, high: 40 },
sin_codigo: { median: 12 },
},
},
};
expect(icdRows(r)).toEqual([
{ label: 'C53', count: 2, median: 30, low: 25, high: 40 },
{ label: 'Sin código disponible', count: 1, median: 12 },
]);
expect(icdRows(undefined)).toEqual([]);
});
});
describe('route by steps', () => {
const at = (score?: number, n = 4, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
it('keeps every step, tells absent from zero and scales from zero to the largest quartile', () => {
const rows = durationRows([
{ label: 'a', r: at(0, 3, 0, 2) },
{ label: 'b', r: at(undefined) },
{ label: 'c', r: at(13, 4, 9, 41) },
{ label: 'd', r: undefined },
]);
expect(rows.map((r) => r.label)).toEqual(['a', 'b', 'c', 'd']);
expect(rows[0]).toMatchObject({ median: 0, observations: 3, low: 0, high: 2 });
expect(rows[1].median).toBeUndefined();
expect(rows[1].observations).toBeUndefined();
expect(rows[3].median).toBeUndefined();
expect(durationMax(rows)).toBe(41);
expect(durationMax(durationRows([{ label: 'x', r: undefined }]))).toBe(0);
});
});
+167
View File
@@ -0,0 +1,167 @@
import type { Reading } from './measures';
/** One category of a distribution: its code in the report, its words and its colour. */
export type DistRow = readonly [code: string, label: string, color: string];
/** A distribution drawn as a table with a bar per category (CaCu's results of HPV and biopsy). */
export interface Distribution {
rows: { code: string; label: string; color: string; count: number }[];
/** units in the categories shown */
total: number;
/** units of the period that are in none of them */
outside: number;
max: number;
/** units the report counts as "no data" (no grade, no result) */
noData: number;
}
/** The categories of a report's `category` stratum, as counts of units. The strata must add up
* to the population: otherwise the report is not trusted and nothing is drawn. A category the
* report does not list is a zero, a missing report is not. */
export function distribution(
reading: Reading | undefined,
categories: readonly DistRow[],
): Distribution | undefined {
const cells = reading?.strata['category'];
const population = reading?.populations['initial-population'];
if (!cells || population === undefined) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (
counts.some((n) => n === undefined || !Number.isInteger(n) || n < 0) ||
counts.reduce((a, b) => a + b, 0) !== population
)
return undefined;
const rows = categories.map(([code, label, color]) => ({
code,
label,
color,
count: cells[code]?.['initial-population'] ?? 0,
}));
const total = rows.reduce((sum, row) => sum + row.count, 0);
return {
rows,
total,
outside: population - total,
max: Math.max(0, ...rows.map((row) => row.count)),
noData: cells['no_data']?.['initial-population'] ?? 0,
};
}
/** Cytology results by Bethesda category (one sample per patient, the latest valid). */
export const CYTOLOGY_REPORTS: readonly DistRow[] = [
['NILM', 'Normal', '#408651'],
['ASC-US', 'ASC-US', '#2778B8'],
['LSIL', 'LIEBG', '#B19525'],
['ASC-H', 'ASC-H', '#7955B1'],
['HSIL', 'LIEAG', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
];
/** The rows a table lists once some categories are left out of it: the total, the percentages and
* the units outside stay as the report gives them (nothing is recomputed); only the rows, the
* bars' scale and a count of what is not listed change. */
export function withoutHidden(d: Distribution, hide: readonly string[] = []) {
const shown = d.rows.filter((r) => !hide.includes(r.code));
return {
shown,
max: Math.max(0, ...shown.map((r) => r.count)),
hiddenCount: d.rows.filter((r) => hide.includes(r.code)).reduce((n, r) => n + r.count, 0),
};
}
/** HPV reports by genotype (one report per patient and sample date). */
export const HPV_REPORTS: readonly DistRow[] = [
['negative', 'Negativo', '#42a77e'],
['positive_16', 'Positivo 16 exclusivamente', '#df8640'],
['positive_18', 'Positivo 18 exclusivamente', '#c29c42'],
['positive_16_18', 'Positivo 16 y 18', '#c24269'],
['positive_other', 'Positivo sin detección de 16/18', '#a8c243'],
['positive_incomplete', 'Positivo con genotipificación incompleta', '#9c42c2'],
['inconsistent', 'No clasificable o inconsistente', '#687786'],
];
/** Biopsy reports by the grade they state. */
export const BIOPSY_REPORTS: readonly DistRow[] = [
['normal', 'Normal', '#408651'],
['LSIL', 'LIEBG (CIN 1)', '#B19525'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
['carcinoma', 'Carcinoma invasor', '#8D4C79'],
];
/** The ICD-10 codes of the diagnosis notes, each with its median and quartiles of days from the
* sample to the diagnosis (an exploratory grouping by the dates that link them). */
export function icdRows(reading: Reading | undefined) {
const scores = reading?.stratumScores?.['diagnosis_code'] ?? {};
return Object.entries(scores)
.map(([label, score]) => ({
label: label
.replace('sin_codigo', 'Sin código disponible')
.replace('ambiguo', 'Diagnóstico ambiguo'),
count: reading?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0,
...score,
}))
.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
}
/** The biopsy requests on record by their state at the cut-off; they are requests, not patients. */
export interface Requests {
total: number;
high: number;
below: number;
pending: number;
noGrade: number;
unclassified: number;
inconsistent: number;
ambiguous: number;
}
/** None when the report is missing, errored or does not add up (the page then says so). */
export function requests(reading: Reading | undefined): Requests | undefined {
const total = reading?.populations['initial-population'];
const cells = reading?.strata['category'];
if (!reading || reading.error || total === undefined || !cells) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (
!Number.isInteger(total) ||
total < 0 ||
counts.some((n) => !Number.isInteger(n) || n < 0) ||
counts.reduce((sum, n) => sum + n, 0) !== total
)
return undefined;
const of = (key: string) => cells[key]?.['initial-population'] ?? 0;
return {
total,
high: of('high_grade'),
below: of('below_high_grade'),
pending: of('pending'),
noGrade: of('no_grade'),
unclassified: of('unclassified'),
inconsistent: of('inconsistent'),
ambiguous: of('ambiguous'),
};
}
/** One row of a duration table: the median days, how many measurements and the quartiles. A
* step with no median keeps its row and says nothing (absent is not zero). */
export interface DurationRow {
label: string;
median?: number;
observations?: number;
low?: number;
high?: number;
}
export function durationRows(steps: { label: string; r: Reading | undefined }[]): DurationRow[] {
return steps.map(({ label, r }) => ({
label,
median: r?.score,
observations: r?.score === undefined ? undefined : r.populations['measure-observation'],
low: r?.score === undefined ? undefined : r.low,
high: r?.score === undefined ? undefined : r.high,
}));
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { requestsAlternate } from './confirmation';
import { Reading } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: {
category: Object.fromEntries(
Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
describe('biopsy requests as a reading of the biopsy card', () => {
it('keeps the request denominator, bars and secondary counts of the old card', () => {
const a = requestsAlternate(report(13, { high_grade: 9, below_high_grade: 4 }), true);
expect(a.score).toBe('69.2 %');
expect(a.detail).toContain('9 de 13 solicitudes registradas (no pacientes)');
expect(a.rows.map((r) => [r.label, r.numerator, r.denominator])).toEqual([
['LIEAG o más', 9, 13],
['Menor que LIEAG', 4, 13],
]);
expect(a.lines[0]).toContain('Pendientes: 0 · Sin grado: 0 · No clasificables: 0');
expect(a.note).toContain('no se pide un corte histórico (as-of)');
});
it('shows pending and ungraded requests in the denominator, not as a result', () => {
const a = requestsAlternate(
report(10, { high_grade: 2, below_high_grade: 1, pending: 4, no_grade: 2, ambiguous: 1 }),
true,
);
expect(a.rows[0].denominator).toBe(10);
expect(a.lines[0]).toContain('Pendientes: 4 · Sin grado: 2');
expect(a.lines[0]).toContain('ambiguos: 1');
});
it('tells no records (a zero) from a missing, failed or inconsistent report', () => {
expect(requestsAlternate(report(0, {}), true).message).toContain('denominador 0');
expect(requestsAlternate(report(0, {}), true).score).toBe('0 solicitudes');
expect(requestsAlternate(undefined, true).message).toContain('No disponible para este periodo');
expect(requestsAlternate(undefined, false).message).toContain('no publicada');
const failed = requestsAlternate({ ...report(1, { pending: 1 }), error: true }, true);
expect(failed.alert).toBe(true);
expect(requestsAlternate(report(5, { pending: 1 }), true).alert).toBe(true);
});
});
+73
View File
@@ -0,0 +1,73 @@
import { requests } from './cacu-results';
import { Reading } from './measures';
import { PpvAlternate } from './ppv';
/** The biopsy requests as one more reading of the biopsy PPV card. They are requests, not
* patients, and the denominator is every request on record (pending and ungraded ones too); the
* histological threshold is high grade (LIEAG or more), not the PPV's LIEBG or more. */
export function requestsAlternate(reading: Reading | undefined, published: boolean): PpvAlternate {
const base = {
label: 'Solicitudes de biopsia',
title: 'Confirmación por solicitudes de biopsia registradas',
note:
'La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones. ' +
'Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud; no se pide un corte ' +
'histórico (as-of) porque la medida no lo admite.',
caption:
'Solicitudes, no pacientes: cada barra cuenta las solicitudes con ese resultado sobre todas las solicitudes ' +
'registradas, incluidas las pendientes y las que no tienen grado.',
rows: [],
lines: [],
};
const without = (message: string, score = 'Sin dato', alert = false): PpvAlternate => ({
...base,
score,
detail: '',
message,
alert,
});
if (!published) return without('No disponible: medida no publicada por el servidor.');
if (reading?.error)
return without('No se pudo consultar las solicitudes de biopsia.', 'Sin dato', true);
if (!reading) return without('No disponible para este periodo.');
const r = requests(reading);
if (!r)
return without(
'Los datos de solicitudes recibidos están incompletos o son inconsistentes.',
'Sin dato',
true,
);
if (!r.total)
return without(
'Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).',
'0 solicitudes',
);
const share = (n: number) => (100 * n) / r.total;
return {
...base,
score: `${share(r.high).toFixed(1)} %`,
detail: `${r.high} de ${r.total} solicitudes registradas (no pacientes) con histología LIEAG o más.`,
rows: [
{
code: 'high_grade',
label: 'LIEAG o más',
color: '#CE4778',
numerator: r.high,
denominator: r.total,
percent: share(r.high),
},
{
code: 'below_high_grade',
label: 'Menor que LIEAG',
color: '#8FA7BB',
numerator: r.below,
denominator: r.total,
percent: share(r.below),
},
],
lines: [
`Pendientes: ${r.pending} · Sin grado: ${r.noGrade} · No clasificables: ${r.unclassified} · ` +
`Fechas inconsistentes: ${r.inconsistent} · Registros fusionados ambiguos: ${r.ambiguous}.`,
],
};
}
+461
View File
@@ -0,0 +1,461 @@
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 } },
};
}
/** A result's share inside each clinical scenario (the report's `<stratum>-category` cells):
* each bar is 100 % of the patients of that scenario with a result in the catalogue, and its
* label says how many they are. Compact: a one-line legend above and thin bars. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
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((s, i) => `${label(s)}<br>n = ${count(totals[i])}`);
const share = (s: string, i: number, c: string) => (totals[i] ? (100 * n(s, c)) / totals[i] : 0);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => share(s, i, c.code)),
customdata: scenarios.map((s) => n(s, c.code)),
text: scenarios.map((s, i) =>
share(s, i, c.code) >= 12 ? `${percent(share(s, i, c.code))} %` : '',
),
textposition: 'inside',
insidetextanchor: 'middle',
textangle: 0,
textfont: { color: '#ffffff', size: 11 },
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
bargap: 0.35,
showlegend: false, // the page draws the legend, which wraps on a narrow screen
margin: { t: 8, r: 8, b: 40, l: 8 },
xaxis: {
title: { text: '% de las pacientes del escenario con resultado', font: { size: 11 } },
ticksuffix: ' %',
range: [0, 100.5],
dtick: 25,
},
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'),
};
}
+50 -2
View File
@@ -1,8 +1,56 @@
import type { RiskAssessment } from 'fhir/r4'; import '@angular/compiler';
import { ageGroup, currentRisk, windowStart } from './follow-up'; import { describe, expect, it } from 'vitest';
import type { Patient, RiskAssessment } from 'fhir/r4';
import {
ageGroup,
currentRisk,
exactAge,
patientLabel,
patientName,
rows,
windowStart,
} from './follow-up';
import { periods } from './measures'; import { periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
it('uses synthetic FHIR names consistently and keeps the patient id as fallback', () => {
const patient: Patient = {
resourceType: 'Patient',
id: 'abcdef123456',
name: [{ text: ' Ana Ejemplo ' }],
};
const page = {
resourceType: 'Bundle' as const,
type: 'searchset' as const,
entry: [{ resource: patient, search: { mode: 'match' as const } }],
};
expect(rows(page, '2026-01-01', '2026-11-27', 5)[0].name).toBe('Ana Ejemplo');
expect(patientLabel(patient)).toBe('Ana Ejemplo');
expect(
patientName({ ...patient, name: [{ given: ['Ana', 'María'], family: 'Ejemplo' }] }),
).toBe('Ana María Ejemplo');
expect(patientLabel({ ...patient, name: [{ text: ' ' }] })).toBe('abcdef1234');
});
it('calculates completed years only from valid full dates', () => {
expect(exactAge('1980-11-23', '2026-11-22')).toBe(45);
expect(exactAge('1980-11-23', '2026-11-23')).toBe(46);
expect(exactAge('2000-02-29', '2025-02-28')).toBe(24);
expect(exactAge('2000-02', '2026-01-01')).toBeUndefined();
expect(exactAge('2001-02-29', '2026-01-01')).toBeUndefined();
expect(exactAge('2027-01-01', '2026-01-01')).toBeUndefined();
});
it('keeps a missing prediction separate from zero', () => {
const risk = (p?: number): RiskAssessment => ({
resourceType: 'RiskAssessment',
status: 'final',
subject: {},
occurrenceDateTime: '2026-01-01',
method: { coding: [{ code: 'cacu.cin2_pim' }] },
prediction: [{ probabilityDecimal: p, whenRange: { high: { value: 5 } } }],
});
expect(currentRisk([risk()], 'cin2', 5)).toBeUndefined();
expect(currentRisk([risk(0)], 'cin2', 5)).toBe(0);
});
it('starts the window the day after the same day months before (core.follow_up)', () => { it('starts the window the day after the same day months before (core.follow_up)', () => {
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23'); expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
+51 -9
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir'; import { code, ext, resources } from '../fhir';
import { routeFacts, StageFacts } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */ /** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row { export interface Row {
@@ -8,7 +9,9 @@ export interface Row {
curp?: string; curp?: string;
status: string; status: string;
ageGroup: string; ageGroup: string;
cytology?: { date: string; result?: string; adequacy?: string }; age?: number;
stageFacts: StageFacts;
cytology?: { date: string; reportDate?: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean }; hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number; daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string }; biopsy?: { date: string; histology?: string };
@@ -17,6 +20,42 @@ export interface Row {
export const CURP = 'https://isssteleon.org/fhir/sid/curp'; export const CURP = 'https://isssteleon.org/fhir/sid/curp';
/** Prefer the supplied FHIR display text, then a structured name, then the next name. */
export function patientName(patient: Patient | undefined): string | undefined {
for (const name of patient?.name ?? []) {
const text = name.text?.trim();
if (text) return text;
const parts = [...(name.given ?? []), name.family ?? '']
.map((part) => part.trim())
.filter(Boolean);
if (parts.length) return parts.join(' ');
}
return undefined;
}
export function patientLabel(patient: Patient | undefined): string {
return patientName(patient) ?? patient?.id?.slice(0, 10) ?? 'No disponible';
}
/** Completed years on a full, valid calendar date; partial dates are unknown. */
export function exactAge(
birth: string | undefined,
cutoff: string | undefined,
): number | undefined {
const parse = (text?: string): [number, number, number] | undefined => {
if (!text || !/^\d{4}-\d{2}-\d{2}$/.test(text)) return undefined;
const [y, m, d] = text.split('-').map(Number);
if (y < 1 || m < 1 || m > 12 || d < 1) return undefined;
const leap = y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
if (d > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]) return undefined;
return [y, m, d];
};
const b = parse(birth),
c = parse(cutoff);
if (!b || !c || birth! > cutoff!) return undefined;
return c[0] - b[0] - (c[1] < b[1] || (c[1] === b[1] && c[2] < b[2]) ? 1 : 0);
}
const AGE_GROUPS: [number, number][] = [ const AGE_GROUPS: [number, number][] = [
[25, 34], [25, 34],
[35, 44], [35, 44],
@@ -49,7 +88,7 @@ export function currentRisk(
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`)) .filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) => .flatMap((r) =>
(r.prediction ?? []) (r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon) .filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
.map((p) => ({ r, p })), .map((p) => ({ r, p })),
); );
if (!mine.length) return undefined; if (!mine.length) return undefined;
@@ -58,9 +97,7 @@ export function currentRisk(
.sort() .sort()
.at(-1); .at(-1);
return Math.max( return Math.max(
...mine ...mine.filter((x) => x.r.occurrenceDateTime === latest).map((x) => x.p.probabilityDecimal!),
.filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal ?? 0),
); );
} }
@@ -99,12 +136,15 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`); const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return { return {
patient, patient,
name: patient.name?.[0]?.text, name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff), ageGroup: ageGroup(patient.birthDate, cutoff),
age: exactAge(patient.birthDate, cutoff),
stageFacts: routeFacts(last),
cytology: last && { cytology: last && {
date: last.effectiveDateTime!, date: last.effectiveDateTime!,
reportDate: ext(last, 'report-date')?.valueDate,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept), result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept), adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
}, },
@@ -146,11 +186,12 @@ export interface CamaRow {
status: string; status: string;
priority: string; priority: string;
ageGroup: string; ageGroup: string;
mammogram: { date: string; birads?: string }; /** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string }; biopsy?: { date: string; histology?: string };
} }
const CAMA_AGE_GROUPS: [number, number][] = [ export const CAMA_AGE_GROUPS: [number, number][] = [
[40, 49], [40, 49],
[50, 59], [50, 59],
[60, 69], [60, 69],
@@ -186,7 +227,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1); .at(-1);
return { return {
patient, patient,
name: patient.name?.[0]?.text, name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '', priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
@@ -196,6 +237,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
birads: mammogram birads: mammogram
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept) ? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
: undefined, : undefined,
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
}, },
biopsy: biopsy && { biopsy: biopsy && {
date: reported(biopsy)!, date: reported(biopsy)!,
+33 -9
View File
@@ -6,35 +6,37 @@ import { Fhir, resources } from '../fhir';
import { TabDefiniciones } from './tab-definiciones'; import { TabDefiniciones } from './tab-definiciones';
import { TabIndicadores } from './tab-indicadores'; import { TabIndicadores } from './tab-indicadores';
import { TabRiesgos } from './tab-riesgos'; import { TabRiesgos } from './tab-riesgos';
import { TabRiesgosTea } from './tab-riesgos-tea';
import { TabSeguimiento } from './tab-seguimiento'; import { TabSeguimiento } from './tab-seguimiento';
import { TabTrazabilidad } from './tab-trazabilidad'; import { TabTrazabilidad } from './tab-trazabilidad';
import { Loading } from '../loading';
/** A domain's indicator page: four tabs over its FHIR measures and patients. */ /** A domain's indicator page: four tabs over its FHIR measures and patients. */
@Component({ @Component({
selector: 'app-indicadores', selector: 'app-indicadores',
imports: [ imports: [
Loading,
MatTabsModule, MatTabsModule,
TabIndicadores, TabIndicadores,
TabTrazabilidad, TabTrazabilidad,
TabRiesgos, TabRiesgos,
TabRiesgosTea,
TabSeguimiento, TabSeguimiento,
TabDefiniciones, TabDefiniciones,
], ],
template: ` template: `
<section class="page"> <section class="page">
<h1>{{ title() }}</h1> <h1>{{ title() }}</h1>
<p class="subtitle"> <p class="subtitle">Explora los indicadores de {{ title().toLowerCase() }}.</p>
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
</p>
@if (measures.isLoading()) { @if (measures.isLoading()) {
<p class="muted">Cargando indicadores…</p> <app-loading what="los indicadores" />
} @else if (measures.error()) { } @else if (measures.error()) {
<p class="muted" role="alert">No se pudieron leer los indicadores.</p> <p class="muted" role="alert">No se pudieron leer los indicadores.</p>
} @else if (!measures.value()?.length) { } @else if (!measures.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else { } @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms"> <mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab label="Indicadores"> <mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" /> <app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab> </mat-tab>
<mat-tab label="Trazabilidad"> <mat-tab label="Trazabilidad">
@@ -48,8 +50,14 @@ import { TabTrazabilidad } from './tab-trazabilidad';
<app-tab-riesgos [domain]="domain()" /> <app-tab-riesgos [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </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') { } @else if (domain() === 'cama') {
<mat-tab label="Seguimiento"> <mat-tab label="Análisis de riesgos">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" /> <app-tab-seguimiento [domain]="domain()" />
</ng-template> </ng-template>
@@ -57,7 +65,7 @@ import { TabTrazabilidad } from './tab-trazabilidad';
} }
<mat-tab label="Datos y definiciones"> <mat-tab label="Datos y definiciones">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-definiciones [measures]="measures.value()!" /> <app-tab-definiciones [domain]="domain()" [measures]="measures.value()!" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
</mat-tab-group> </mat-tab-group>
@@ -68,11 +76,27 @@ import { TabTrazabilidad } from './tab-trazabilidad';
:host { :host {
display: block; 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 { h1 {
text-align: center; font-size: 28px;
font-weight: 500;
margin: 16px 0 8px;
} }
.subtitle { .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 { .empty {
padding: 48px 0; padding: 48px 0;
+86 -3
View File
@@ -44,12 +44,17 @@ export function periodTypes(measure: Measure): PeriodType[] {
/** What one report says: its counts, its score and interval, and its strata. */ /** What one report says: its counts, its score and interval, and its strata. */
export interface Reading { export interface Reading {
/** The server refused or failed the report (a measure that was asked for, not an empty one). */
error?: boolean;
populations: Record<string, number>; populations: Record<string, number>;
score?: number; score?: number;
low?: number; low?: number;
high?: number; high?: number;
unit?: string; unit?: string;
strata: Record<string, Record<string, Record<string, number>>>; strata: Record<string, Record<string, Record<string, number>>>;
/** A stratum's own score by stratifier and value: a median with its quartiles, or a
* proportion with its interval, whichever the report publishes. */
stratumScores?: Record<string, Record<string, { median: number; low?: number; high?: number }>>;
} }
function counts(group: { function counts(group: {
@@ -65,10 +70,29 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined; if (!group) return undefined;
const score = group.measureScore; const score = group.measureScore;
const strata: Reading['strata'] = {}; const strata: Reading['strata'] = {};
const stratumScores: NonNullable<Reading['stratumScores']> = {};
for (const s of group.stratifier ?? []) { 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( 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),
]),
);
stratumScores[name] = Object.fromEntries(
(s.stratum ?? [])
.filter((x) => x.measureScore?.value !== undefined)
.map((x) => [
x.value?.text ?? '',
{
median: x.measureScore!.value!,
low: (ext(x.measureScore, 'q1') ?? ext(x.measureScore, 'ic-bajo'))?.valueDecimal,
high: (ext(x.measureScore, 'q3') ?? ext(x.measureScore, 'ic-alto'))?.valueDecimal,
},
]),
); );
} }
return { return {
@@ -78,11 +102,12 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit, unit: score?.unit,
strata, strata,
stratumScores,
}; };
} }
/** Codes as the screens name them. */ /** Codes as the screens name them. */
const LABELS: Record<string, string> = { export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)', NILM: 'Normal (NILM)',
LSIL: 'LIEBG', LSIL: 'LIEBG',
HSIL: 'LIEAG', HSIL: 'LIEAG',
@@ -116,6 +141,17 @@ const LABELS: Record<string, string> = {
good: 'Bueno', good: 'Bueno',
bad: 'Malo', bad: 'Malo',
not_analyzed: 'Sin analizar', not_analyzed: 'Sin analizar',
'ASCUS+': 'Citología ASC-US o mayor',
'LSIL+': 'Citología LIEBG o mayor',
'HSIL+': 'Citología LIEAG o mayor',
'LIEBG+': 'Histología LIEBG o mayor',
'LIEAG+': 'Histología LIEAG o mayor',
initial: 'Tamizaje inicial',
subsequent: 'Tamizaje subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'Positivo para VPH 16',
hpv_18: 'Positivo para VPH 18',
...Object.fromEntries( ...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
), ),
@@ -128,7 +164,43 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento', follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado', result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía', birads: 'BI-RADS de la mastografía',
referral_cytology: 'Citología previa asociada por fechas',
referral_hpv: 'VPH de la citología previa asociada por fechas',
histology_level: 'Nivel de histología confirmado',
screening_round: 'Tamizaje inicial o subsecuente',
result_initial: 'Resultado en tamizaje inicial',
result_subsequent: 'Resultado en tamizaje subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
hpv_initial: 'VPH en tamizaje inicial',
hpv_subsequent: 'VPH en tamizaje subsecuente',
}; };
/** What the referral PPVs are: the records show procedures, not issued referrals, and the
* previous cytology is linked by dates. */
export const PPV_NOTES: Record<string, { title: string; note: string }> = {
CACU_VPP_COLPOSCOPIA: {
title: 'VPP tras colposcopía registrada',
note:
'De las pacientes con colposcopía registrada en el periodo (puede inferirse de notas clínicas), ' +
'las que tienen histología LIEBG o mayor. Se muestra la citología previa más reciente en los 365 ' +
'días anteriores: es una asociación por fechas, no un vínculo clínico confirmado ni una referencia emitida.',
},
CACU_VPP_BIOPSIA: {
title: 'VPP tras biopsia registrada',
note:
'De las pacientes con biopsia reportada en el periodo, las que tienen histología LIEBG o mayor. ' +
'La citología previa es una asociación por fechas, no un vínculo clínico confirmado ni una referencia ' +
'emitida. Su denominador difiere del de las solicitudes de biopsia registradas.',
},
CACU_VPH: {
title: 'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
note:
'Una paciente por periodo, por su última muestra con resultado de VPH, aunque la citología no tenga ' +
'resultado. Es distinto de los reportes de VPH por genotipo, que cuentan reportes, no pacientes.',
},
};
export const measureTitle = (m: { name?: string; title?: string }) =>
PPV_NOTES[m.name ?? '']?.title ?? m.title ?? m.name ?? '';
export const name = (value: string) => LABELS[value] ?? value; export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string { export function formatScore(measure: Measure, r: Reading | undefined): string {
@@ -209,6 +281,17 @@ export function strataBars(measure: Measure, r: Reading, stratifier: string): Fi
y: cells.map(([v]) => name(v)), y: cells.map(([v]) => name(v)),
x: values, x: values,
marker: { color: PALETTE[0] }, marker: { color: PALETTE[0] },
...(proportion
? {
text: cells.map(([, c]) =>
c['denominator']
? `${c['numerator'] ?? 0} de ${c['denominator']}`
: 'sin pacientes',
),
textposition: 'auto' as const,
hovertemplate: '%{y}<br>%{x:.1f} % (%{text})<extra></extra>',
}
: {}),
}, },
], ],
layout: { layout: {
+700
View File
@@ -0,0 +1,700 @@
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */
export interface Page {
kpis: Kpi[];
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[];
clinical: Section[];
/** The measure whose data decides the default period. */
anchor: string;
}
/** A card: its measure (none: not published yet), its title, and its value and note as
* templates (figures.fill). */
export interface Kpi {
measure?: string;
title: string;
value?: string;
note?: string;
}
/** A measure's categories as a table with a bar each; say what is counted. */
export interface DistSpec {
title: string;
measure: string;
/** what the units are, in the plural */
unit: string;
/** the categories, and which of them to head with a group line */
catalog: readonly (readonly [string, string, string])[];
groups?: { before: string; label: string; codes: string[] }[];
notes: string[];
/** categories left out of the table (their units stay in the total and the percentages) */
hide?: string[];
}
export type Section =
| {
kind: 'route';
title: string;
/** `measure`: days from the sample to the step; `stepMeasure`: days from the previous step */
steps: { label: string; measure: string; step?: string; stepMeasure?: string }[];
/** the route in three readings: cumulative, step by step, and by the ICD-10 of the diagnosis */
modes?: { icd: string };
}
/** CaCu's joint card: the cytology and HPV distributions side by side, the biopsy's below, and
* the scenario figure as a complement. */
| {
kind: 'results';
title: string;
cytology: DistSpec;
hpv: DistSpec;
biopsy: DistSpec;
complement: FigureSpec[];
}
/** A positive predictive value read one way at a time (the whole, or a stratifier). */
| {
kind: 'ppv';
measure: string;
modes: PpvMode[];
/** the heading figures when the measure is not a proportion */
summary?: (reading: Reading | undefined) => { score: string; detail: string };
}
/** The generic card of a measure: its score with numerator, denominator and interval, and its strata. */
| { kind: 'measure-card'; measure: string }
/** The histopathological confirmation: one card, two perspectives (a colposcopy and a biopsy
* PPV), the biopsy requests as one more reading of the biopsy one, and the original measure */
| {
kind: 'confirmation';
title: string;
colposcopy: { measure: string; modes: PpvMode[] };
biopsy: { measure: string; modes: PpvMode[]; requests: string };
}
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
| {
kind: 'boxes';
/** none: the boxes stand alone (TEA) */
title?: string;
cards: { measure?: string; title: string }[];
/** the measure's own title under each card's (CaMa) */
subtitles?: boolean;
}
/** Each figure in its own card, titled, two to a row (TEA). */
| { kind: 'grid'; figures: FigureSpec[] }
/** TEA's period summary in words, its numbers from the measures. */
| { kind: 'tea-summary' }
| ({ kind: 'card' } & Kpi);
/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec =
| {
kind: 'donut' | 'share-donut';
title: string;
measure: string;
catalog: Catalog;
center: string;
}
| { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string }
| { kind: 'counts'; title: string; measure: string; catalog: Catalog; axis: string }
| {
kind: 'age-stack' | 'age-share';
title: string;
measure: string;
/** the numerator's and the rest's names (stack), or the axis (share) */
names: [string, string];
}
| {
kind: 'rates';
title: string;
measure: string;
stratum: string;
rows: Category[];
/** each row in its category's colour (else all rose) */
colored?: boolean;
/** the categories (of the measure) that count as a positive */
positive: string[];
axis: string;
};
export interface Category {
code: string;
label: string;
color: string;
group: string;
}
export interface Catalog {
groups: { id: string; label: string; color: string }[];
categories: Category[];
/** categories drawn faded (not the ones the figure is about) */
faded?: string[];
}
import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results';
import { Reading } from './measures';
import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, PpvMode } from './ppv';
import { VPH_MODES, vphSummary } from './vph';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
/** HPV categories the page leaves out (their reports stay in the total and the percentages). */
const HPV_HIDDEN = ['positive_incomplete', 'inconsistent'];
/** The cytology results by scenario, in the page's cytology colours. */
const CYTOLOGY_SCENARIO: Catalog = {
groups: [],
categories: CYTOLOGY_REPORTS.map(([code, label, color]) => ({ code, label, color, group: '' })),
};
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
const PENDING = 'Indicador no publicado en el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
groups: [],
categories: [
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
],
};
const BREAST_BIOPSY: Catalog = {
groups: [
{ id: 'benign', label: 'No maligno', color: '#42C29C' },
{ id: 'malignant', label: 'Maligno', color: ROSE },
],
categories: [
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
],
};
export const PAGES: Record<string, Page> = {
tea: {
anchor: 'M23_PACIENTES_EVALUADOS',
kpis: [],
opportunity: [
{ kind: 'tea-summary' },
{
kind: 'boxes',
cards: [
{ measure: 'M26_DIAS_MCHAT_ADOS2', title: 'Días de M-CHAT a ADOS-2' },
{ measure: 'M27_DIAS_ADOS2_DIAGNOSTICO', title: 'Días de ADOS-2 a diagnóstico' },
{ measure: 'M25_DIAS_MCHAT_DIAGNOSTICO', title: 'Días de M-CHAT a diagnóstico positivo' },
],
},
],
clinical: [
{
kind: 'grid',
figures: [
{
kind: 'counts',
title: 'Pacientes evaluados por resultado diagnóstico',
measure: 'M23_PACIENTES_EVALUADOS',
axis: 'Conteo (paciente)',
catalog: {
groups: [],
categories: [
{ code: 'confirmed', label: 'Diagnóstico confirmado', color: OLIVE, group: '' },
{ code: 'in_process', label: 'En proceso', color: '#B8433A', group: '' },
],
},
},
{
kind: 'age-stack',
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
names: ['Diagnóstico confirmado', 'En proceso'],
},
{
kind: 'age-share',
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
names: ['% de pacientes con EEG', ''],
},
{
kind: 'age-share',
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
names: ['% de pacientes sin EEG', ''],
},
{
kind: 'counts',
title: 'Casos por estatus',
measure: 'M28_CASOS_POR_ESTADO',
axis: 'Conteo (paciente)',
catalog: {
groups: [],
categories: [
{ code: 'mchat_only', label: 'Solo M-CHAT', color: '#B8433A', group: '' },
{
code: 'psychology',
label: 'Hasta evaluación psicológica',
color: '#42C29C',
group: '',
},
{
code: 'neuropediatrics',
label: 'Hasta evaluación neuropediátrica',
color: '#7184A2',
group: '',
},
{ code: 'eeg', label: 'Con EEG', color: OLIVE, group: '' },
],
},
},
{
kind: 'counts',
title: 'Calidad del EEG',
measure: 'M29_CALIDAD_EEG',
axis: 'Conteo (examen)',
catalog: {
groups: [],
categories: [
{ code: 'good', label: 'Bueno', color: OLIVE, group: '' },
{ code: 'bad', label: 'No aceptable', color: '#B8433A', group: '' },
{ code: 'not_analyzed', label: 'Sin analizar', color: '#C9CDD2', group: '' },
],
},
},
],
},
],
},
cama: {
anchor: 'CAMA_BIRADS456_PACIENTE',
kpis: [
{
measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
},
{
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} biopsias con riesgo a carcinoma.',
},
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
...CAMA_DAYS,
},
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: PENDING,
},
],
opportunity: [
{
kind: 'boxes',
title: 'Tiempo de tamizaje a diagnóstico',
subtitles: true,
cards: [
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
},
{ title: 'Tiempo de interpretación radiológica a resultado de biopsia' },
{ title: 'Tiempo de diagnóstico a tratamiento' },
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
],
},
],
clinical: [
{
kind: 'figures',
figures: [
{
kind: 'share-donut',
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
catalog: BIRADS,
center: 'mastografías',
},
{
kind: 'share-donut',
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_PACIENTE',
catalog: BIRADS,
center: 'pacientes',
},
],
},
{
kind: 'figures',
title: 'Resultado histopatológico por categoría BI-RADS',
figures: [
{
kind: 'rates',
title: 'Por categoría BI-RADS, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
colored: true,
positive: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
},
{
kind: 'donut',
title: 'Resultado de la biopsia, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: BREAST_BIOPSY,
center: 'con resultado',
},
],
},
{
kind: 'card',
measure: 'CAMA_CONFIRMACION_BIRADS45',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
},
],
},
cacu: {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'route',
title: 'Tiempos de la ruta del tamizaje',
modes: { icd: 'CACU_TIEMPO_DIAGNOSTICO_CIE10' },
steps: [
{
label: 'Resultado de citología',
measure: 'CACU_EU_TIEMPO_REPORTE',
step: 'Toma a resultado de citología',
stepMeasure: 'CACU_EU_TIEMPO_REPORTE',
},
{
label: 'Resultado de colposcopía',
measure: 'CACU_DIAS_TOMA_COLPOSCOPIA',
step: 'Del resultado de citología a la colposcopía',
stepMeasure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA',
},
{
label: 'Resultado de biopsia',
measure: 'CACU_DIAS_TOMA_BIOPSIA',
step: 'De la colposcopía al resultado de biopsia',
stepMeasure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
step: 'Del resultado de biopsia al diagnóstico',
stepMeasure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
},
],
clinical: [
{
kind: 'results',
title: 'Resultados de citología, VPH y biopsia',
cytology: {
title: 'Distribución de resultados citológicos',
measure: 'CACU_EU7',
unit: 'pacientes',
catalog: CYTOLOGY_REPORTS,
notes: [
'Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.',
],
},
hpv: {
title: 'Resultados de VPH por genotipo',
measure: 'CACU_VPH_GENOTIPO',
unit: 'reportes',
catalog: HPV_REPORTS,
hide: HPV_HIDDEN,
notes: [
'Un reporte de VPH por paciente y fecha de toma; el periodo es el de la toma. Cuenta reportes, ' +
'no pacientes: es una medida distinta de las pacientes evaluadas por resultado de VPH.',
'Los valores nulos no se cuentan como negativos.',
],
},
biopsy: {
title: 'Resultados de biopsia cervical',
measure: 'CACU_BIOPSIA_RESULTADOS',
unit: 'reportes',
catalog: BIOPSY_REPORTS,
groups: [
{ before: 'normal', label: 'Menor que LIEAG', codes: ['normal', 'LSIL'] },
{ before: 'HSIL', label: 'LIEAG o más', codes: ['HSIL', 'CIS', 'carcinoma'] },
],
notes: [
'Reportes de biopsia con histología clasificable; el periodo es el de la fecha del reporte. ' +
'Las órdenes sin reporte no están incluidas.',
],
},
complement: [
{
kind: 'scenario-bars',
title: 'Resultados citológicos por escenario clínico, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY_SCENARIO,
stratum: 'follow_up_status',
},
],
},
{ kind: 'ppv', measure: 'CACU_VPH', modes: VPH_MODES, summary: vphSummary },
{
kind: 'confirmation',
title: 'Tasa de confirmación histopatológica',
colposcopy: { measure: 'CACU_VPP_COLPOSCOPIA', modes: PPV_COLPOSCOPY_MODES },
biopsy: {
measure: 'CACU_VPP_BIOPSIA',
modes: PPV_BIOPSY_MODES,
requests: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
},
},
],
},
};
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
export interface HistoryPanel {
title: string;
measure: string;
kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string;
group?: string;
}
export interface History {
panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number;
}
const GREY = '#C9CDD2';
const stack = (
title: string,
measure: string,
axis: string,
series: [string, string, string][],
): HistoryPanel => ({
title,
measure,
kind: 'stack',
axis,
series: series.map(([code, label, color]) => ({ code, label, color })),
});
const BIRADS_SERIES: [string, string, string][] = [
['4A', 'BI-RADS 4A', '#C24269'],
['4B', 'BI-RADS 4B', '#9C42C2'],
['4C', 'BI-RADS 4C', '#5C42C2'],
['5', 'BI-RADS 5', '#C2429C'],
['6', 'BI-RADS 6', '#8E2F62'],
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
];
export const HISTORY: Record<string, History> = {
cacu: {
line: '#6A8000',
months: 5,
panels: [
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
['NILM', 'Normal', '#9DBFE3'],
['ASC-US', 'ASC-US', '#2F6DB3'],
['LSIL', 'LIEBG', '#9C42C2'],
['ASC-H', 'ASC-H', '#5C42C2'],
['HSIL', 'LIEAG', '#C2429C'],
['CIS', 'Carcinoma in situ', '#8E2F62'],
['no_data', 'Sin dato', GREY],
]),
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
stack(
'Resultado de biopsia tras citología de alto grado',
'CACU_CONFIRMACION_CITOLOGIA',
'Pacientes',
[
['normal', 'Normal', '#9DBFE3'],
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
['CIS', 'Carcinoma in situ', '#9C42C2'],
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
['no_biopsy', 'Sin biopsia aún', GREY],
['no_data', 'Biopsia sin grado', GREY],
],
),
{
title: 'Días de la toma de la citología a su resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median',
},
{
title: 'Tiempo de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
{
title: 'Riesgo CIN2+ por banda',
measure: 'CACU_RIESGO_BANDA',
kind: 'stack',
axis: 'Pacientes',
},
],
},
cama: {
line: '#9C42C2',
panels: [
{
title: 'Días de la toma de la mastografía a su resultado',
measure: 'CAMA_EU38A',
kind: 'median',
},
{
title: 'Días del resultado de la mastografía al diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Días de tamizaje a diagnóstico',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
stack(
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_MASTOGRAFIA',
'Mastografías',
BIRADS_SERIES,
),
stack(
'Pacientes con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_PACIENTE',
'Pacientes',
BIRADS_SERIES,
),
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
['benign', 'Benigno', '#9DBFE3'],
['in_situ', 'Carcinoma in situ', '#C24269'],
['invasive', 'Carcinoma invasor', '#9C42C2'],
['no_biopsy', 'Sin biopsia reportada', GREY],
['no_data', 'Sin dato', GREY],
]),
{
title: 'Tasa de confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent',
},
],
},
tea: {
line: '#9C42C2',
panels: [
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a ADOS-2',
measure: 'M26_DIAS_MCHAT_ADOS2',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de ADOS-2 a diagnóstico',
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a diagnóstico positivo',
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
kind: 'median',
},
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
['in_process', 'En proceso', '#B8433A'],
]),
{
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
kind: 'percent',
},
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
['mchat_only', 'Solo M-CHAT', '#B8433A'],
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
['eeg', 'Con EEG', '#A8C243'],
]),
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
['good', 'Bueno', '#A8C243'],
['bad', 'No aceptable', '#B8433A'],
['not_analyzed', 'Sin analizar', GREY],
]),
],
},
};
@@ -0,0 +1,19 @@
import { matchesSearch, patientSearch } from './patient-search';
describe('patient search', () => {
it('asks the API by identifier for one word with a digit, else by name', () => {
expect(patientSearch(' IARM800101MNLBVR09 ')).toEqual({ identifier: 'IARM800101MNLBVR09' });
expect(patientSearch('0451A')).toEqual({ identifier: '0451A' });
expect(patientSearch('martha ibarra')).toEqual({ name: 'martha ibarra' });
expect(patientSearch('')).toEqual({});
});
it('matches in the browser by word starts, case and accents ignored', () => {
const texts = ['IBARRA RIVERA MARTHA', 'd5a6a924-f2ad', 'N0183'];
expect(matchesSearch('már riv', texts)).toBe(true);
expect(matchesSearch('d5a6', texts)).toBe(true);
expect(matchesSearch('n0183', texts)).toBe(true);
expect(matchesSearch('arth', texts)).toBe(false);
expect(matchesSearch('', texts)).toBe(true);
});
});

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