Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c0e4920159 | |||
| 31400c77b1 |
-122
@@ -1,122 +0,0 @@
|
||||
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)];
|
||||
});
|
||||
}
|
||||
+15
-240
@@ -1,6 +1,4 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expect, Page, test } from '@playwright/test';
|
||||
import { layoutProblems } from './layout';
|
||||
|
||||
/** Every page loads from the API with no failed request and no console error. */
|
||||
function watch(page: Page): string[] {
|
||||
@@ -11,32 +9,6 @@ function watch(page: Page): string[] {
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The pages show only to someone signed in (the API itself answers everyone).
|
||||
test.beforeEach(async ({ page }) => {
|
||||
const signed = await page.request.post('/api/auth/login', {
|
||||
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
|
||||
});
|
||||
expect(signed.status()).toBe(204);
|
||||
});
|
||||
|
||||
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
|
||||
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
|
||||
await page.goto('/conectar');
|
||||
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
|
||||
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
|
||||
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
|
||||
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
|
||||
await page.getByRole('button', { name: 'Ingresar' }).click();
|
||||
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
|
||||
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
|
||||
await page.getByRole('button', { name: 'Ingresar' }).click();
|
||||
await expect(page).toHaveURL(/\/conectar$/);
|
||||
await page.getByRole('button', { name: 'Cuenta' }).click();
|
||||
await page.getByRole('menuitem', { name: 'Salir' }).click();
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
await page.close();
|
||||
});
|
||||
|
||||
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
|
||||
page,
|
||||
}) => {
|
||||
@@ -47,22 +19,21 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
r.url().includes('measure=cacu-eu7') &&
|
||||
!r.url().includes('%2C'),
|
||||
);
|
||||
const catalog = page.waitForResponse((r) => r.url().endsWith('/cacu/fhir/Measure'));
|
||||
await page.goto('/indicadores/cacu');
|
||||
const measures = await (await catalog).json();
|
||||
const eu7 = await (await report).json();
|
||||
const count = eu7.entry[0].resource.group[0].population.find(
|
||||
(p: any) => p.code.coding[0].code === 'initial-population',
|
||||
).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('[data-measure="CACU_EU7"] mat-card-subtitle')).toContainText(String(count));
|
||||
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
|
||||
|
||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
||||
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
|
||||
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(measures.total);
|
||||
|
||||
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
||||
await expect(page.locator('app-tab-definiciones details')).toHaveCount(14);
|
||||
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(measures.total);
|
||||
|
||||
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
|
||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
||||
@@ -73,7 +44,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
await expect(rows).toHaveCount(Math.min(20, bundle.total));
|
||||
await expect(rows.first().locator('a').first()).toHaveText(first);
|
||||
await page.getByRole('button', { name: 'Siguiente' }).click();
|
||||
await expect(page.getByText('Página 2 de')).toBeVisible();
|
||||
await expect(page.getByText(`21–`)).toBeVisible();
|
||||
|
||||
await page.getByRole('button', { name: 'Anterior' }).click();
|
||||
await rows.first().locator('a').first().click();
|
||||
@@ -85,13 +56,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
|
||||
await page.goto('/indicadores/cama');
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
|
||||
await page.getByRole('option', { name: '12 meses' }).click();
|
||||
const camaRows = page.locator('table.worklist tbody tr');
|
||||
await expect(camaRows.first()).toContainText('BI-RADS');
|
||||
await page.goto('/indicadores/tea');
|
||||
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -102,18 +73,13 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
|
||||
await page.goto('/conectar');
|
||||
await page.getByText('cacu', { exact: true }).click();
|
||||
await expect(page.locator('vflow')).toBeVisible();
|
||||
// a node's caption: its kind, then its name
|
||||
await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
|
||||
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
|
||||
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
|
||||
await page.getByText('Fuente · Patients').click();
|
||||
await expect(page.locator('formly-form')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Vista previa' }).click();
|
||||
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
|
||||
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
|
||||
await page
|
||||
.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 page.getByText('Mapear · cytology', { exact: true }).click();
|
||||
await expect(page.getByText('Códigos del sitio')).toBeVisible();
|
||||
await expect
|
||||
.poll(() =>
|
||||
page
|
||||
@@ -126,9 +92,7 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
test('revision: what the hospital source holds, and a decision through the page', async ({
|
||||
page,
|
||||
}) => {
|
||||
test('revision: what the hospital source holds, and a decision through the page', async ({ page }) => {
|
||||
const problems = watch(page);
|
||||
await page.goto('/revision');
|
||||
await page.getByRole('tab', { name: 'Personas' }).click();
|
||||
@@ -145,201 +109,12 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
|
||||
}) => {
|
||||
const problems = watch(page);
|
||||
await page.goto('/gobernanza/cama');
|
||||
await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible();
|
||||
const version = page.locator('tr', { hasText: 'v1' });
|
||||
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
|
||||
await version.getByRole('button', { name: 'Ver gráficas' }).click();
|
||||
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
|
||||
await version.getByRole('button', { name: 'Promover' }).click();
|
||||
await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
|
||||
await expect(page.getByText('No se promovió')).toContainText('clinical_validation');
|
||||
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
|
||||
page,
|
||||
}) => {
|
||||
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
|
||||
const problems = watch(page);
|
||||
await page.goto('/conectar');
|
||||
await page.getByLabel('Nueva canalización').fill('asistente');
|
||||
await page.getByLabel('Nueva canalización').press('Enter');
|
||||
await page.getByRole('button', { name: 'Fuente de datos' }).click();
|
||||
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
|
||||
await page.locator('[data-type="sqlserver"]').click();
|
||||
await page.locator('[data-field="host"]').fill(site.hostname);
|
||||
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
|
||||
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
|
||||
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
|
||||
await page.getByRole('button', { name: 'Probar conexión' }).click();
|
||||
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
|
||||
await page.locator('mat-select[data-field="table"]').click();
|
||||
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
|
||||
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
|
||||
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
|
||||
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
|
||||
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
|
||||
// A wrong password says so in words, not a stack trace.
|
||||
await page.getByRole('button', { name: 'Editar conexión' }).click();
|
||||
await page.locator('[data-field="password"]').fill('not-it');
|
||||
await page.getByRole('button', { name: 'Probar conexión' }).click();
|
||||
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Cancelar' }).click();
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
|
||||
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
|
||||
* opportunity section on, in order, and the kind of each plot (its traces' types). */
|
||||
function captured(domain: string) {
|
||||
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
|
||||
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
|
||||
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
|
||||
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
|
||||
return items
|
||||
.slice(from)
|
||||
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
|
||||
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
|
||||
}
|
||||
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
|
||||
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
|
||||
|
||||
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 });
|
||||
const headings = await tab
|
||||
.locator('h2, h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
const from = headings.indexOf('Indicadores de oportunidad');
|
||||
expect(headings.slice(from).map(period)).toEqual(
|
||||
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
|
||||
);
|
||||
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
|
||||
const drawn = await tab
|
||||
.locator('.js-plotly-plot')
|
||||
.evaluateAll((els) =>
|
||||
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
|
||||
);
|
||||
const kinds = new Set(
|
||||
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
|
||||
);
|
||||
for (const types of drawn) expect(kinds).toContain(kindOf(types));
|
||||
});
|
||||
}
|
||||
|
||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const tabs = JSON.parse(
|
||||
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
|
||||
).tabs;
|
||||
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
|
||||
['h2', 'h3', 'plot'].includes(i.kind),
|
||||
);
|
||||
await page.goto(`/indicadores/${domain}`);
|
||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
||||
const tab = page.locator('app-tab-trazabilidad');
|
||||
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
|
||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
||||
const headings = await tab
|
||||
.locator('h2, h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
|
||||
const drawn = await tab
|
||||
.locator('.js-plotly-plot')
|
||||
.evaluateAll((els) =>
|
||||
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
|
||||
);
|
||||
const kinds = new Set(
|
||||
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
|
||||
);
|
||||
for (const types of drawn) expect(kinds).toContain(kindOf(types));
|
||||
});
|
||||
}
|
||||
|
||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const tabs = JSON.parse(
|
||||
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
|
||||
).tabs;
|
||||
const old = (tabs['Datos y definiciones'] as any[])
|
||||
.filter((i) => ['h2', 'h3'].includes(i.kind))
|
||||
.map((i) => i.text);
|
||||
await page.goto(`/indicadores/${domain}`);
|
||||
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
||||
const tab = page.locator('app-tab-definiciones');
|
||||
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
|
||||
const headings = await tab
|
||||
.locator('h2, h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
expect(headings).toEqual(old);
|
||||
await tab.locator('summary').first().click();
|
||||
await expect(
|
||||
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
|
||||
).toBeVisible();
|
||||
});
|
||||
}
|
||||
|
||||
/** Waits for a page's data: no loading indicator left. */
|
||||
async function loaded(page: Page): Promise<void> {
|
||||
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
|
||||
timeout: 5 * 60_000,
|
||||
});
|
||||
await page.waitForTimeout(1000); // plots finish drawing
|
||||
}
|
||||
|
||||
for (const width of [1440, 820]) {
|
||||
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const found: string[] = [];
|
||||
const check = async (where: string) => {
|
||||
await loaded(page);
|
||||
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
|
||||
};
|
||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
await page.goto(`/indicadores/${domain}`);
|
||||
const tabs = page.locator('.mdc-tab');
|
||||
for (let i = 0; i < (await tabs.count()); i++) {
|
||||
await tabs.nth(i).click();
|
||||
await check(`${domain} tab ${i + 1}`);
|
||||
}
|
||||
// the record of the risk list's first patient
|
||||
await tabs.nth(2).click();
|
||||
await loaded(page);
|
||||
const first = page.locator('table a[href*="/pacientes/"]').first();
|
||||
if (await first.count()) {
|
||||
await first.click();
|
||||
await check(`${domain} record`);
|
||||
}
|
||||
await page.goto(`/gobernanza/${domain}`);
|
||||
await check(`${domain} gobernanza`);
|
||||
}
|
||||
await page.goto('/conectar');
|
||||
await check('conectar');
|
||||
// a pipeline open, a node chosen, in both of its panel's tabs
|
||||
await page.locator('.pipelines [mat-list-item]').first().click();
|
||||
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
|
||||
await check('conectar node');
|
||||
await page.getByRole('tab', { name: 'Avanzado' }).click();
|
||||
await check('conectar node, advanced');
|
||||
await page.goto('/revision');
|
||||
const tabs = page.locator('.mdc-tab');
|
||||
for (let i = 0; i < (await tabs.count()); i++) {
|
||||
await tabs.nth(i).click();
|
||||
await check(`revision tab ${i + 1}`);
|
||||
}
|
||||
expect(found).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
location /api/ {
|
||||
proxy_pass http://api:8000/;
|
||||
proxy_read_timeout 120s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
|
||||
+65
-2214
File diff suppressed because it is too large
Load Diff
@@ -1,32 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,29 +0,0 @@
|
||||
/* 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';
|
||||
@@ -24,16 +24,6 @@ export interface SearchPatient$Params {
|
||||
'follow-up-cutoff'?: (string | null);
|
||||
'follow-up-status'?: (string | null);
|
||||
|
||||
/**
|
||||
* each word starts a word of her name (case and accents ignored)
|
||||
*/
|
||||
name?: (string | null);
|
||||
|
||||
/**
|
||||
* [system|]value: a CURP or record number (case ignored)
|
||||
*/
|
||||
identifier?: (string | null);
|
||||
|
||||
/**
|
||||
* -recent or -risk-<outcome>
|
||||
*/
|
||||
@@ -66,8 +56,6 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
|
||||
rb.query('follow-up-window', params['follow-up-window'], {});
|
||||
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
|
||||
rb.query('follow-up-status', params['follow-up-status'], {});
|
||||
rb.query('name', params.name, {});
|
||||
rb.query('identifier', params.identifier, {});
|
||||
rb.query('_sort', params['_sort'], {});
|
||||
rb.query('risk-horizon', params['risk-horizon'], {});
|
||||
rb.query('_revinclude', params['_revinclude'], {});
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,34 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,30 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,35 +0,0 @@
|
||||
/* 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';
|
||||
@@ -8,13 +8,14 @@ import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { BodyUpload } from '../../models/body-upload';
|
||||
import { Uploaded } from '../../models/uploaded';
|
||||
|
||||
export interface Upload$Params {
|
||||
body: BodyUpload
|
||||
}
|
||||
|
||||
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<Uploaded>> {
|
||||
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, upload.PATH, 'post');
|
||||
if (params) {
|
||||
rb.body(params.body, 'multipart/form-data');
|
||||
@@ -25,7 +26,9 @@ export function upload(http: HttpClient, rootUrl: string, params: Upload$Params,
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Uploaded>;
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,13 +8,12 @@ import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Domain } from '../../models/domain';
|
||||
import { Model } from '../../models/model';
|
||||
|
||||
export interface Models$Params {
|
||||
domain: Domain;
|
||||
}
|
||||
|
||||
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Model>>> {
|
||||
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> {
|
||||
const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
|
||||
if (params) {
|
||||
rb.path('domain', params.domain, {});
|
||||
@@ -25,7 +24,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<Model>>;
|
||||
return r as StrictHttpResponse<Array<string>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Conflicts$Params {
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
}
|
||||
|
||||
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
|
||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Held$Params {
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
}
|
||||
|
||||
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,35 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,33 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,30 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,31 +0,0 @@
|
||||
/* 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}';
|
||||
@@ -1,33 +0,0 @@
|
||||
/* 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';
|
||||
@@ -1,35 +0,0 @@
|
||||
/* 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}';
|
||||
@@ -1,32 +0,0 @@
|
||||
/* 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}';
|
||||
@@ -1,10 +1,6 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth/auth-cookie-login';
|
||||
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
|
||||
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
|
||||
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
|
||||
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
|
||||
export { domains as domains } from './fn/operations/domains';
|
||||
export type { Health$Params as Health$Params } from './fn/operations/health';
|
||||
@@ -27,18 +23,10 @@ export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
|
||||
export { startRun as startRun } from './fn/ingest/start-run';
|
||||
export type { Schema$Params as Schema$Params } from './fn/ingest/schema';
|
||||
export { schema as schema } from './fn/ingest/schema';
|
||||
export type { Browse$Params as Browse$Params } from './fn/ingest/browse';
|
||||
export { browse as browse } from './fn/ingest/browse';
|
||||
export type { OauthStart$Params as OauthStart$Params } from './fn/ingest/oauth-start';
|
||||
export { oauthStart as oauthStart } from './fn/ingest/oauth-start';
|
||||
export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
|
||||
export { sourcePreview as sourcePreview } from './fn/ingest/source-preview';
|
||||
export type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
|
||||
export { sourceResources as sourceResources } from './fn/ingest/source-resources';
|
||||
export type { TestSource$Params as TestSource$Params } from './fn/ingest/test-source';
|
||||
export { testSource as testSource } from './fn/ingest/test-source';
|
||||
export type { SourceTypes$Params as SourceTypes$Params } from './fn/ingest/source-types';
|
||||
export { sourceTypes as sourceTypes } from './fn/ingest/source-types';
|
||||
export type { Upload$Params as Upload$Params } from './fn/ingest/upload';
|
||||
export { upload as upload } from './fn/ingest/upload';
|
||||
export type { Models$Params as Models$Params } from './fn/models/models';
|
||||
@@ -71,28 +59,12 @@ export type { DecidePersons$Params as DecidePersons$Params } from './fn/review/d
|
||||
export { decidePersons as decidePersons } from './fn/review/decide-persons';
|
||||
export type { Reject$Params as Reject$Params } from './fn/review/reject';
|
||||
export { reject as reject } from './fn/review/reject';
|
||||
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
|
||||
export { unrecognised as unrecognised } from './fn/review/unrecognised';
|
||||
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
|
||||
export { runStatus as runStatus } from './fn/runs/run-status';
|
||||
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
|
||||
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
|
||||
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
|
||||
export { studies as studies } from './fn/eeg/studies';
|
||||
export type { Study$Params as Study$Params } from './fn/eeg/study';
|
||||
export { study as study } from './fn/eeg/study';
|
||||
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
|
||||
export { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user';
|
||||
export type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
|
||||
export { usersPatchCurrentUser as usersPatchCurrentUser } from './fn/users/users-patch-current-user';
|
||||
export type { RegisterRegister$Params as RegisterRegister$Params } from './fn/users/register-register';
|
||||
export { registerRegister as registerRegister } from './fn/users/register-register';
|
||||
export type { UsersUser$Params as UsersUser$Params } from './fn/users/users-user';
|
||||
export { usersUser as usersUser } from './fn/users/users-user';
|
||||
export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/users/users-delete-user';
|
||||
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
|
||||
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
|
||||
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
|
||||
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
|
||||
export { postBundle as postBundle } from './fn/fhir/post-bundle';
|
||||
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
|
||||
|
||||
@@ -2,52 +2,30 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export type { Analysis } from './models/analysis';
|
||||
export type { Answers } from './models/answers';
|
||||
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
|
||||
export type { BodyUpload } from './models/body-upload';
|
||||
export type { Browsed } from './models/browsed';
|
||||
export type { Catalog } from './models/catalog';
|
||||
export type { Condition } from './models/condition';
|
||||
export type { Correction } from './models/correction';
|
||||
export type { Domain } from './models/domain';
|
||||
export type { Entry } from './models/entry';
|
||||
export type { ErrorModel } from './models/error-model';
|
||||
export type { Extract } from './models/extract';
|
||||
export type { Fhir } from './models/fhir';
|
||||
export type { FieldSpec } from './models/field-spec';
|
||||
export type { Group } from './models/group';
|
||||
export type { Guided } from './models/guided';
|
||||
export type { HttpValidationError } from './models/http-validation-error';
|
||||
export type { Join } from './models/join';
|
||||
export type { Link } from './models/link';
|
||||
export type { Listing } from './models/listing';
|
||||
export type { Login } from './models/login';
|
||||
export type { Map } from './models/map';
|
||||
export type { Metric } from './models/metric';
|
||||
export type { Model } from './models/model';
|
||||
export type { Option } from './models/option';
|
||||
export type { PersonDecision } from './models/person-decision';
|
||||
export type { Pipeline } from './models/pipeline';
|
||||
export type { Position } from './models/position';
|
||||
export type { Provider } from './models/provider';
|
||||
export type { Read } from './models/read';
|
||||
export type { Rejection } from './models/rejection';
|
||||
export type { Relation } from './models/relation';
|
||||
export type { Route } from './models/route';
|
||||
export type { RunRequest } from './models/run-request';
|
||||
export type { SavedPipeline } from './models/saved-pipeline';
|
||||
export type { SignIn } from './models/sign-in';
|
||||
export type { Site } from './models/site';
|
||||
export type { Source } from './models/source';
|
||||
export type { SourceRef } from './models/source-ref';
|
||||
export type { SourceType } from './models/source-type';
|
||||
export type { Study } from './models/study';
|
||||
export type { Target } from './models/target';
|
||||
export type { Tested } from './models/tested';
|
||||
export type { Training } from './models/training';
|
||||
export type { Uploaded } from './models/uploaded';
|
||||
export type { UserCreate } from './models/user-create';
|
||||
export type { UserRead } from './models/user-read';
|
||||
export type { UserUpdate } from './models/user-update';
|
||||
export type { ValidationError } from './models/validation-error';
|
||||
export type { Version } from './models/version';
|
||||
|
||||
@@ -2,12 +2,10 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Metric } from '../models/metric';
|
||||
import { Relation } from '../models/relation';
|
||||
export interface Analysis {
|
||||
age_months: (number | null);
|
||||
id: string;
|
||||
level: (string | null);
|
||||
metrics: Array<Metric>;
|
||||
relation?: Array<Relation>;
|
||||
valid: (boolean | null);
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
/* 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,6 +2,5 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface BodyUpload {
|
||||
files: Array<string>;
|
||||
folder?: (string | null);
|
||||
file: string;
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/* 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);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/* 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;
|
||||
};
|
||||
}
|
||||
@@ -2,15 +2,7 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Condition {
|
||||
|
||||
/**
|
||||
* Por ejemplo «text», el texto leído del documento.
|
||||
*/
|
||||
column: string;
|
||||
op: 'equals' | 'contains' | 'matches' | 'present';
|
||||
|
||||
/**
|
||||
* Lo que se busca; por ejemplo «citología».
|
||||
*/
|
||||
value?: string;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
|
||||
*/
|
||||
export interface Correction {
|
||||
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
field: string;
|
||||
record: string;
|
||||
value: string;
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Entry {
|
||||
kind: 'folder' | 'file';
|
||||
name: string;
|
||||
path: string;
|
||||
size?: (number | null);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface ErrorModel {
|
||||
detail: (string | {
|
||||
[key: string]: string;
|
||||
});
|
||||
}
|
||||
@@ -13,40 +13,17 @@ import { Position } from '../models/position';
|
||||
*/
|
||||
export interface Extract {
|
||||
column: (string | Array<string>);
|
||||
|
||||
/**
|
||||
* Dato → columna, sin leer el texto.
|
||||
*/
|
||||
columns?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
concept_map?: (string | null);
|
||||
|
||||
/**
|
||||
* Qué estudio se saca del documento.
|
||||
*/
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
formats?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Para el modelo de lenguaje.
|
||||
*/
|
||||
hints?: string;
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'extract';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
method?: 'auto' | 'llm' | 'patterns';
|
||||
|
||||
/**
|
||||
* Dato → expresión con un grupo ( ).
|
||||
*/
|
||||
patterns?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
@@ -11,14 +11,10 @@ import { Position } from '../models/position';
|
||||
export interface Fhir {
|
||||
column?: string;
|
||||
concept_map?: (string | null);
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'fhir';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
position?: (Position | null);
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
/* 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';
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Group {
|
||||
description: string;
|
||||
title: string;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -11,15 +11,7 @@ export interface Join {
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'join';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
|
||||
/**
|
||||
* Columna de la primera entrada = columna de la segunda.
|
||||
*/
|
||||
on: Array<[string, string]>;
|
||||
position?: (Position | null);
|
||||
}
|
||||
|
||||
@@ -16,20 +16,8 @@ export interface Link {
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'link';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
position?: (Position | null);
|
||||
|
||||
/**
|
||||
* Parecidos por encima de esto los ve un revisor.
|
||||
*/
|
||||
review?: number;
|
||||
|
||||
/**
|
||||
* Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).
|
||||
*/
|
||||
rules?: Array<string>;
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
/* 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);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -8,38 +8,18 @@ import { Position } from '../models/position';
|
||||
* (core.concept_map), and its date formats.
|
||||
*/
|
||||
export interface Map {
|
||||
|
||||
/**
|
||||
* La tabla de códigos del sitio.
|
||||
*/
|
||||
concept_map?: (string | null);
|
||||
|
||||
/**
|
||||
* Dato de la plataforma → columna del sitio.
|
||||
*/
|
||||
fields: {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Por ejemplo %d/%m/%Y.
|
||||
*/
|
||||
formats?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'map';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
position?: (Position | null);
|
||||
|
||||
/**
|
||||
* Un dato igual para todas las filas.
|
||||
*/
|
||||
values?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Site } from '../models/site';
|
||||
export interface Metric {
|
||||
code: string;
|
||||
electrodes?: Array<Site>;
|
||||
median?: (number | null);
|
||||
model: (string | null);
|
||||
outside: (number | null);
|
||||
p5?: (number | null);
|
||||
p95?: (number | null);
|
||||
value: number;
|
||||
z: (number | null);
|
||||
zones?: Array<Site>;
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Model {
|
||||
name: string;
|
||||
title: string;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Option {
|
||||
label: string;
|
||||
value: any;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -7,18 +7,10 @@ import { Position } from '../models/position';
|
||||
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
|
||||
*/
|
||||
export interface Read {
|
||||
|
||||
/**
|
||||
* Donde la entrada trae cada documento.
|
||||
*/
|
||||
column: string;
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'read';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
position?: (Position | null);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Rejection {
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
reason: string;
|
||||
record: string;
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -5,24 +5,13 @@ import { Condition } from '../models/condition';
|
||||
import { Position } from '../models/position';
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Only the rows where every condition holds (e.g. reports titled "Citología").
|
||||
*/
|
||||
export interface Route {
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'route';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
|
||||
/**
|
||||
* Recoge lo que nadie reconoce, para revisarlo.
|
||||
*/
|
||||
otherwise?: boolean;
|
||||
position?: (Position | null);
|
||||
when?: Array<Condition>;
|
||||
when: Array<Condition>;
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface SignIn {
|
||||
state: string;
|
||||
url: string;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Site {
|
||||
site: string;
|
||||
value: number;
|
||||
z: (number | null);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Guided } from '../models/guided';
|
||||
import { Position } from '../models/position';
|
||||
|
||||
/**
|
||||
@@ -9,41 +8,16 @@ import { Position } from '../models/position';
|
||||
* own primary key or `primary_key`; replaced whole when it has none.
|
||||
*/
|
||||
export interface Source {
|
||||
|
||||
/**
|
||||
* Los de la fuente dlt.
|
||||
*/
|
||||
args?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
guided?: (Guided | null);
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'source';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
position?: (Position | null);
|
||||
|
||||
/**
|
||||
* Columnas que identifican una fila.
|
||||
*/
|
||||
primary_key?: Array<string>;
|
||||
|
||||
/**
|
||||
* Cuál, si la fuente ofrece varios (una tabla).
|
||||
*/
|
||||
resource?: (string | null);
|
||||
|
||||
/**
|
||||
* Módulo:función de la fuente dlt.
|
||||
*/
|
||||
source: string;
|
||||
|
||||
/**
|
||||
* Transformador dlt para los archivos.
|
||||
*/
|
||||
then?: (string | null);
|
||||
}
|
||||
|
||||
@@ -8,18 +8,10 @@ import { Position } from '../models/position';
|
||||
* one `link` node among the inputs. Rule breaks are held for review.
|
||||
*/
|
||||
export interface Target {
|
||||
|
||||
/**
|
||||
* En qué estudio de la plataforma se guarda.
|
||||
*/
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'target';
|
||||
|
||||
/**
|
||||
* Cómo se ve en el diagrama.
|
||||
*/
|
||||
label?: string;
|
||||
position?: (Position | null);
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
/* 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>;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Uploaded {
|
||||
bucket_url: string;
|
||||
files: Array<string>;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/* 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);
|
||||
}
|
||||
+8
-21
@@ -4,9 +4,7 @@
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
@if (domain(); as current) {
|
||||
<span class="title">{{
|
||||
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
|
||||
}}</span>
|
||||
<span class="title">Plataforma de Indicadores</span>
|
||||
<button
|
||||
mat-flat-button
|
||||
class="domain"
|
||||
@@ -18,29 +16,18 @@
|
||||
</button>
|
||||
<mat-menu #menu="matMenu">
|
||||
@for (d of others(); track d) {
|
||||
<a mat-menu-item [routerLink]="['/' + section(), d]">{{ labels[d] }}</a>
|
||||
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a>
|
||||
}
|
||||
</mat-menu>
|
||||
} @else {
|
||||
<span class="title"></span>
|
||||
}
|
||||
@if (!onLogin()) {
|
||||
<nav class="sections" aria-label="Secciones">
|
||||
<a [routerLink]="home()" routerLinkActive="active">Indicadores</a>
|
||||
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
|
||||
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
|
||||
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
|
||||
</nav>
|
||||
@if (auth.user(); as u) {
|
||||
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
|
||||
<mat-icon>account_circle</mat-icon><span class="who-name">{{ u.name || u.email }}</span>
|
||||
</button>
|
||||
<mat-menu #account="matMenu">
|
||||
<span class="who" mat-menu-item disabled>{{ u.email }}</span>
|
||||
<button mat-menu-item (click)="logout()"><mat-icon>logout</mat-icon> Salir</button>
|
||||
</mat-menu>
|
||||
}
|
||||
}
|
||||
<nav class="sections" aria-label="Secciones">
|
||||
<a routerLink="/indicadores/cacu" routerLinkActive="active">Indicadores</a>
|
||||
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
|
||||
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
|
||||
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="main">
|
||||
|
||||
+15
-32
@@ -1,38 +1,21 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { domainAllowed, signedIn } from './auth/auth';
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: 'login', loadComponent: () => import('./auth/login').then((m) => m.Login) },
|
||||
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
|
||||
{
|
||||
path: '',
|
||||
canActivateChild: [signedIn],
|
||||
children: [
|
||||
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
|
||||
{
|
||||
path: 'indicadores/:domain',
|
||||
canActivate: [domainAllowed],
|
||||
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
|
||||
},
|
||||
{
|
||||
path: 'indicadores/:domain/pacientes/:id',
|
||||
canActivate: [domainAllowed],
|
||||
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
|
||||
},
|
||||
{
|
||||
path: 'conectar',
|
||||
loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar),
|
||||
},
|
||||
{
|
||||
path: 'revision',
|
||||
loadComponent: () => import('./revision/revision').then((m) => m.Revision),
|
||||
},
|
||||
{ path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
|
||||
{
|
||||
path: 'gobernanza/:domain',
|
||||
canActivate: [domainAllowed],
|
||||
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
|
||||
},
|
||||
{ path: '**', redirectTo: 'indicadores/cacu' },
|
||||
],
|
||||
path: 'indicadores/:domain',
|
||||
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
|
||||
},
|
||||
{
|
||||
path: 'indicadores/:domain/pacientes/:id',
|
||||
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
|
||||
},
|
||||
{ path: 'conectar', loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar) },
|
||||
{ path: 'revision', loadComponent: () => import('./revision/revision').then((m) => m.Revision) },
|
||||
{ path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' },
|
||||
{
|
||||
path: 'gobernanza/:domain',
|
||||
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
|
||||
},
|
||||
{ path: '**', redirectTo: 'indicadores/cacu' },
|
||||
];
|
||||
|
||||
+1
-43
@@ -21,22 +21,10 @@
|
||||
|
||||
.title {
|
||||
flex: 1;
|
||||
min-width: 0; // gives way to the switcher and the sections, on one line
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
|
||||
.domain,
|
||||
.sections a,
|
||||
.user {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.domain {
|
||||
--mat-button-filled-container-color: var(--color-primary);
|
||||
--mat-button-filled-label-text-color: var(--color-text);
|
||||
@@ -79,38 +67,8 @@
|
||||
width: clamp(155px, 15vw, 185px);
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
@media (max-width: 720px) {
|
||||
.title {
|
||||
display: none;
|
||||
}
|
||||
.header {
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
.sections {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
// the account by its icon alone; the switcher's name cut short if it must be
|
||||
.user .who-name {
|
||||
display: none;
|
||||
}
|
||||
.domain {
|
||||
max-width: 15rem;
|
||||
}
|
||||
.domain ::ng-deep .mdc-button__label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.header {
|
||||
flex-wrap: wrap;
|
||||
padding-block: var(--space-2);
|
||||
}
|
||||
}
|
||||
|
||||
.user {
|
||||
color: var(--color-text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
+6
-20
@@ -8,12 +8,11 @@ import { filter, map } from 'rxjs';
|
||||
import { Api } from './api/api';
|
||||
import { domains } from './api/fn/operations/domains';
|
||||
import { Domain } from './api/models/domain';
|
||||
import { Auth } from './auth/auth';
|
||||
|
||||
export const DOMAINS: Record<Domain, string> = {
|
||||
cacu: 'Cáncer cervicouterino',
|
||||
cama: 'Cáncer de mama',
|
||||
tea: 'Trastorno del espectro autista',
|
||||
tea: 'TEA',
|
||||
};
|
||||
|
||||
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
|
||||
@@ -33,7 +32,6 @@ export const DOMAINS: Record<Domain, string> = {
|
||||
export class App {
|
||||
private readonly api = inject(Api);
|
||||
private readonly router = inject(Router);
|
||||
protected readonly auth = inject(Auth);
|
||||
protected readonly labels = DOMAINS;
|
||||
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||
private readonly url = toSignal(
|
||||
@@ -43,23 +41,11 @@ export class App {
|
||||
),
|
||||
{ initialValue: '' },
|
||||
);
|
||||
/** The section and domain of a page that has one (indicators, governance): the switcher
|
||||
* moves between that section's domains. */
|
||||
private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
|
||||
protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
|
||||
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
|
||||
/** The domain of an indicator page, if this is one. */
|
||||
protected readonly domain = computed(
|
||||
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined,
|
||||
);
|
||||
protected readonly others = computed(() =>
|
||||
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
|
||||
(this.domains.value() ?? []).filter((d) => d !== this.domain()),
|
||||
);
|
||||
/** 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');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
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']);
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
<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>
|
||||
@@ -1,141 +0,0 @@
|
||||
: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;
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,7 @@
|
||||
</span>
|
||||
@if (pipelineId()) {
|
||||
@for (k of kinds; track k[0]) {
|
||||
<button mat-stroked-button (click)="add(k[0])" [matTooltip]="help[k[0]]">
|
||||
<mat-icon>add</mat-icon>{{ k[1] }}
|
||||
</button>
|
||||
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
|
||||
}
|
||||
<span class="spacer"></span>
|
||||
<button mat-stroked-button (click)="save()">Guardar</button>
|
||||
@@ -72,7 +70,10 @@
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
<p class="help">{{ help[d.kind ?? 'source'] }}</p>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
|
||||
<mat-label>Id</mat-label>
|
||||
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
|
||||
</mat-form-field>
|
||||
@if (d.inputs?.length) {
|
||||
<div class="inputs">
|
||||
Entradas:
|
||||
@@ -83,71 +84,17 @@
|
||||
}
|
||||
</div>
|
||||
} @else if (d.kind !== 'source') {
|
||||
<p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
|
||||
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
|
||||
}
|
||||
<formly-form
|
||||
[form]="form"
|
||||
[fields]="fields()"
|
||||
[model]="model"
|
||||
(modelChange)="edited($event)"
|
||||
/>
|
||||
@if (conceptMap(d); as cm) {
|
||||
<app-concept-map-editor [id]="cm" />
|
||||
}
|
||||
<mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
|
||||
<mat-tab label="Configuración">
|
||||
@if (d.kind === 'source') {
|
||||
@if (guided(d)) {
|
||||
<div class="source-summary">
|
||||
<p>
|
||||
<mat-icon>check_circle</mat-icon>
|
||||
{{ d.label || d.id }}
|
||||
</p>
|
||||
<button mat-flat-button (click)="connectSource(d.id)">
|
||||
<mat-icon>edit</mat-icon> Editar conexión
|
||||
</button>
|
||||
</div>
|
||||
} @else {
|
||||
<p class="muted">
|
||||
Esta fuente no corresponde a ningún tipo del asistente. Edítela en «Avanzado» o
|
||||
vuelva a conectarla con el asistente.
|
||||
</p>
|
||||
<button mat-stroked-button (click)="connectSource(d.id)">
|
||||
<mat-icon>cable</mat-icon> Conectar con el asistente
|
||||
</button>
|
||||
}
|
||||
}
|
||||
<formly-form
|
||||
[form]="form"
|
||||
[fields]="fields()"
|
||||
[model]="model"
|
||||
[options]="formOptions"
|
||||
(modelChange)="edited($event)"
|
||||
/>
|
||||
@if (conceptMap(d); as cm) {
|
||||
<app-concept-map-editor [id]="cm" />
|
||||
}
|
||||
</mat-tab>
|
||||
<mat-tab label="Avanzado">
|
||||
<p class="hint">
|
||||
Para personal técnico: el nodo completo como lo guarda la plataforma.
|
||||
@if (guided(d)) {
|
||||
Si cambia su fuente aquí, deja de editarse con el asistente.
|
||||
}
|
||||
</p>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
|
||||
<mat-label>Id</mat-label>
|
||||
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
|
||||
<mat-hint>Nombre interno: minúsculas, números y _.</mat-hint>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full raw">
|
||||
<mat-label>Nodo (JSON)</mat-label>
|
||||
<textarea
|
||||
matInput
|
||||
rows="16"
|
||||
[value]="raw(d)"
|
||||
(input)="rawDraft.set($any($event.target).value)"
|
||||
></textarea>
|
||||
</mat-form-field>
|
||||
@if (rawError()) {
|
||||
<p class="error" role="alert">{{ rawError() }}</p>
|
||||
}
|
||||
<button mat-stroked-button [disabled]="rawDraft() === undefined" (click)="applyRaw()">
|
||||
Aplicar
|
||||
</button>
|
||||
</mat-tab>
|
||||
</mat-tab-group>
|
||||
<button mat-stroked-button (click)="show()">Vista previa</button>
|
||||
@if (preview(); as rows) {
|
||||
<div class="preview">
|
||||
|
||||
@@ -109,86 +109,3 @@ h2 {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.help {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 13px;
|
||||
margin: 0 0 var(--space-2);
|
||||
}
|
||||
|
||||
.source-summary {
|
||||
align-items: center;
|
||||
background: var(--color-background, #f7f8f6);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
justify-content: space-between;
|
||||
margin-bottom: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
|
||||
p {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
font-weight: 500;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
p mat-icon {
|
||||
color: var(--color-success, #2e7d32);
|
||||
}
|
||||
}
|
||||
|
||||
// The canvas's nodes: the kind small on top, the name below in two lines at most.
|
||||
:host ::ng-deep default-node {
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
padding: 4px 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
:host ::ng-deep .node-caption {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
line-height: 1.2;
|
||||
}
|
||||
:host ::ng-deep .node-caption .kind {
|
||||
display: block;
|
||||
font-size: 10px;
|
||||
color: var(--color-text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
:host ::ng-deep .node-caption .name {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.panel-tabs {
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
.panel-tabs .hint {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
margin: var(--space-3) 0;
|
||||
}
|
||||
.raw textarea {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.error {
|
||||
color: var(--mat-sys-error);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
// Fields in the panel keep their hints clear of the next field's label.
|
||||
:host ::ng-deep .panel mat-form-field {
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
+12
-150
@@ -1,23 +1,12 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import {
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
resource,
|
||||
signal,
|
||||
WritableSignal,
|
||||
} from '@angular/core';
|
||||
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core';
|
||||
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatListModule } from '@angular/material/list';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
|
||||
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
|
||||
import { withFormlyMaterial } from '@ngx-formly/material';
|
||||
@@ -35,7 +24,6 @@ import type { Pipeline } from '../api/models/pipeline';
|
||||
import type { Source } from '../api/models/source';
|
||||
import { ConceptMapEditor } from './concept-map-editor';
|
||||
import { FORMLY_TYPES, nodeSchema } from './schema-form';
|
||||
import { SourceDialog, SourceDialogData, SourceDialogResult } from './source-dialog';
|
||||
|
||||
type Doc = Pipeline['nodes'][number];
|
||||
type Kind = NonNullable<Doc['kind']>;
|
||||
@@ -59,29 +47,16 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
|
||||
};
|
||||
}
|
||||
|
||||
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
|
||||
export const KINDS: Record<Kind, string> = {
|
||||
source: 'Fuente de datos',
|
||||
read: 'Leer documentos',
|
||||
route: 'Separar por tipo',
|
||||
map: 'Traducir códigos',
|
||||
extract: 'Extraer datos',
|
||||
fhir: 'Leer FHIR',
|
||||
source: 'Fuente',
|
||||
read: 'Leer',
|
||||
route: 'Filtrar',
|
||||
map: 'Mapear',
|
||||
extract: 'Extraer',
|
||||
fhir: 'FHIR',
|
||||
join: 'Unir',
|
||||
link: 'Identificar a la persona',
|
||||
target: 'Guardar en la plataforma',
|
||||
};
|
||||
export const HELP: Record<Kind, string> = {
|
||||
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
|
||||
read: '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.',
|
||||
link: 'Vincular',
|
||||
target: 'Destino',
|
||||
};
|
||||
const ID = /^[a-z][a-z0-9_]*$/;
|
||||
|
||||
@@ -98,9 +73,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatListModule,
|
||||
MatTabsModule,
|
||||
MatTableModule,
|
||||
MatTooltipModule,
|
||||
Vflow,
|
||||
ConceptMapEditor,
|
||||
],
|
||||
@@ -112,12 +85,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
|
||||
export class Conectar {
|
||||
private readonly api = inject(Api);
|
||||
private readonly jsonschema = inject(FormlyJsonschema);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
|
||||
protected readonly help = HELP;
|
||||
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
|
||||
protected readonly rawDraft = signal<string | undefined>(undefined);
|
||||
protected readonly rawError = signal('');
|
||||
|
||||
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
|
||||
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
|
||||
@@ -141,20 +109,6 @@ export class Conectar {
|
||||
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
|
||||
});
|
||||
|
||||
/** What the node forms share: each entity's fields by their titles (the catalog's). */
|
||||
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
|
||||
private readonly titles = effect(() => {
|
||||
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
|
||||
string,
|
||||
{ properties?: Record<string, { title?: string }> }
|
||||
>;
|
||||
this.formOptions.formState.fields = Object.fromEntries(
|
||||
Object.entries(entities).map(([e, s]) => [
|
||||
e,
|
||||
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
|
||||
]),
|
||||
);
|
||||
});
|
||||
protected form = new UntypedFormGroup({});
|
||||
protected model: Record<string, unknown> = {};
|
||||
/** The selected node's form, generated from its kind's JSON Schema. */
|
||||
@@ -204,47 +158,10 @@ export class Conectar {
|
||||
}
|
||||
|
||||
protected add(kind: Kind): void {
|
||||
if (kind === 'source') {
|
||||
void this.connectSource();
|
||||
return;
|
||||
}
|
||||
this.place(kind, {});
|
||||
}
|
||||
|
||||
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
|
||||
protected async connectSource(id?: string): Promise<void> {
|
||||
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
|
||||
const data: SourceDialogData = {
|
||||
pipeline: this.pipelineId(),
|
||||
node: doc?.id,
|
||||
guided: doc?.guided ?? null,
|
||||
label: doc?.label ?? '',
|
||||
};
|
||||
const ref = this.dialog.open<SourceDialog, SourceDialogData, SourceDialogResult>(SourceDialog, {
|
||||
data,
|
||||
width: '760px',
|
||||
maxWidth: '96vw',
|
||||
maxHeight: '92vh',
|
||||
autoFocus: false,
|
||||
});
|
||||
const result = await new Promise<SourceDialogResult | undefined>((done) =>
|
||||
ref.afterClosed().subscribe(done),
|
||||
);
|
||||
if (!result) return;
|
||||
if (doc) {
|
||||
this.update(doc.id, (d) => ({ ...d, guided: result.guided, label: result.label }) as Doc);
|
||||
this.select(doc.id);
|
||||
} else {
|
||||
this.place('source', { guided: result.guided, label: result.label });
|
||||
}
|
||||
this.message.set('Fuente lista. Guarde la canalización para conservarla.');
|
||||
}
|
||||
|
||||
private place(kind: Kind, fields: Record<string, unknown>): void {
|
||||
let n = 1;
|
||||
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
|
||||
const id = `${kind}_${n}`;
|
||||
const doc = { id, kind, inputs: [], ...fields } as unknown as Doc;
|
||||
const doc = { id, kind, inputs: [] } as unknown as Doc;
|
||||
this.docs.update((ds) => [...ds, doc]);
|
||||
this.nodes.update((ns) => [
|
||||
...ns,
|
||||
@@ -287,13 +204,6 @@ export class Conectar {
|
||||
);
|
||||
this.form = new UntypedFormGroup({});
|
||||
this.preview.set(undefined);
|
||||
this.rawDraft.set(undefined);
|
||||
this.rawError.set('');
|
||||
}
|
||||
|
||||
/** A source the dialog drew (its answers make its dlt fields). */
|
||||
protected guided(d: Doc): Source['guided'] {
|
||||
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
|
||||
}
|
||||
|
||||
/** The form's values into the selected node. */
|
||||
@@ -309,40 +219,6 @@ export class Conectar {
|
||||
);
|
||||
}
|
||||
|
||||
/** The node as the platform keeps it (its place on the canvas aside). */
|
||||
protected raw(d: Doc): string {
|
||||
const { position, ...rest } = d as Doc & { position?: unknown };
|
||||
return JSON.stringify(rest, null, 2);
|
||||
}
|
||||
|
||||
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
|
||||
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
|
||||
* then on (unless a catalog type makes it exactly: the platform reads it back). */
|
||||
protected applyRaw(): void {
|
||||
const d = this.doc();
|
||||
const text = this.rawDraft();
|
||||
if (!d || text === undefined) return;
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
this.rawError.set('El texto no es JSON válido.');
|
||||
return;
|
||||
}
|
||||
if (parsed['kind'] !== d.kind) {
|
||||
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
|
||||
return;
|
||||
}
|
||||
if (d.kind === 'source') {
|
||||
const dlt = ['source', 'args', 'resource', 'then'] as const;
|
||||
const before = d as unknown as Record<string, unknown>;
|
||||
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
|
||||
delete parsed['guided'];
|
||||
}
|
||||
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
|
||||
this.select(d.id);
|
||||
}
|
||||
|
||||
protected rename(to: string): void {
|
||||
const from = this.selected();
|
||||
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
|
||||
@@ -420,7 +296,7 @@ export class Conectar {
|
||||
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
|
||||
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
|
||||
this.preview.set(rows);
|
||||
this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
|
||||
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.');
|
||||
} catch (e) {
|
||||
this.message.set(problem(e));
|
||||
}
|
||||
@@ -446,14 +322,7 @@ export class Conectar {
|
||||
}
|
||||
|
||||
function text(d: Doc): string {
|
||||
// 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>`
|
||||
);
|
||||
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`;
|
||||
}
|
||||
|
||||
/** Each node's distance from the sources: its column when it has no saved position. */
|
||||
@@ -480,10 +349,3 @@ function problem(e: unknown): string {
|
||||
}
|
||||
return String(e);
|
||||
}
|
||||
|
||||
function escape(text: string): string {
|
||||
return text.replace(
|
||||
/[&<>"']/g,
|
||||
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,12 +16,6 @@ const PIPELINE = {
|
||||
when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
|
||||
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
|
||||
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
|
||||
on: {
|
||||
type: 'array',
|
||||
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
|
||||
},
|
||||
extra: { type: 'object', title: 'Extra' },
|
||||
source: { type: 'string', advanced: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -31,7 +25,7 @@ describe('node forms from the pipeline schema', () => {
|
||||
const schema = nodeSchema(PIPELINE, 'route') as any;
|
||||
|
||||
it('leaves out what the canvas edits', () => {
|
||||
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
|
||||
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']);
|
||||
expect(schema.required).toEqual(['when']);
|
||||
});
|
||||
|
||||
@@ -40,13 +34,7 @@ describe('node forms from the pipeline schema', () => {
|
||||
expect(schema.properties.resource.type).toBe('string');
|
||||
});
|
||||
|
||||
it('edits maps of texts and pairs as rows', () => {
|
||||
expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
|
||||
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
|
||||
});
|
||||
|
||||
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
|
||||
expect(schema.properties.extra).toBeUndefined();
|
||||
expect(schema.properties.source).toBeUndefined();
|
||||
it('edits maps as JSON', () => {
|
||||
expect(schema.properties.values.widget.formlyConfig.type).toBe('json');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import {
|
||||
ConfigOption,
|
||||
@@ -28,29 +27,11 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
|
||||
)!;
|
||||
const node = structuredClone(defs[name]);
|
||||
for (const field of CANVAS_FIELDS) delete node.properties?.[field];
|
||||
// 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 ?? {}),
|
||||
);
|
||||
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f));
|
||||
delete node.additionalProperties;
|
||||
return simplify(node, defs);
|
||||
}
|
||||
|
||||
function isJson(schema: Schema): boolean {
|
||||
return (
|
||||
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
|
||||
'json'
|
||||
);
|
||||
}
|
||||
|
||||
function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
|
||||
if (schema.$ref) {
|
||||
const { $ref, ...rest } = schema;
|
||||
@@ -64,34 +45,6 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
|
||||
return simplify({ ...kept[0], ...rest }, defs);
|
||||
}
|
||||
}
|
||||
const values = schema.additionalProperties as Schema | boolean | undefined;
|
||||
if (
|
||||
schema.type === 'object' &&
|
||||
!schema.properties &&
|
||||
typeof values === 'object' &&
|
||||
values.type === 'string'
|
||||
) {
|
||||
const byField = (schema as { keys?: string }).keys === 'field';
|
||||
return {
|
||||
title: schema.title,
|
||||
description: schema.description,
|
||||
default: schema.default,
|
||||
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
|
||||
} as Schema;
|
||||
}
|
||||
const pair = schema.items as Schema | undefined;
|
||||
if (
|
||||
schema.type === 'array' &&
|
||||
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
|
||||
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
|
||||
) {
|
||||
return {
|
||||
title: schema.title,
|
||||
description: schema.description,
|
||||
default: schema.default,
|
||||
widget: { formlyConfig: { type: 'pairs' } },
|
||||
} as Schema;
|
||||
}
|
||||
const isMap = schema.type === 'object' && !schema.properties;
|
||||
const isTuple =
|
||||
schema.type === 'array' &&
|
||||
@@ -164,7 +117,7 @@ export class ArrayType extends FieldArrayType {}
|
||||
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
|
||||
template: `
|
||||
<mat-form-field appearance="outline" class="json">
|
||||
<mat-label>{{ props.label }}</mat-label>
|
||||
<mat-label>{{ props.label }} (JSON)</mat-label>
|
||||
<textarea
|
||||
matInput
|
||||
rows="4"
|
||||
@@ -199,198 +152,11 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
|
||||
* per entry, its name and its text, to add or remove. */
|
||||
@Component({
|
||||
selector: 'app-formly-map',
|
||||
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
|
||||
template: `
|
||||
<div class="legend">{{ props.label }}</div>
|
||||
@if (props.description) {
|
||||
<p class="hint">{{ props.description }}</p>
|
||||
}
|
||||
@for (row of rows(); track $index; let i = $index) {
|
||||
<div class="row">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
|
||||
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
|
||||
@if (props['fieldKeys']) {
|
||||
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
|
||||
@for (o of keyOptions(row[0]); track o[0]) {
|
||||
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
} @else {
|
||||
<input
|
||||
matInput
|
||||
[value]="row[0]"
|
||||
(change)="edit(i, $any($event.target).value, row[1])"
|
||||
/>
|
||||
}
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
|
||||
<mat-label>Valor</mat-label>
|
||||
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
|
||||
</mat-form-field>
|
||||
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
<button mat-stroked-button type="button" (click)="add()">
|
||||
<mat-icon>add</mat-icon> Agregar
|
||||
</button>
|
||||
`,
|
||||
styles: `
|
||||
.legend {
|
||||
font-weight: 500;
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
column-gap: 4px;
|
||||
row-gap: 6px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.key,
|
||||
.value {
|
||||
min-width: 0;
|
||||
grid-column: 1;
|
||||
}
|
||||
.row button {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / span 2;
|
||||
align-self: center;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class MapType extends FieldType<FormlyFieldConfig> {
|
||||
/** The platform fields a key can be, by title: the node's study's, or every study's when
|
||||
* it names none (formState.fields: entity -> field -> title). */
|
||||
protected keyOptions(current: string): [string, string][] {
|
||||
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
|
||||
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
|
||||
string | undefined;
|
||||
const titles: Record<string, string> = entity
|
||||
? (all[entity] ?? {})
|
||||
: Object.assign({}, ...Object.values(all));
|
||||
const options = Object.entries(titles);
|
||||
if (current && !(current in titles)) options.unshift([current, current]);
|
||||
return options;
|
||||
}
|
||||
protected rows(): [string, string][] {
|
||||
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
|
||||
}
|
||||
private save(rows: [string, string][]): void {
|
||||
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
|
||||
this.formControl.markAsDirty();
|
||||
}
|
||||
protected edit(i: number, key: string, value: string): void {
|
||||
const rows = this.rows();
|
||||
rows[i] = [key.trim(), value];
|
||||
this.save(rows);
|
||||
}
|
||||
protected add(): void {
|
||||
// a new row needs a key before it is kept: the first field not used yet, or a new name
|
||||
const rows = this.rows();
|
||||
const used = new Set(rows.map(([k]) => k));
|
||||
const free = this.props['fieldKeys']
|
||||
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
|
||||
: undefined;
|
||||
let n = rows.length + 1;
|
||||
while (used.has(`campo_${n}`)) n++;
|
||||
this.save([...rows, [free ?? `campo_${n}`, '']]);
|
||||
}
|
||||
protected remove(i: number): void {
|
||||
this.save(this.rows().filter((_, j) => j !== i));
|
||||
}
|
||||
}
|
||||
|
||||
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
|
||||
@Component({
|
||||
selector: 'app-formly-pairs',
|
||||
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
|
||||
template: `
|
||||
<div class="legend">{{ props.label }}</div>
|
||||
@if (props.description) {
|
||||
<p class="hint">{{ props.description }}</p>
|
||||
}
|
||||
@for (row of rows(); track $index; let i = $index) {
|
||||
<div class="row">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
|
||||
<mat-label>Primera entrada</mat-label>
|
||||
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
|
||||
</mat-form-field>
|
||||
<span>=</span>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
|
||||
<mat-label>Segunda entrada</mat-label>
|
||||
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
|
||||
</mat-form-field>
|
||||
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
<button mat-stroked-button type="button" (click)="add()">
|
||||
<mat-icon>add</mat-icon> Agregar
|
||||
</button>
|
||||
`,
|
||||
styles: `
|
||||
.legend {
|
||||
font-weight: 500;
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.half {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class PairsType extends FieldType<FormlyFieldConfig> {
|
||||
protected rows(): [string, string][] {
|
||||
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
|
||||
}
|
||||
private save(rows: [string, string][]): void {
|
||||
this.formControl.setValue(rows);
|
||||
this.formControl.markAsDirty();
|
||||
}
|
||||
protected edit(i: number, side: 0 | 1, value: string): void {
|
||||
const rows = this.rows();
|
||||
rows[i][side] = value.trim();
|
||||
this.save(rows);
|
||||
}
|
||||
protected add(): void {
|
||||
this.save([...this.rows(), ['', '']]);
|
||||
}
|
||||
protected remove(i: number): void {
|
||||
this.save(this.rows().filter((_, j) => j !== i));
|
||||
}
|
||||
}
|
||||
|
||||
export const FORMLY_TYPES: ConfigOption = {
|
||||
types: [
|
||||
{ name: 'object', component: ObjectType },
|
||||
{ name: 'array', component: ArrayType },
|
||||
{ name: 'json', component: JsonType },
|
||||
{ name: 'map', component: MapType },
|
||||
{ name: 'pairs', component: PairsType },
|
||||
{ name: 'enum', extends: 'select' },
|
||||
{ name: 'string', extends: 'input' },
|
||||
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
|
||||
|
||||
@@ -1,388 +0,0 @@
|
||||
@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>
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
: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;
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { HttpClient, HttpErrorResponse, HttpEventType } from '@angular/common/http';
|
||||
import { Component, computed, inject, resource, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatExpansionModule } from '@angular/material/expansion';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { Api } from '../api/api';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { browse } from '../api/fn/ingest/browse';
|
||||
import { oauthStart } from '../api/fn/ingest/oauth-start';
|
||||
import { sourceTypes } from '../api/fn/ingest/source-types';
|
||||
import { testSource } from '../api/fn/ingest/test-source';
|
||||
import type { Browsed } from '../api/models/browsed';
|
||||
import type { FieldSpec } from '../api/models/field-spec';
|
||||
import type { Guided } from '../api/models/guided';
|
||||
import type { SourceType } from '../api/models/source-type';
|
||||
import type { Tested } from '../api/models/tested';
|
||||
import type { Uploaded } from '../api/models/uploaded';
|
||||
|
||||
/** What the dialog is opened with: the source being edited, if any. */
|
||||
export interface SourceDialogData {
|
||||
pipeline?: string;
|
||||
node?: string;
|
||||
guided?: Guided | null;
|
||||
label?: string;
|
||||
}
|
||||
const NONE: string[] = [];
|
||||
|
||||
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
|
||||
export interface SourceDialogResult {
|
||||
guided: Guided;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** The catalog's generic icon words, as Material Symbols. */
|
||||
const ICONS: Record<string, string> = {
|
||||
database: 'database',
|
||||
upload: 'upload_file',
|
||||
folder: 'folder_open',
|
||||
link: 'link',
|
||||
'folder-network': 'lan',
|
||||
server: 'dns',
|
||||
cloud: 'cloud',
|
||||
onedrive: 'cloud',
|
||||
sharepoint: 'groups',
|
||||
'google-drive': 'add_to_drive',
|
||||
web: 'api',
|
||||
fhir: 'local_hospital',
|
||||
};
|
||||
const MASK = '********';
|
||||
|
||||
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
|
||||
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
|
||||
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
|
||||
@Component({
|
||||
selector: 'app-source-dialog',
|
||||
imports: [
|
||||
FormsModule,
|
||||
NgTemplateOutlet,
|
||||
MatButtonModule,
|
||||
MatDialogModule,
|
||||
MatExpansionModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatProgressBarModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatSelectModule,
|
||||
MatSlideToggleModule,
|
||||
MatTableModule,
|
||||
],
|
||||
templateUrl: './source-dialog.html',
|
||||
styleUrl: './source-dialog.scss',
|
||||
})
|
||||
export class SourceDialog {
|
||||
private readonly api = inject(Api);
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly root = inject(ApiConfiguration).rootUrl;
|
||||
private readonly ref = inject(MatDialogRef<SourceDialog, SourceDialogResult>);
|
||||
protected readonly data = inject<SourceDialogData>(MAT_DIALOG_DATA, { optional: true }) ?? {};
|
||||
|
||||
protected readonly catalog = resource({ loader: () => this.api.invoke(sourceTypes) });
|
||||
protected readonly groups = computed(() => {
|
||||
const c = this.catalog.value();
|
||||
if (!c) return [];
|
||||
return Object.entries(c.groups).map(([id, g]) => ({
|
||||
id,
|
||||
...g,
|
||||
types: Object.entries(c.types)
|
||||
.filter(([, t]) => t.group === id)
|
||||
.map(([tid, t]) => ({ id: tid, ...t })),
|
||||
}));
|
||||
});
|
||||
|
||||
protected readonly typeId = signal<string | undefined>(this.data.guided?.type);
|
||||
protected readonly type = computed<SourceType | undefined>(() => {
|
||||
const id = this.typeId();
|
||||
return id ? this.catalog.value()?.types[id] : undefined;
|
||||
});
|
||||
protected readonly answers = signal<Record<string, unknown>>({
|
||||
...(this.data.guided?.answers ?? {}),
|
||||
});
|
||||
protected readonly label = signal(this.data.label ?? '');
|
||||
protected readonly fields = computed(() => entries(this.type()).filter(([, f]) => !f.advanced));
|
||||
protected readonly more = computed(() => entries(this.type()).filter(([, f]) => f.advanced));
|
||||
protected readonly showPassword = signal<Record<string, boolean>>({});
|
||||
|
||||
protected readonly testing = signal(false);
|
||||
/** The tables the last listing found: kept while one is picked and its rows shown. */
|
||||
protected readonly tableList = signal<string[]>([]);
|
||||
protected readonly tested = signal<Tested | undefined>(undefined);
|
||||
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
|
||||
|
||||
protected readonly browsing = signal<{ field: string; at: Browsed } | undefined>(undefined);
|
||||
protected readonly uploading = signal<{ field: string; percent: number } | undefined>(undefined);
|
||||
protected readonly uploaded = signal<Record<string, string[]>>({});
|
||||
protected readonly problem = signal('');
|
||||
|
||||
icon(name: string): string {
|
||||
return ICONS[name] ?? 'input';
|
||||
}
|
||||
|
||||
protected pick(id: string): void {
|
||||
const t = this.catalog.value()!.types[id];
|
||||
this.typeId.set(id);
|
||||
this.answers.set(
|
||||
Object.fromEntries(
|
||||
Object.entries(t.fields)
|
||||
.filter(([, f]) => f.default !== null && f.default !== undefined)
|
||||
.map(([k, f]) => [k, f.default]),
|
||||
),
|
||||
);
|
||||
if (!this.label()) this.label.set(t.title);
|
||||
this.tested.set(undefined);
|
||||
this.problem.set('');
|
||||
}
|
||||
|
||||
protected back(): void {
|
||||
this.typeId.set(undefined);
|
||||
this.tested.set(undefined);
|
||||
this.problem.set('');
|
||||
}
|
||||
|
||||
protected value(name: string): unknown {
|
||||
return this.answers()[name];
|
||||
}
|
||||
protected text(name: string): string {
|
||||
const v = this.answers()[name];
|
||||
return v === null || v === undefined ? '' : String(v);
|
||||
}
|
||||
protected set(name: string, value: unknown): void {
|
||||
this.answers.update((a) => ({ ...a, [name]: value }));
|
||||
if (this.type()?.fields[name]?.type === 'table') return;
|
||||
this.tested.set(undefined); // another connection: test again
|
||||
this.tableList.set([]);
|
||||
}
|
||||
protected setNumber(name: string, value: string): void {
|
||||
this.set(name, value === '' ? null : Number(value));
|
||||
}
|
||||
protected togglePassword(name: string): void {
|
||||
this.showPassword.update((s) => ({ ...s, [name]: !s[name] }));
|
||||
}
|
||||
protected isMasked(name: string): boolean {
|
||||
return this.answers()[name] === MASK;
|
||||
}
|
||||
protected formats() {
|
||||
return this.catalog.value()?.formats ?? [];
|
||||
}
|
||||
protected account(name: string): string | undefined {
|
||||
const a = this.answers()[name] as { user?: string } | undefined;
|
||||
return a ? (a.user ?? 'cuenta conectada') : undefined;
|
||||
}
|
||||
|
||||
/** "Probar conexión": what the source holds, in plain words. */
|
||||
protected async test(): Promise<void> {
|
||||
const type = this.typeId();
|
||||
if (!type) return;
|
||||
this.testing.set(true);
|
||||
this.problem.set('');
|
||||
try {
|
||||
const found = await this.api.invoke(testSource, {
|
||||
limit: 20,
|
||||
body: {
|
||||
type,
|
||||
answers: this.cleaned(),
|
||||
pipeline: this.data.pipeline,
|
||||
node: this.data.node,
|
||||
},
|
||||
});
|
||||
this.tested.set(found);
|
||||
if (found.tables?.length) this.tableList.set(found.tables);
|
||||
} catch (e) {
|
||||
this.problem.set(message(e));
|
||||
} finally {
|
||||
this.testing.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** A list answer (the columns picked), as a list. */
|
||||
protected listed(name: string): string[] {
|
||||
const v = this.value(name);
|
||||
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
|
||||
}
|
||||
/** The columns to pick from: the first rows', and those already picked. */
|
||||
protected columnOptions(name: string): string[] {
|
||||
return [...new Set([...this.columns(), ...this.listed(name)])];
|
||||
}
|
||||
|
||||
/** The tables a database listed, for its table field. */
|
||||
protected tables(): string[] {
|
||||
return this.tableList();
|
||||
}
|
||||
|
||||
/** Server folders, under the roots the operator mounted. */
|
||||
protected async openFolder(field: string, path?: string | null): Promise<void> {
|
||||
try {
|
||||
const at = await this.api.invoke(browse, path ? { path } : {});
|
||||
this.browsing.set({ field, at });
|
||||
} catch (e) {
|
||||
this.problem.set(message(e));
|
||||
}
|
||||
}
|
||||
protected chooseFolder(): void {
|
||||
const b = this.browsing();
|
||||
if (b?.at.path) this.set(b.field, b.at.path);
|
||||
this.browsing.set(undefined);
|
||||
}
|
||||
protected chooseFile(path: string): void {
|
||||
const b = this.browsing();
|
||||
if (b) this.set(b.field, path);
|
||||
this.browsing.set(undefined);
|
||||
}
|
||||
/** Whether the field being browsed takes a file (else a folder). */
|
||||
protected readonly browsingFiles = computed(() => {
|
||||
const b = this.browsing();
|
||||
return !!b && this.type()?.fields[b.field]?.type === 'server_file';
|
||||
});
|
||||
|
||||
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
|
||||
* subfolders. More files can be added to the same set. */
|
||||
protected upload(field: string, list: FileList | null): void {
|
||||
if (!list?.length) return;
|
||||
const body = new FormData();
|
||||
for (const file of Array.from(list)) {
|
||||
body.append('files', file, file.webkitRelativePath || file.name);
|
||||
}
|
||||
const folder = this.answers()[field];
|
||||
if (typeof folder === 'string' && folder) body.append('folder', folder);
|
||||
this.uploading.set({ field, percent: 0 });
|
||||
this.problem.set('');
|
||||
this.http
|
||||
.post<Uploaded>(`${this.root}/ingest/uploads`, body, {
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
})
|
||||
.subscribe({
|
||||
next: (event) => {
|
||||
if (event.type === HttpEventType.UploadProgress && event.total) {
|
||||
this.uploading.set({ field, percent: Math.round((100 * event.loaded) / event.total) });
|
||||
} else if (event.type === HttpEventType.Response && event.body) {
|
||||
this.set(field, event.body.bucket_url);
|
||||
this.uploaded.update((u) => ({
|
||||
...u,
|
||||
[field]: [...(u[field] ?? []), ...event.body!.files],
|
||||
}));
|
||||
}
|
||||
},
|
||||
error: (e) => {
|
||||
this.uploading.set(undefined);
|
||||
this.problem.set(message(e));
|
||||
},
|
||||
complete: () => this.uploading.set(undefined),
|
||||
});
|
||||
}
|
||||
protected dropped(field: string, event: DragEvent): void {
|
||||
event.preventDefault();
|
||||
this.upload(field, event.dataTransfer?.files ?? null);
|
||||
}
|
||||
|
||||
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
|
||||
protected async signIn(field: string, provider: string): Promise<void> {
|
||||
this.problem.set('');
|
||||
let started;
|
||||
try {
|
||||
started = await this.api.invoke(oauthStart, { provider, origin: location.origin });
|
||||
} catch (e) {
|
||||
this.problem.set(message(e));
|
||||
return;
|
||||
}
|
||||
const popup = window.open(started.url, 'isssteleon-oauth', 'width=520,height=680');
|
||||
const listen = (event: MessageEvent) => {
|
||||
const m = event.data as { type?: string; state?: string; account?: unknown; error?: string };
|
||||
if (event.origin !== location.origin || m?.type !== 'isssteleon-oauth') return;
|
||||
if (m.state !== started.state) return;
|
||||
window.removeEventListener('message', listen);
|
||||
if (m.error) this.problem.set(m.error);
|
||||
else this.set(field, m.account);
|
||||
popup?.close();
|
||||
};
|
||||
window.addEventListener('message', listen);
|
||||
}
|
||||
|
||||
protected cell(v: unknown): string {
|
||||
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
|
||||
}
|
||||
|
||||
/** Answers without empty ones (a default takes their place on the server). */
|
||||
private cleaned(): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
|
||||
);
|
||||
}
|
||||
|
||||
protected readonly missing = computed(() =>
|
||||
entries(this.type())
|
||||
.filter(([k, f]) => f.required && f.type !== 'table' && isEmpty(this.answers()[k]))
|
||||
.filter(([, f]) => f.default === null || f.default === undefined)
|
||||
.map(([, f]) => f.label),
|
||||
);
|
||||
protected readonly ready = computed(
|
||||
() =>
|
||||
!this.missing().length &&
|
||||
entries(this.type())
|
||||
.filter(([, f]) => f.type === 'table' && f.required)
|
||||
.every(([k]) => !isEmpty(this.answers()[k])),
|
||||
);
|
||||
|
||||
protected save(): void {
|
||||
const type = this.typeId();
|
||||
if (!type || !this.ready()) return;
|
||||
this.ref.close({
|
||||
guided: { type, answers: this.cleaned() },
|
||||
label: this.label() || this.type()!.title,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function entries(t: SourceType | undefined): [string, FieldSpec][] {
|
||||
return Object.entries(t?.fields ?? {});
|
||||
}
|
||||
function isEmpty(v: unknown): boolean {
|
||||
return v === '' || v === null || v === undefined;
|
||||
}
|
||||
function message(e: unknown): string {
|
||||
if (e instanceof HttpErrorResponse) {
|
||||
const d = e.error?.detail;
|
||||
if (typeof d === 'string') return d;
|
||||
if (e.status === 0) return 'No hay conexión con la plataforma. Intente de nuevo.';
|
||||
return JSON.stringify(d ?? e.message);
|
||||
}
|
||||
return String(e);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
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',
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { interpretabilityFigures, scenarioFigure } from './figures';
|
||||
import { interpretabilityFigures } from './figures';
|
||||
|
||||
describe('governance figures', () => {
|
||||
it('draws a survival report as curves with bands and the model points', () => {
|
||||
@@ -13,7 +13,7 @@ describe('governance figures', () => {
|
||||
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
|
||||
});
|
||||
|
||||
it('leaves the survival scenarios to the patient record, which draws them whole', () => {
|
||||
it("draws each survival scenario after the cohort's curves, titled with its deaths", () => {
|
||||
const scenario = {
|
||||
escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)',
|
||||
n: 1142,
|
||||
@@ -30,14 +30,14 @@ describe('governance figures', () => {
|
||||
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
|
||||
escenarios: [scenario],
|
||||
});
|
||||
expect(found.length).toBe(1); // the cohort's curves only
|
||||
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
|
||||
expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
|
||||
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
|
||||
expect(found.length).toBe(2);
|
||||
expect(found[1].title).toContain('fallecidos = 308');
|
||||
expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
|
||||
expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]);
|
||||
});
|
||||
|
||||
it('leaves recurrence scenarios to the patient record', () => {
|
||||
const found = interpretabilityFigures({
|
||||
it('draws a recurrence scenario: KM band, both Weibulls and the model points', () => {
|
||||
const [found] = interpretabilityFigures({
|
||||
kind: 'scenarios',
|
||||
recurrencia: {
|
||||
horizons_months: [12, 36],
|
||||
@@ -55,7 +55,7 @@ describe('governance figures', () => {
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(found).toEqual([]);
|
||||
expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
|
||||
});
|
||||
|
||||
it('draws an age curve with its centile band', () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { Figure } from '../plot';
|
||||
import { PALETTE } from '../plot';
|
||||
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
|
||||
|
||||
/** A curve with its band, as the reports give them. */
|
||||
interface Band {
|
||||
@@ -71,7 +70,15 @@ export function interpretabilityFigures(
|
||||
},
|
||||
},
|
||||
},
|
||||
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
|
||||
// Its clinical scenarios, those with enough deaths to draw.
|
||||
...((report['escenarios'] ?? []) as any[]).map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
|
||||
e,
|
||||
e.horizons_months,
|
||||
'Supervivencia S(t)',
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
case 'subgroups':
|
||||
@@ -140,8 +147,17 @@ export function interpretabilityFigures(
|
||||
},
|
||||
];
|
||||
}
|
||||
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
|
||||
return [];
|
||||
case 'scenarios':
|
||||
return (report['recurrencia']['escenarios'] as any[])
|
||||
.slice(0, 6)
|
||||
.map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.cohorte_nombre} · ${e.escenario} (n = ${e.n}, ${e.recaidas} recaídas)`,
|
||||
e,
|
||||
report['recurrencia']['horizons_months'],
|
||||
'Supervivencia libre de recaída',
|
||||
),
|
||||
);
|
||||
case 'age_curves': {
|
||||
// The metric's own curve; a topography has only electrodes: its first one.
|
||||
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
|
||||
@@ -189,70 +205,14 @@ export function interpretabilityFigures(
|
||||
},
|
||||
];
|
||||
}
|
||||
case 'associations': {
|
||||
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
|
||||
const rows = (report['rows'] as any[])
|
||||
.filter((r) => r.odds_ratio !== null)
|
||||
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
|
||||
const label = (r: any) =>
|
||||
`${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${
|
||||
OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code
|
||||
}`;
|
||||
return [
|
||||
{
|
||||
title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${
|
||||
report['level'] === 'item' ? 'reactivo' : 'dominio'
|
||||
})`,
|
||||
figure: {
|
||||
data: [
|
||||
{
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
x: rows.map((r) => r.odds_ratio),
|
||||
y: rows.map(label),
|
||||
error_x: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio),
|
||||
arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)),
|
||||
},
|
||||
marker: {
|
||||
color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')),
|
||||
size: 9,
|
||||
},
|
||||
customdata: rows.map((r) => r.q),
|
||||
hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}<extra>%{y}</extra>',
|
||||
showlegend: false,
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' },
|
||||
yaxis: { automargin: true, autorange: 'reversed' },
|
||||
shapes: [
|
||||
{
|
||||
type: 'line',
|
||||
x0: 1,
|
||||
x1: 1,
|
||||
yref: 'paper',
|
||||
y0: 0,
|
||||
y1: 1,
|
||||
line: { color: '#9aa0a6', dash: 'dot' },
|
||||
},
|
||||
],
|
||||
height: Math.max(320, 22 * rows.length + 80),
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
|
||||
* and the model's points with their bootstrap band (also a patient's, in her record). */
|
||||
export function scenarioFigure(
|
||||
* and the model's points with their bootstrap band. */
|
||||
function scenarioFigure(
|
||||
title: string,
|
||||
e: any,
|
||||
horizons: number[],
|
||||
@@ -286,10 +246,8 @@ export function scenarioFigure(
|
||||
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
|
||||
],
|
||||
layout: {
|
||||
// One label per month with every curve's survival there, as percentages.
|
||||
hovermode: 'x unified',
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
|
||||
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' } },
|
||||
yaxis: { title: { text: yTitle } },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
<section class="page">
|
||||
<h1>{{ labels[domain()] ?? domain() }}</h1>
|
||||
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
|
||||
<h1>Gobernanza de modelos</h1>
|
||||
<nav class="domains" aria-label="Dominios">
|
||||
@for (d of domains.value() ?? []; track d) {
|
||||
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
|
||||
}
|
||||
</nav>
|
||||
|
||||
<form class="card actions" (submit)="$event.preventDefault()">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
@@ -13,44 +17,13 @@
|
||||
name="asOf"
|
||||
/>
|
||||
</mat-form-field>
|
||||
@if (confirming(); as c) {
|
||||
<span class="confirm" role="alert">
|
||||
{{
|
||||
c === 'train'
|
||||
? '¿Entrenar todos los modelos de este dominio ahora?'
|
||||
: '¿Calcular los riesgos de todas las pacientes con los modelos en producción?'
|
||||
}}
|
||||
<button mat-flat-button type="button" (click)="start(c)">Sí, iniciar</button>
|
||||
<button mat-button type="button" (click)="confirming.set(undefined)">Cancelar</button>
|
||||
</span>
|
||||
} @else {
|
||||
<button
|
||||
mat-flat-button
|
||||
type="button"
|
||||
[disabled]="running()"
|
||||
(click)="confirming.set('train')"
|
||||
>
|
||||
Entrenar
|
||||
</button>
|
||||
<button
|
||||
mat-stroked-button
|
||||
type="button"
|
||||
[disabled]="running()"
|
||||
(click)="confirming.set('score')"
|
||||
>
|
||||
Calcular riesgos
|
||||
</button>
|
||||
@if (domain() === 'tea') {
|
||||
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
|
||||
Analizar EEG
|
||||
</button>
|
||||
}
|
||||
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button>
|
||||
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button>
|
||||
@if (domain() === 'tea') {
|
||||
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button>
|
||||
}
|
||||
@if (run(); as r) {
|
||||
<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>
|
||||
}
|
||||
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span>
|
||||
}
|
||||
</form>
|
||||
@if (message()) {
|
||||
@@ -58,21 +31,19 @@
|
||||
}
|
||||
|
||||
@if (models.isLoading()) {
|
||||
<app-loading what="los modelos" />
|
||||
<p class="muted">Cargando modelos…</p>
|
||||
} @else if (!models.value()?.length) {
|
||||
<p class="muted empty">Sin modelos entrenados en este dominio.</p>
|
||||
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
|
||||
}
|
||||
@for (m of models.value() ?? []; track m.name) {
|
||||
<div class="card model">
|
||||
<h2>
|
||||
{{ m.title }} <code class="muted code">{{ m.name }}</code>
|
||||
</h2>
|
||||
<h2>{{ m.name }}</h2>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Versión</th>
|
||||
<th>Creada</th>
|
||||
<th>Datos</th>
|
||||
<th>Entrenamiento / prueba</th>
|
||||
<th>Informes</th>
|
||||
<th>Validación clínica</th>
|
||||
<th></th>
|
||||
@@ -88,37 +59,32 @@
|
||||
}
|
||||
</td>
|
||||
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
|
||||
<td class="nowrap">{{ sizes(v) }}</td>
|
||||
<td class="num">
|
||||
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
|
||||
</td>
|
||||
<td>
|
||||
<div class="reports">
|
||||
@for (r of v.reports; track r) {
|
||||
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
|
||||
reportNames[r] ?? r
|
||||
}}</a>
|
||||
}
|
||||
@if (v.reports.includes('interpretability')) {
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
(click)="chosen.set({ name: m.name, version: v.version })"
|
||||
>
|
||||
Ver gráficas
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
@for (r of v.reports; track r) {
|
||||
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
|
||||
reportNames[r] ?? r
|
||||
}}</a>
|
||||
}
|
||||
@if (v.reports.includes('interpretability')) {
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
(click)="chosen.set({ name: m.name, version: v.version })"
|
||||
>
|
||||
Ver gráficas
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@if (!v.reports.includes('clinical_validation')) {
|
||||
<input
|
||||
#file
|
||||
type="file"
|
||||
hidden
|
||||
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
|
||||
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
|
||||
(change)="upload(m.name, v.version, $event)"
|
||||
/>
|
||||
<button mat-stroked-button type="button" (click)="file.click()">
|
||||
Subir validación clínica
|
||||
</button>
|
||||
} @else {
|
||||
Agregada
|
||||
}
|
||||
@@ -139,7 +105,7 @@
|
||||
|
||||
@if (chosen(); as c) {
|
||||
<div class="card">
|
||||
<h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
|
||||
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2>
|
||||
@for (f of figures(); track f.title) {
|
||||
<h3>{{ f.title }}</h3>
|
||||
<app-plot [figure]="f.figure" [height]="360" />
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
.subtitle {
|
||||
margin: 4px 0 var(--space-4);
|
||||
h1 {
|
||||
text-align: center;
|
||||
}
|
||||
.domains {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: var(--space-4);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
.domains a.active {
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
@@ -20,7 +30,6 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge {
|
||||
white-space: nowrap;
|
||||
margin-left: var(--space-2);
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
@@ -36,32 +45,3 @@ td a {
|
||||
padding: 48px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.reports {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
column-gap: var(--space-3);
|
||||
row-gap: 2px;
|
||||
}
|
||||
.reports a {
|
||||
margin-right: 0;
|
||||
}
|
||||
h2 .code {
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
margin-left: var(--space-2);
|
||||
}
|
||||
.confirm {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 4px 4px 4px 12px;
|
||||
border-radius: 8px;
|
||||
background: var(--color-surface-warning, #fdf3dc);
|
||||
}
|
||||
|
||||
td button {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { METRIC_NAMES } from '../eeg-labels';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { DatePipe, DecimalPipe } from '@angular/common';
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
@@ -6,6 +5,7 @@ import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { Api } from '../api/api';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
||||
@@ -16,16 +16,15 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||
import { score } from '../api/fn/models/score';
|
||||
import { train } from '../api/fn/models/train';
|
||||
import { versions } from '../api/fn/models/versions';
|
||||
import { domains } from '../api/fn/operations/domains';
|
||||
import { studies } from '../api/fn/eeg/studies';
|
||||
import { study } from '../api/fn/eeg/study';
|
||||
import { terminateRun } from '../api/fn/runs/terminate-run';
|
||||
import { runStatus } from '../api/fn/runs/run-status';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import type { Version } from '../api/models/version';
|
||||
import { DOMAINS } from '../app';
|
||||
import { Plot } from '../plot';
|
||||
import { interpretabilityFigures } from './figures';
|
||||
import { Loading } from '../loading';
|
||||
|
||||
const REPORTS: Record<string, string> = {
|
||||
technical_validation: 'Validación técnica',
|
||||
@@ -39,13 +38,13 @@ const REPORTS: Record<string, string> = {
|
||||
@Component({
|
||||
selector: 'app-gobernanza',
|
||||
imports: [
|
||||
Loading,
|
||||
DatePipe,
|
||||
DecimalPipe,
|
||||
FormsModule,
|
||||
MatButtonModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
RouterLink,
|
||||
Plot,
|
||||
],
|
||||
templateUrl: './gobernanza.html',
|
||||
@@ -58,15 +57,15 @@ export class Gobernanza {
|
||||
|
||||
protected readonly labels = DOMAINS as Record<string, string>;
|
||||
protected readonly reportNames = REPORTS;
|
||||
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||
private readonly refreshed = signal(0);
|
||||
protected readonly models = resource({
|
||||
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
|
||||
loader: async ({ params: { domain } }) => {
|
||||
const found = await this.api.invoke(models, { domain });
|
||||
const names = await this.api.invoke(models, { domain });
|
||||
return Promise.all(
|
||||
found.map(async ({ name, title }) => ({
|
||||
names.map(async (name) => ({
|
||||
name,
|
||||
title,
|
||||
versions: await this.api.invoke(versions, { domain, name }),
|
||||
})),
|
||||
);
|
||||
@@ -92,43 +91,15 @@ export class Gobernanza {
|
||||
params: () => this.eeg(),
|
||||
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
|
||||
});
|
||||
protected readonly metricNames = METRIC_NAMES;
|
||||
protected readonly asOf = signal('');
|
||||
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',
|
||||
protected readonly metricNames: Record<string, string> = {
|
||||
posterior_rhythm: 'Ritmo posterior (Hz)',
|
||||
spindles_n2: 'Husos de sueño N2 (por min)',
|
||||
spindles_n3: 'Husos de sueño N3 (por min)',
|
||||
paroxysmal_spikes: 'Picos paroxísticos (por min)',
|
||||
anteroposterior_gradient: 'Gradiente anteroposterior',
|
||||
};
|
||||
/** 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 asOf = signal('');
|
||||
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
|
||||
protected readonly message = signal('');
|
||||
|
||||
protected champion(v: Version): boolean {
|
||||
@@ -149,27 +120,18 @@ export class Gobernanza {
|
||||
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
|
||||
body: { file: file as unknown as string },
|
||||
});
|
||||
this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
|
||||
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
|
||||
this.refreshed.update((n) => n + 1);
|
||||
}
|
||||
|
||||
protected async promote(name: string, version: number): Promise<void> {
|
||||
try {
|
||||
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
|
||||
this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
|
||||
this.message.set(`${name} v${version} es ahora la versión en producción.`);
|
||||
this.refreshed.update((n) => n + 1);
|
||||
} catch (e) {
|
||||
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
|
||||
// "<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'}`,
|
||||
);
|
||||
this.message.set(`No se promovió: ${detail ?? 'error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,22 +143,14 @@ export class Gobernanza {
|
||||
private async follow(run_id: string, label: string): Promise<void> {
|
||||
for (;;) {
|
||||
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
|
||||
this.run.set({ id: run_id, kind: label, status });
|
||||
this.run.set({ kind: label, status });
|
||||
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
}
|
||||
this.refreshed.update((n) => n + 1);
|
||||
}
|
||||
|
||||
protected async stop(): Promise<void> {
|
||||
const r = this.run();
|
||||
if (!r) return;
|
||||
const found = await this.api.invoke(terminateRun, { run_id: r.id });
|
||||
this.run.set({ ...r, status: found['status'] });
|
||||
}
|
||||
|
||||
protected async start(kind: 'train' | 'score'): Promise<void> {
|
||||
this.confirming.set(undefined);
|
||||
const domain = this.domain() as Domain;
|
||||
const { run_id } =
|
||||
kind === 'train'
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results';
|
||||
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('reportes clínicos', () => {
|
||||
it('counts HPV reports and retains inconsistent and zero categories', () => {
|
||||
const d = hpvDistribution(report(4, { negative: 2, positive_16: 1, inconsistent: 1 }))!;
|
||||
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('excludes missing or unclassifiable histology from the denominator', () => {
|
||||
const d = biopsyDistribution(report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }))!;
|
||||
expect(d.total).toBe(3);
|
||||
expect(d.noData).toBe(1);
|
||||
expect(d.outside).toBe(2);
|
||||
});
|
||||
it('does not fabricate a report or accept mismatched counts', () => {
|
||||
expect(hpvDistribution(undefined)).toBeUndefined();
|
||||
expect(biopsyDistribution(report(2, { normal: 1 }))).toBeUndefined();
|
||||
expect(hpvDistribution(report(0, {}))?.total).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('citología EU7', () => {
|
||||
it('uses eligible results as denominator and preserves outside counts and zero categories', () => {
|
||||
const result = cytologyDistribution(report(10, { NILM: 6, HSIL: 2, no_data: 2 }))!;
|
||||
expect(result.total).toBe(8);
|
||||
expect(result.outside).toBe(2);
|
||||
expect(result.rows.map((r) => r.count)).toEqual([6, 0, 0, 0, 2, 0]);
|
||||
});
|
||||
it('supports an empty population without inventing percentages', () => {
|
||||
expect(cytologyDistribution(report(0, {}))).toMatchObject({ total: 0, max: 0, outside: 0 });
|
||||
});
|
||||
it('rejects absent or inconsistent distributions', () => {
|
||||
expect(cytologyDistribution(undefined)).toBeUndefined();
|
||||
expect(cytologyDistribution(report(3, { NILM: 2 }))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Reading } from './measures';
|
||||
|
||||
const CATEGORIES = [
|
||||
['NILM', 'Normal', '#408651'],
|
||||
['ASC-US', 'ASC-US', '#2778B8'],
|
||||
['LSIL', 'LIEBG', '#B19525'],
|
||||
['ASC-H', 'ASC-H', '#7955B1'],
|
||||
['HSIL', 'LIEAG', '#CE4778'],
|
||||
['CIS', 'Carcinoma in situ', '#AA394D'],
|
||||
] as const;
|
||||
|
||||
/** EU7 selects one sample per patient. Unknown categories stay outside the denominator. */
|
||||
export function cytologyDistribution(reading: Reading | undefined) {
|
||||
return distribution(reading, CATEGORIES);
|
||||
}
|
||||
|
||||
const HPV = [
|
||||
['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'],
|
||||
] as const;
|
||||
|
||||
const BIOPSY = [
|
||||
['normal', 'Normal', '#408651'],
|
||||
['LSIL', 'LIEBG (CIN 1)', '#B19525'],
|
||||
['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'],
|
||||
['CIS', 'Carcinoma in situ', '#AA394D'],
|
||||
['carcinoma', 'Carcinoma invasor', '#8D4C79'],
|
||||
] as const;
|
||||
|
||||
export function hpvDistribution(reading: Reading | undefined) {
|
||||
const result = distribution(reading, HPV);
|
||||
return result && { ...result, total: result.total + result.outside };
|
||||
}
|
||||
export const biopsyDistribution = (reading: Reading | undefined) => distribution(reading, BIOPSY);
|
||||
|
||||
function distribution(reading: Reading | undefined, categories: readonly (readonly [string, string, string])[]) {
|
||||
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]) => ({
|
||||
label, color, count: cells[code]?.['initial-population'] ?? 0,
|
||||
}));
|
||||
const total = rows.reduce((sum, row) => sum + row.count, 0);
|
||||
const max = Math.max(0, ...rows.map((row) => row.count));
|
||||
return { rows, total, outside: population - total, max,
|
||||
noData: cells['no_data']?.['initial-population'] ?? 0 };
|
||||
}
|
||||
@@ -1,480 +0,0 @@
|
||||
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})`;
|
||||
}
|
||||
|
||||
/** The screening route: each step's median days from the sample, with Q1–Q3. */
|
||||
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
|
||||
const shown = steps.filter((s) => s.r?.score !== undefined);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'bar',
|
||||
orientation: 'h',
|
||||
y: shown.map(
|
||||
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
|
||||
),
|
||||
x: shown.map((s) => s.r!.score!),
|
||||
marker: { color: OLIVE },
|
||||
error_x: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
thickness: 1.5,
|
||||
width: 6,
|
||||
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
|
||||
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
|
||||
},
|
||||
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A category's count in the report (the composition's `category` stratum). */
|
||||
function counted(r: Reading, code: string): number {
|
||||
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
|
||||
}
|
||||
|
||||
/** Groups inside, their categories outside, the total in the centre. */
|
||||
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
|
||||
const values = catalog.categories.map((c) => counted(r, c.code));
|
||||
const total = values.reduce((a, b) => a + b, 0);
|
||||
const groups = catalog.groups.map((g) =>
|
||||
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
|
||||
);
|
||||
const faded = new Set(catalog.faded ?? []);
|
||||
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
|
||||
const common = {
|
||||
type: 'pie',
|
||||
sort: false,
|
||||
direction: 'clockwise',
|
||||
rotation: 0,
|
||||
showlegend: false,
|
||||
textinfo: 'text',
|
||||
textposition: 'inside',
|
||||
insidetextorientation: 'horizontal',
|
||||
};
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
...common,
|
||||
name: 'centro',
|
||||
values: [1],
|
||||
labels: ['centro'],
|
||||
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
|
||||
text: [`<b>${count(total)}</b><br>${center}`],
|
||||
marker: { colors: ['#FFFFFF'] },
|
||||
hoverinfo: 'skip',
|
||||
},
|
||||
{
|
||||
...common,
|
||||
name: 'grupos',
|
||||
values: groups,
|
||||
labels: catalog.groups.map((g) => g.label),
|
||||
hole: 0.62,
|
||||
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
|
||||
text: groups.map((n, i) =>
|
||||
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
|
||||
),
|
||||
marker: {
|
||||
colors: catalog.groups.map((g) =>
|
||||
rgba(
|
||||
g.color,
|
||||
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
|
||||
),
|
||||
),
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
},
|
||||
{
|
||||
...common,
|
||||
name: 'categorias',
|
||||
values,
|
||||
labels: catalog.categories.map((c) => c.label),
|
||||
hole: 0.74,
|
||||
domain: { x: [0, 1], y: [0, 1] },
|
||||
// along the thin ring, so a label fits its slice
|
||||
insidetextorientation: 'tangential',
|
||||
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
|
||||
marker: {
|
||||
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
},
|
||||
] as Partial<Plotly.Data>[],
|
||||
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
|
||||
};
|
||||
}
|
||||
|
||||
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
|
||||
export function scenarioBars(
|
||||
r: Reading,
|
||||
catalog: Catalog,
|
||||
stratum: string,
|
||||
label: (code: string) => string,
|
||||
): Figure {
|
||||
const cells = r.strata[`${stratum}-category`] ?? {};
|
||||
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
|
||||
label(a).localeCompare(label(b), 'es'),
|
||||
);
|
||||
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
|
||||
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
|
||||
const y = scenarios.map(label);
|
||||
return {
|
||||
data: catalog.categories.map((c) => ({
|
||||
type: 'bar',
|
||||
orientation: 'h',
|
||||
name: c.label,
|
||||
y,
|
||||
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
|
||||
customdata: scenarios.map((s) => n(s, c.code)),
|
||||
marker: { color: c.color },
|
||||
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
|
||||
})) as Partial<Plotly.Data>[],
|
||||
layout: {
|
||||
barmode: 'stack',
|
||||
xaxis: {
|
||||
title: { text: '% de pacientes del escenario con resultado' },
|
||||
ticksuffix: ' %',
|
||||
range: [0, 100.5],
|
||||
dtick: 20,
|
||||
},
|
||||
yaxis: {
|
||||
type: 'category',
|
||||
autorange: 'reversed',
|
||||
categoryorder: 'array',
|
||||
categoryarray: y,
|
||||
automargin: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Wilson score interval at 95 %, in percent. */
|
||||
export function wilson(k: number, n: number): [number, number] {
|
||||
const z = 1.959963984540054;
|
||||
const p = k / n;
|
||||
const d = 1 + (z * z) / n;
|
||||
const c = (p + (z * z) / (2 * n)) / d;
|
||||
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
|
||||
return [100 * (c - h), 100 * (c + h)];
|
||||
}
|
||||
|
||||
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
|
||||
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
|
||||
export function rateDots(
|
||||
r: Reading,
|
||||
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
|
||||
): Figure {
|
||||
const cells = r.strata[`${spec.stratum}-category`] ?? {};
|
||||
const rows = spec.rows.map((row) => {
|
||||
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
|
||||
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
|
||||
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
|
||||
const k = biopsied
|
||||
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
|
||||
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
|
||||
const rate = den ? (100 * k) / den : null;
|
||||
const [low, high] = den ? wilson(k, den) : [null, null];
|
||||
return { row, k, den, rate, low, high };
|
||||
});
|
||||
const y = rows.map((x) => x.row.label);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
name: 'tasas',
|
||||
y,
|
||||
x: rows.map((x) => x.rate),
|
||||
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
|
||||
cliponaxis: false,
|
||||
error_x: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
color: ROSE,
|
||||
thickness: 2,
|
||||
width: 6,
|
||||
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
|
||||
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
|
||||
},
|
||||
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
margin: { t: 24, r: 110, b: 56, l: 56 },
|
||||
yaxis: {
|
||||
type: 'category',
|
||||
categoryorder: 'array',
|
||||
categoryarray: [...y].reverse(),
|
||||
automargin: true,
|
||||
},
|
||||
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
|
||||
annotations: rows.map((x) => ({
|
||||
x: 1,
|
||||
xref: 'paper',
|
||||
xanchor: 'left',
|
||||
xshift: 8,
|
||||
y: x.row.label,
|
||||
yref: 'y',
|
||||
showarrow: false,
|
||||
align: 'left',
|
||||
text: x.den
|
||||
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
|
||||
: spec.colored
|
||||
? 'Sin pacientes'
|
||||
: 'Sin biopsias',
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
|
||||
|
||||
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
|
||||
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
|
||||
export function fill(template: string, r: Reading): string {
|
||||
const p = r.populations;
|
||||
const values: Record<string, string> = {
|
||||
n: count(p['initial-population'] ?? 0),
|
||||
obs: count(p['measure-observation'] ?? 0),
|
||||
median: r.score === undefined ? '' : decimal(r.score),
|
||||
q1: decimal(r.low ?? r.score ?? 0),
|
||||
q3: decimal(r.high ?? r.score ?? 0),
|
||||
num: count(p['numerator'] ?? 0),
|
||||
den: count(p['denominator'] ?? 0),
|
||||
pct: r.score === undefined ? '' : percent(r.score * 100),
|
||||
};
|
||||
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
|
||||
}
|
||||
|
||||
/** A duration's quartile box in the period. */
|
||||
export function boxFigure(r: Reading, period: string): Figure {
|
||||
const q1 = r.low ?? r.score!;
|
||||
const q3 = r.high ?? r.score!;
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'box',
|
||||
name: 'Total',
|
||||
x: [period],
|
||||
q1: [q1],
|
||||
median: [r.score!],
|
||||
q3: [q3],
|
||||
lowerfence: [q1],
|
||||
upperfence: [q3],
|
||||
marker: { color: '#4269C2' },
|
||||
fillcolor: 'rgba(66,105,194,0.55)',
|
||||
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
|
||||
};
|
||||
}
|
||||
|
||||
/** One ring: the categories' shares, the total in the centre. */
|
||||
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
|
||||
const values = catalog.categories.map((c) => counted(r, c.code));
|
||||
const total = values.reduce((a, b) => a + b, 0);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'pie',
|
||||
hole: 0.54,
|
||||
sort: false,
|
||||
direction: 'clockwise',
|
||||
labels: catalog.categories.map((c) => c.label),
|
||||
values,
|
||||
marker: {
|
||||
colors: catalog.categories.map((c) => c.color),
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
// an empty slice says nothing (its label would sit on its neighbours')
|
||||
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
|
||||
textposition: 'outside',
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
margin: { t: 30, l: 60, r: 60, b: 30 },
|
||||
annotations: [
|
||||
{
|
||||
text: `<b>${count(total)}</b><br>${center}`,
|
||||
showarrow: false,
|
||||
x: 0.5,
|
||||
y: 0.5,
|
||||
xref: 'paper',
|
||||
yref: 'paper',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A category's count per bar, one bar each, in the period. */
|
||||
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
|
||||
const y = catalog.categories.map((c) => c.label);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'bar',
|
||||
orientation: 'h',
|
||||
name: period,
|
||||
y,
|
||||
x: catalog.categories.map((c) => counted(r, c.code)),
|
||||
marker: { color: catalog.categories.map((c) => c.color) },
|
||||
texttemplate: '%{x}',
|
||||
textposition: 'outside',
|
||||
hovertemplate: '%{y}: %{x}<extra></extra>',
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
xaxis: { title: { text: axis }, rangemode: 'tozero' },
|
||||
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2'];
|
||||
/** "16-23" as the screens say it: "16 a 23 meses". */
|
||||
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
|
||||
|
||||
function ages(r: Reading): [string, Record<string, number>][] {
|
||||
return Object.entries(r.strata['age_group'] ?? {}).sort(
|
||||
([a], [b]) => parseInt(a, 10) - parseInt(b, 10),
|
||||
);
|
||||
}
|
||||
|
||||
/** By age group: the numerator and the rest of the denominator, stacked. */
|
||||
export function ageStack(r: Reading, names: [string, string]): Figure {
|
||||
const rows = ages(r);
|
||||
const x = rows.map(([a]) => ageLabel(a));
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'bar',
|
||||
name: names[0],
|
||||
x,
|
||||
y: rows.map(([, c]) => c['numerator'] ?? 0),
|
||||
marker: { color: AGE_COLORS[0] },
|
||||
},
|
||||
{
|
||||
type: 'bar',
|
||||
name: names[1],
|
||||
x,
|
||||
y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)),
|
||||
marker: { color: AGE_COLORS[1] },
|
||||
},
|
||||
] as Partial<Plotly.Data>[],
|
||||
layout: {
|
||||
barmode: 'stack',
|
||||
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
|
||||
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** By age group: the numerator's share of the denominator, one bar each. */
|
||||
export function ageShare(r: Reading, axis: string): Figure {
|
||||
const rows = ages(r);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'bar',
|
||||
x: rows.map(([a]) => ageLabel(a)),
|
||||
y: rows.map(([, c]) =>
|
||||
c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0,
|
||||
),
|
||||
marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) },
|
||||
texttemplate: '%{y:.1f} %',
|
||||
textposition: 'outside',
|
||||
hovertemplate: '%{x}: %{y:.1f} %<extra></extra>',
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
|
||||
yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
|
||||
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
|
||||
* closed shape. */
|
||||
export function historyFigure(
|
||||
panel: HistoryPanel,
|
||||
series: { label: string; r: Reading | undefined }[],
|
||||
line: string,
|
||||
xTitle: string,
|
||||
): Figure {
|
||||
const x = series.map((s) => s.label);
|
||||
const layout = (y: string) => ({
|
||||
xaxis: { title: { text: xTitle }, type: 'category' as const },
|
||||
yaxis: { title: { text: y } },
|
||||
});
|
||||
if (panel.kind === 'stack') {
|
||||
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
|
||||
const declared = panel.series ?? [];
|
||||
const named = [
|
||||
...declared,
|
||||
...found
|
||||
.filter((c) => !declared.some((d) => d.code === c))
|
||||
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
|
||||
];
|
||||
return {
|
||||
data: named.map((c) => ({
|
||||
type: 'bar',
|
||||
name: c.label,
|
||||
x,
|
||||
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
|
||||
marker: { color: c.color },
|
||||
})),
|
||||
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
|
||||
};
|
||||
}
|
||||
const k = panel.kind === 'percent' ? 100 : 1;
|
||||
const at = (v?: number) => (v === undefined ? null : v * k);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
x: [...x, ...[...x].reverse()],
|
||||
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
|
||||
mode: 'lines',
|
||||
fill: 'toself',
|
||||
fillcolor: line + '33',
|
||||
line: { width: 0 },
|
||||
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
|
||||
hoverinfo: 'skip',
|
||||
},
|
||||
{
|
||||
x,
|
||||
y: series.map((s) => at(s.r?.score)),
|
||||
mode: 'lines+markers',
|
||||
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
|
||||
line: { color: line },
|
||||
marker: { color: line },
|
||||
},
|
||||
],
|
||||
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,32 @@
|
||||
import type { RiskAssessment } from 'fhir/r4';
|
||||
import { ageGroup, currentRisk, windowStart } from './follow-up';
|
||||
import '@angular/compiler';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
vi.mock('../plot', () => ({ PALETTE: [] }));
|
||||
import type { Patient, RiskAssessment } from 'fhir/r4';
|
||||
import { ageGroup, currentRisk, exactAge, patientLabel, patientName, rows, windowStart } from './follow-up';
|
||||
import { periods } from './measures';
|
||||
|
||||
describe('follow-up list', () => {
|
||||
it('uses synthetic FHIR names consistently and keeps the patient id as fallback', () => {
|
||||
const patient: Patient = { resourceType: 'Patient', id: 'abcdef123456', name: [{ text: ' Ana Ejemplo ' }] };
|
||||
const page = { resourceType: 'Bundle' as const, type: 'searchset' as const, entry: [{ resource: patient, search: { mode: 'match' as const } }] };
|
||||
expect(rows(page, '2026-01-01', '2026-11-27', 5)[0].name).toBe('Ana Ejemplo');
|
||||
expect(patientLabel(patient)).toBe('Ana Ejemplo');
|
||||
expect(patientName({ ...patient, name: [{ given: ['Ana', 'María'], family: 'Ejemplo' }] })).toBe('Ana María Ejemplo');
|
||||
expect(patientLabel({ ...patient, name: [{ text: ' ' }] })).toBe('abcdef1234');
|
||||
});
|
||||
it('calculates completed years only from valid full dates', () => {
|
||||
expect(exactAge('1980-11-23', '2026-11-22')).toBe(45);
|
||||
expect(exactAge('1980-11-23', '2026-11-23')).toBe(46);
|
||||
expect(exactAge('2000-02-29', '2025-02-28')).toBe(24);
|
||||
expect(exactAge('2000-02', '2026-01-01')).toBeUndefined();
|
||||
expect(exactAge('2001-02-29', '2026-01-01')).toBeUndefined();
|
||||
expect(exactAge('2027-01-01', '2026-01-01')).toBeUndefined();
|
||||
});
|
||||
it('keeps a missing prediction separate from zero', () => {
|
||||
const risk = (p?: number): RiskAssessment => ({resourceType:'RiskAssessment', status:'final', subject:{}, occurrenceDateTime:'2026-01-01', method:{coding:[{code:'cacu.cin2_pim'}]}, prediction:[{probabilityDecimal:p,whenRange:{high:{value:5}}}]});
|
||||
expect(currentRisk([risk()], 'cin2', 5)).toBeUndefined();
|
||||
expect(currentRisk([risk(0)], 'cin2', 5)).toBe(0);
|
||||
});
|
||||
it('starts the window the day after the same day months before (core.follow_up)', () => {
|
||||
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
|
||||
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
|
||||
import { code, ext, resources } from '../fhir';
|
||||
import { routeFacts, StageFacts } from '../paciente/stages';
|
||||
|
||||
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
|
||||
export interface Row {
|
||||
@@ -8,7 +9,9 @@ export interface Row {
|
||||
curp?: string;
|
||||
status: string;
|
||||
ageGroup: string;
|
||||
cytology?: { date: string; result?: string; adequacy?: string };
|
||||
age?: number;
|
||||
stageFacts: StageFacts;
|
||||
cytology?: { date: string; reportDate?: string; result?: string; adequacy?: string };
|
||||
hpv?: { date: string; positive: boolean; types1618?: boolean };
|
||||
daysToDiagnosis?: number;
|
||||
biopsy?: { date: string; histology?: string };
|
||||
@@ -17,6 +20,36 @@ export interface Row {
|
||||
|
||||
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
|
||||
|
||||
/** Prefer the supplied FHIR display text, then a structured name, then the next name. */
|
||||
export function patientName(patient: Patient | undefined): string | undefined {
|
||||
for (const name of patient?.name ?? []) {
|
||||
const text = name.text?.trim();
|
||||
if (text) return text;
|
||||
const parts = [...(name.given ?? []), name.family ?? ''].map(part => part.trim()).filter(Boolean);
|
||||
if (parts.length) return parts.join(' ');
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function patientLabel(patient: Patient | undefined): string {
|
||||
return patientName(patient) ?? patient?.id?.slice(0, 10) ?? 'No disponible';
|
||||
}
|
||||
|
||||
/** Completed years on a full, valid calendar date; partial dates are unknown. */
|
||||
export function exactAge(birth: string | undefined, cutoff: string | undefined): number | undefined {
|
||||
const parse = (text?: string): [number, number, number] | undefined => {
|
||||
if (!text || !/^\d{4}-\d{2}-\d{2}$/.test(text)) return undefined;
|
||||
const [y, m, d] = text.split('-').map(Number);
|
||||
if (y < 1 || m < 1 || m > 12 || d < 1) return undefined;
|
||||
const leap = y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
|
||||
if (d > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]) return undefined;
|
||||
return [y, m, d];
|
||||
};
|
||||
const b = parse(birth), c = parse(cutoff);
|
||||
if (!b || !c || birth! > cutoff!) return undefined;
|
||||
return c[0] - b[0] - (c[1] < b[1] || (c[1] === b[1] && c[2] < b[2]) ? 1 : 0);
|
||||
}
|
||||
|
||||
const AGE_GROUPS: [number, number][] = [
|
||||
[25, 34],
|
||||
[35, 44],
|
||||
@@ -49,7 +82,7 @@ export function currentRisk(
|
||||
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
|
||||
.flatMap((r) =>
|
||||
(r.prediction ?? [])
|
||||
.filter((p) => p.whenRange?.high?.value === horizon)
|
||||
.filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
|
||||
.map((p) => ({ r, p })),
|
||||
);
|
||||
if (!mine.length) return undefined;
|
||||
@@ -60,7 +93,7 @@ export function currentRisk(
|
||||
return Math.max(
|
||||
...mine
|
||||
.filter((x) => x.r.occurrenceDateTime === latest)
|
||||
.map((x) => x.p.probabilityDecimal ?? 0),
|
||||
.map((x) => x.p.probabilityDecimal!),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -99,12 +132,15 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
|
||||
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
|
||||
return {
|
||||
patient,
|
||||
name: patient.name?.[0]?.text,
|
||||
name: patientName(patient),
|
||||
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
|
||||
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
|
||||
ageGroup: ageGroup(patient.birthDate, cutoff),
|
||||
age: exactAge(patient.birthDate, cutoff),
|
||||
stageFacts: routeFacts(last),
|
||||
cytology: last && {
|
||||
date: last.effectiveDateTime!,
|
||||
reportDate: ext(last, 'report-date')?.valueDate,
|
||||
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
|
||||
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
|
||||
},
|
||||
@@ -146,12 +182,11 @@ export interface CamaRow {
|
||||
status: string;
|
||||
priority: string;
|
||||
ageGroup: string;
|
||||
/** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
|
||||
mammogram: { date: string; birads?: string; days?: number };
|
||||
mammogram: { date: string; birads?: string };
|
||||
biopsy?: { date: string; histology?: string };
|
||||
}
|
||||
|
||||
export const CAMA_AGE_GROUPS: [number, number][] = [
|
||||
const CAMA_AGE_GROUPS: [number, number][] = [
|
||||
[40, 49],
|
||||
[50, 59],
|
||||
[60, 69],
|
||||
@@ -187,7 +222,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
|
||||
.at(-1);
|
||||
return {
|
||||
patient,
|
||||
name: patient.name?.[0]?.text,
|
||||
name: patientName(patient),
|
||||
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
|
||||
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
|
||||
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
|
||||
@@ -197,7 +232,6 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
|
||||
birads: mammogram
|
||||
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
|
||||
: undefined,
|
||||
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
|
||||
},
|
||||
biopsy: biopsy && {
|
||||
date: reported(biopsy)!,
|
||||
|
||||
@@ -6,37 +6,35 @@ import { Fhir, resources } from '../fhir';
|
||||
import { TabDefiniciones } from './tab-definiciones';
|
||||
import { TabIndicadores } from './tab-indicadores';
|
||||
import { TabRiesgos } from './tab-riesgos';
|
||||
import { TabRiesgosTea } from './tab-riesgos-tea';
|
||||
import { TabSeguimiento } from './tab-seguimiento';
|
||||
import { TabTrazabilidad } from './tab-trazabilidad';
|
||||
import { Loading } from '../loading';
|
||||
|
||||
/** A domain's indicator page: four tabs over its FHIR measures and patients. */
|
||||
@Component({
|
||||
selector: 'app-indicadores',
|
||||
imports: [
|
||||
Loading,
|
||||
MatTabsModule,
|
||||
TabIndicadores,
|
||||
TabTrazabilidad,
|
||||
TabRiesgos,
|
||||
TabRiesgosTea,
|
||||
TabSeguimiento,
|
||||
TabDefiniciones,
|
||||
],
|
||||
template: `
|
||||
<section class="page">
|
||||
<h1>{{ title() }}</h1>
|
||||
<p class="subtitle">Explora los indicadores de {{ title().toLowerCase() }}.</p>
|
||||
<p class="subtitle">
|
||||
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
|
||||
</p>
|
||||
@if (measures.isLoading()) {
|
||||
<app-loading what="los indicadores" />
|
||||
<p class="muted">Cargando indicadores…</p>
|
||||
} @else if (measures.error()) {
|
||||
<p class="muted" role="alert">No se pudieron leer los indicadores.</p>
|
||||
} @else if (!measures.value()?.length) {
|
||||
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
|
||||
} @else {
|
||||
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
|
||||
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
|
||||
<mat-tab label="Indicadores">
|
||||
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
|
||||
</mat-tab>
|
||||
<mat-tab label="Trazabilidad">
|
||||
@@ -50,14 +48,8 @@ import { Loading } from '../loading';
|
||||
<app-tab-riesgos [domain]="domain()" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'tea') {
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-riesgos-tea [domain]="domain()" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'cama') {
|
||||
<mat-tab label="Análisis de riesgos">
|
||||
<mat-tab label="Seguimiento">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-seguimiento [domain]="domain()" />
|
||||
</ng-template>
|
||||
@@ -65,7 +57,7 @@ import { Loading } from '../loading';
|
||||
}
|
||||
<mat-tab label="Datos y definiciones">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-definiciones [domain]="domain()" [measures]="measures.value()!" />
|
||||
<app-tab-definiciones [measures]="measures.value()!" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
</mat-tab-group>
|
||||
@@ -76,27 +68,11 @@ import { Loading } from '../loading';
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
/* As the old page: the domain's name and a line under it, then a white tab bar under
|
||||
an olive rule. */
|
||||
h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 500;
|
||||
margin: 16px 0 8px;
|
||||
text-align: center;
|
||||
}
|
||||
.subtitle {
|
||||
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;
|
||||
text-align: center;
|
||||
}
|
||||
.empty {
|
||||
padding: 48px 0;
|
||||
|
||||
@@ -44,12 +44,14 @@ export function periodTypes(measure: Measure): PeriodType[] {
|
||||
|
||||
/** What one report says: its counts, its score and interval, and its strata. */
|
||||
export interface Reading {
|
||||
error?: boolean;
|
||||
populations: Record<string, number>;
|
||||
score?: number;
|
||||
low?: number;
|
||||
high?: number;
|
||||
unit?: string;
|
||||
strata: Record<string, Record<string, Record<string, number>>>;
|
||||
stratumScores?: Record<string, Record<string, { median: number; low?: number; high?: number }>>;
|
||||
}
|
||||
|
||||
function counts(group: {
|
||||
@@ -65,17 +67,13 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
|
||||
if (!group) return undefined;
|
||||
const score = group.measureScore;
|
||||
const strata: Reading['strata'] = {};
|
||||
const stratumScores: NonNullable<Reading['stratumScores']> = {};
|
||||
for (const s of group.stratifier ?? []) {
|
||||
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
|
||||
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
|
||||
const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? '';
|
||||
strata[name] = Object.fromEntries(
|
||||
(s.stratum ?? []).map((x) => [
|
||||
x.component?.length
|
||||
? x.component.map((c) => c.value?.text ?? '').join('|')
|
||||
: (x.value?.text ?? ''),
|
||||
counts(x),
|
||||
]),
|
||||
(s.stratum ?? []).map((x) => [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')?.valueDecimal, high: ext(x.measureScore, 'q3')?.valueDecimal}]));
|
||||
}
|
||||
return {
|
||||
populations: counts(group),
|
||||
@@ -84,11 +82,12 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
|
||||
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
|
||||
unit: score?.unit,
|
||||
strata,
|
||||
stratumScores,
|
||||
};
|
||||
}
|
||||
|
||||
/** Codes as the screens name them. */
|
||||
export const LABELS: Record<string, string> = {
|
||||
const LABELS: Record<string, string> = {
|
||||
NILM: 'Normal (NILM)',
|
||||
LSIL: 'LIEBG',
|
||||
HSIL: 'LIEAG',
|
||||
@@ -122,6 +121,13 @@ export const LABELS: Record<string, string> = {
|
||||
good: 'Bueno',
|
||||
bad: 'Malo',
|
||||
not_analyzed: 'Sin analizar',
|
||||
'ASCUS+': 'Citología ASC-US o mayor',
|
||||
'LSIL+': 'Citología LIEBG o mayor',
|
||||
'HSIL+': 'Citología LIEAG o mayor',
|
||||
'LIEBG+': 'Histología LIEBG o mayor',
|
||||
'LIEAG+': 'Histología LIEAG o mayor',
|
||||
initial: 'Tamizaje inicial',
|
||||
subsequent: 'Tamizaje subsecuente',
|
||||
...Object.fromEntries(
|
||||
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
|
||||
),
|
||||
@@ -134,7 +140,18 @@ export const STRATA: Record<string, string> = {
|
||||
follow_up_status: 'Estatus de seguimiento',
|
||||
result: 'Citología de alto grado',
|
||||
birads: 'BI-RADS de la mastografía',
|
||||
referral_cytology: 'Citología previa asociada por fechas',
|
||||
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',
|
||||
};
|
||||
/** Measures whose server title says "referral": the data record procedures, not issued referrals. */
|
||||
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.' },
|
||||
};
|
||||
export const measureTitle = (m: { name?: string; title?: string }) => PPV_NOTES[m.name ?? '']?.title ?? m.title ?? m.name ?? '';
|
||||
export const name = (value: string) => LABELS[value] ?? value;
|
||||
|
||||
export function formatScore(measure: Measure, r: Reading | undefined): string {
|
||||
|
||||
@@ -1,630 +0,0 @@
|
||||
/** 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;
|
||||
}
|
||||
export type Section =
|
||||
| { kind: 'route'; title: string; steps: { label: string; measure: 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[];
|
||||
}
|
||||
|
||||
const OLIVE = '#A8C243';
|
||||
const ROSE = '#C24269';
|
||||
|
||||
/** Bethesda results as the old app grouped and coloured them. */
|
||||
const CYTOLOGY: Catalog = {
|
||||
groups: [
|
||||
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
|
||||
{ id: 'abnormal', label: 'Anormal', color: ROSE },
|
||||
],
|
||||
categories: [
|
||||
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
|
||||
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
|
||||
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
|
||||
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
|
||||
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
|
||||
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
|
||||
],
|
||||
};
|
||||
|
||||
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
|
||||
const BIOPSY: Catalog = {
|
||||
groups: [
|
||||
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
|
||||
{ id: 'high', label: 'LIEAG o más', color: ROSE },
|
||||
],
|
||||
categories: [
|
||||
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
|
||||
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
|
||||
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
|
||||
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
|
||||
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
|
||||
],
|
||||
faded: ['normal', 'LSIL'],
|
||||
};
|
||||
|
||||
const CACU_DAYS = {
|
||||
value: '{median} días (mediana)',
|
||||
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
|
||||
};
|
||||
const CAMA_DAYS = {
|
||||
value: '{median} días (mediana)',
|
||||
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
|
||||
};
|
||||
const PENDING = '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,
|
||||
},
|
||||
],
|
||||
clinical: [
|
||||
{
|
||||
kind: 'route',
|
||||
title: 'Tiempos de la ruta del tamizaje',
|
||||
steps: [
|
||||
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
|
||||
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
|
||||
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
|
||||
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'figures',
|
||||
title: 'Distribución de resultados citológicos',
|
||||
figures: [
|
||||
{
|
||||
kind: 'donut',
|
||||
title: 'Distribución de resultados, {p}',
|
||||
measure: 'CACU_EU7',
|
||||
catalog: CYTOLOGY,
|
||||
center: 'pacientes',
|
||||
},
|
||||
{
|
||||
kind: 'scenario-bars',
|
||||
title: 'TOTAL por escenario clínico, {p}',
|
||||
measure: 'CACU_EU7',
|
||||
catalog: CYTOLOGY,
|
||||
stratum: 'follow_up_status',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'figures',
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
figures: [
|
||||
{
|
||||
kind: 'rates',
|
||||
title: 'Por resultado de la citología, {p}',
|
||||
measure: 'CACU_CONFIRMACION_CITOLOGIA',
|
||||
stratum: 'result',
|
||||
rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)),
|
||||
positive: ['HSIL', 'CIS', 'carcinoma'],
|
||||
axis: 'Verdaderos positivos (valor predictivo positivo)',
|
||||
},
|
||||
{
|
||||
kind: 'donut',
|
||||
title: 'Resultado de la biopsia, {p}',
|
||||
measure: 'CACU_CONFIRMACION_CITOLOGIA',
|
||||
catalog: BIOPSY,
|
||||
center: 'con biopsia',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
|
||||
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
|
||||
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
|
||||
export interface HistoryPanel {
|
||||
title: string;
|
||||
measure: string;
|
||||
kind: 'stack' | 'percent' | 'median';
|
||||
/** stack: the categories, in the old order, with their names and colours */
|
||||
series?: { code: string; label: string; color: string }[];
|
||||
/** stack: the y axis */
|
||||
axis?: string;
|
||||
group?: string;
|
||||
}
|
||||
export interface History {
|
||||
panels: HistoryPanel[];
|
||||
/** the line's colour (percent and median) */
|
||||
line: string;
|
||||
/** how many of the latest months the tab opens with (none: from the first with data) */
|
||||
months?: number;
|
||||
}
|
||||
|
||||
const GREY = '#C9CDD2';
|
||||
const stack = (
|
||||
title: string,
|
||||
measure: string,
|
||||
axis: string,
|
||||
series: [string, string, string][],
|
||||
): HistoryPanel => ({
|
||||
title,
|
||||
measure,
|
||||
kind: 'stack',
|
||||
axis,
|
||||
series: series.map(([code, label, color]) => ({ code, label, color })),
|
||||
});
|
||||
const BIRADS_SERIES: [string, string, string][] = [
|
||||
['4A', 'BI-RADS 4A', '#C24269'],
|
||||
['4B', 'BI-RADS 4B', '#9C42C2'],
|
||||
['4C', 'BI-RADS 4C', '#5C42C2'],
|
||||
['5', 'BI-RADS 5', '#C2429C'],
|
||||
['6', 'BI-RADS 6', '#8E2F62'],
|
||||
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
|
||||
];
|
||||
|
||||
export const HISTORY: Record<string, History> = {
|
||||
cacu: {
|
||||
line: '#6A8000',
|
||||
months: 5,
|
||||
panels: [
|
||||
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
|
||||
['NILM', 'Normal', '#9DBFE3'],
|
||||
['ASC-US', 'ASC-US', '#2F6DB3'],
|
||||
['LSIL', 'LIEBG', '#9C42C2'],
|
||||
['ASC-H', 'ASC-H', '#5C42C2'],
|
||||
['HSIL', 'LIEAG', '#C2429C'],
|
||||
['CIS', 'Carcinoma in situ', '#8E2F62'],
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
|
||||
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
|
||||
stack(
|
||||
'Resultado de biopsia tras citología de alto grado',
|
||||
'CACU_CONFIRMACION_CITOLOGIA',
|
||||
'Pacientes',
|
||||
[
|
||||
['normal', 'Normal', '#9DBFE3'],
|
||||
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
|
||||
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
|
||||
['CIS', 'Carcinoma in situ', '#9C42C2'],
|
||||
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
|
||||
['no_biopsy', 'Sin biopsia aún', GREY],
|
||||
['no_data', 'Biopsia sin grado', GREY],
|
||||
],
|
||||
),
|
||||
{
|
||||
title: 'Días de la toma de la citología a su resultado',
|
||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a tratamiento',
|
||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de diagnóstico a tratamiento',
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Riesgo CIN2+ por banda',
|
||||
measure: 'CACU_RIESGO_BANDA',
|
||||
kind: 'stack',
|
||||
axis: 'Pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
cama: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{
|
||||
title: 'Días de la toma de la mastografía a su resultado',
|
||||
measure: 'CAMA_EU38A',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días del resultado de la mastografía al diagnóstico',
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de tamizaje a diagnóstico',
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
stack(
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_MASTOGRAFIA',
|
||||
'Mastografías',
|
||||
BIRADS_SERIES,
|
||||
),
|
||||
stack(
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_PACIENTE',
|
||||
'Pacientes',
|
||||
BIRADS_SERIES,
|
||||
),
|
||||
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
|
||||
['benign', 'Benigno', '#9DBFE3'],
|
||||
['in_situ', 'Carcinoma in situ', '#C24269'],
|
||||
['invasive', 'Carcinoma invasor', '#9C42C2'],
|
||||
['no_biopsy', 'Sin biopsia reportada', GREY],
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
measure: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
kind: 'percent',
|
||||
},
|
||||
],
|
||||
},
|
||||
tea: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de M-CHAT a ADOS-2',
|
||||
measure: 'M26_DIAS_MCHAT_ADOS2',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de ADOS-2 a diagnóstico',
|
||||
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de M-CHAT a diagnóstico positivo',
|
||||
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
|
||||
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
|
||||
['in_process', 'En proceso', '#B8433A'],
|
||||
]),
|
||||
{
|
||||
title: 'Porcentaje de confirmación diagnóstica',
|
||||
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
|
||||
kind: 'percent',
|
||||
},
|
||||
{
|
||||
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
|
||||
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
|
||||
kind: 'percent',
|
||||
},
|
||||
{
|
||||
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
|
||||
kind: 'percent',
|
||||
},
|
||||
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
|
||||
['mchat_only', 'Solo M-CHAT', '#B8433A'],
|
||||
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
|
||||
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
|
||||
['eeg', 'Con EEG', '#A8C243'],
|
||||
]),
|
||||
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
|
||||
['good', 'Bueno', '#A8C243'],
|
||||
['bad', 'No aceptable', '#B8433A'],
|
||||
['not_analyzed', 'Sin analizar', GREY],
|
||||
]),
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,83 +0,0 @@
|
||||
import { Component, model, output, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
|
||||
/** A search box's text as FHIR Patient search parameters: one word with a digit is an
|
||||
* identifier (a CURP or a record number); anything else is her name. */
|
||||
export function patientSearch(text: string): { name?: string; identifier?: string } {
|
||||
const t = text.trim();
|
||||
if (!t) return {};
|
||||
return /\d/.test(t) && !/\s/.test(t) ? { identifier: t } : { name: t };
|
||||
}
|
||||
|
||||
const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
|
||||
|
||||
/** Whether a row matches the search in the browser (lists loaded whole): each word starts a
|
||||
* word of one of its texts (a name, an identifier, the pseudonymous id). */
|
||||
export function matchesSearch(text: string, texts: (string | undefined)[]): boolean {
|
||||
const words = fold(text).split(/\s+/).filter(Boolean);
|
||||
if (!words.length) return true;
|
||||
const known = texts.filter((t): t is string => !!t).map((t) => fold(t).split(/\s+/));
|
||||
return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w))));
|
||||
}
|
||||
|
||||
/** "Buscar paciente": applied on Enter or the search button, cleared with the cross. */
|
||||
@Component({
|
||||
selector: 'app-patient-search',
|
||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
|
||||
template: `
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="patient-search">
|
||||
<mat-label>Buscar paciente</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="search"
|
||||
name="patient-search"
|
||||
[placeholder]="hint"
|
||||
[ngModel]="draft()"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
(ngModelChange)="draft.set($event)"
|
||||
(keydown.enter)="$event.preventDefault(); apply()"
|
||||
/>
|
||||
@if (value()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
matSuffix
|
||||
type="button"
|
||||
aria-label="Limpiar búsqueda"
|
||||
(click)="clear()"
|
||||
>
|
||||
<mat-icon>close</mat-icon>
|
||||
</button>
|
||||
} @else {
|
||||
<button mat-icon-button matSuffix type="button" aria-label="Buscar" (click)="apply()">
|
||||
<mat-icon>search</mat-icon>
|
||||
</button>
|
||||
}
|
||||
</mat-form-field>
|
||||
`,
|
||||
styles: `
|
||||
.patient-search {
|
||||
min-width: 18rem;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class PatientSearch {
|
||||
/** The search as applied. */
|
||||
readonly value = model('');
|
||||
readonly searched = output<string>();
|
||||
protected readonly draft = signal('');
|
||||
protected readonly hint = 'Nombre, CURP o expediente';
|
||||
|
||||
protected apply(): void {
|
||||
const text = this.draft().trim();
|
||||
this.value.set(text);
|
||||
this.searched.emit(text);
|
||||
}
|
||||
protected clear(): void {
|
||||
this.draft.set('');
|
||||
this.apply();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { PPV_NOTES, STRATA, measureTitle, name } from './measures';
|
||||
|
||||
describe('referral PPV wording', () => {
|
||||
it('never presents procedures or date associations as confirmed referrals', () => {
|
||||
for (const measure of ['CACU_VPP_COLPOSCOPIA', 'CACU_VPP_BIOPSIA']) {
|
||||
const { title, note } = PPV_NOTES[measure];
|
||||
expect(title).toContain('registrada');
|
||||
expect(title.toLowerCase()).not.toContain('referencia');
|
||||
expect(note).toContain('asociación por fechas');
|
||||
expect(note).toContain('no un vínculo clínico confirmado');
|
||||
expect(measureTitle({ name: measure, title: 'VPP de la referencia' })).toBe(title);
|
||||
}
|
||||
expect(PPV_NOTES['CACU_VPP_COLPOSCOPIA'].note).toContain('inferirse de notas');
|
||||
});
|
||||
|
||||
it('keeps the server title for other measures', () => {
|
||||
expect(measureTitle({ name: 'CACU_EU7', title: 'Pacientes evaluadas' })).toBe('Pacientes evaluadas');
|
||||
});
|
||||
|
||||
it('names the new strata and their values in Spanish', () => {
|
||||
for (const code of ['referral_cytology', 'histology_level', 'screening_round', 'result_initial', 'result_subsequent'])
|
||||
expect(STRATA[code]).toBeTruthy();
|
||||
expect(name('ASCUS+')).toBe('Citología ASC-US o mayor');
|
||||
expect(name('LSIL+')).toBe('Citología LIEBG o mayor');
|
||||
expect(name('HSIL+')).toBe('Citología LIEAG o mayor');
|
||||
expect(name('LIEBG+')).toBe('Histología LIEBG o mayor');
|
||||
expect(name('LIEAG+')).toBe('Histología LIEAG o mayor');
|
||||
expect(name('invasive')).toBe('Carcinoma invasor');
|
||||
expect(name('initial')).toBe('Tamizaje inicial');
|
||||
expect(name('subsequent')).toBe('Tamizaje subsecuente');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { Component, input } from '@angular/core';
|
||||
import type { Measure } from 'fhir/r4';
|
||||
import { DOMAINS } from '../app';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import { code, label } from '../fhir';
|
||||
import { periodTypes, STRATA } from './measures';
|
||||
|
||||
@@ -16,120 +14,48 @@ const IMPROVEMENT: Record<string, string> = {
|
||||
};
|
||||
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
|
||||
|
||||
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
|
||||
* indicator opening to what it is (how it scores, which way is better, its periods and
|
||||
* strata). */
|
||||
/** What each measure is: how it scores, which way is better, its periods and strata. */
|
||||
@Component({
|
||||
selector: 'app-tab-definiciones',
|
||||
template: `
|
||||
<section class="card">
|
||||
<h2>Datos y definiciones de {{ domainName() }}</h2>
|
||||
<section aria-labelledby="domain-info-title">
|
||||
<h3 id="domain-info-title">Información del dominio</h3>
|
||||
@if (domain() === 'cacu') {
|
||||
<p>
|
||||
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
|
||||
espécimen fue insatisfactorio.
|
||||
</p>
|
||||
}
|
||||
@if (available().length) {
|
||||
<p>Periodicidad disponible: {{ available().join(', ') }}.</p>
|
||||
} @else {
|
||||
<p>Periodicidad: pendiente de información.</p>
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="definitions-catalog-title">
|
||||
<h3 id="definitions-catalog-title">Catálogo de indicadores</h3>
|
||||
<p>Consulta las gráficas disponibles y la periodicidad de cada indicador.</p>
|
||||
<table class="plain card">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Indicador</th>
|
||||
<th>Clave</th>
|
||||
<th>Cálculo</th>
|
||||
<th>Mejora</th>
|
||||
<th>Periodos</th>
|
||||
<th>Estratos</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (m of measures(); track m.id) {
|
||||
<details>
|
||||
<summary>{{ m.title || 'Nombre pendiente de publicación' }}</summary>
|
||||
<div class="indicator-detail">
|
||||
@if (m.description) {
|
||||
<p>{{ m.description }}</p>
|
||||
}
|
||||
<h4>Cálculo</h4>
|
||||
<p>
|
||||
{{ scoring[code(m.scoring) ?? ''] }}
|
||||
@if (improvement[code(m.improvementNotation) ?? '']; as better) {
|
||||
· {{ better }}
|
||||
}
|
||||
</p>
|
||||
<h4>Tipos de periodo admitidos</h4>
|
||||
@if (types(m).length) {
|
||||
<ul>
|
||||
@for (t of types(m); track t) {
|
||||
<li>{{ t }}</li>
|
||||
}
|
||||
</ul>
|
||||
} @else {
|
||||
<p>Pendiente de información.</p>
|
||||
}
|
||||
<h4>Estratos</h4>
|
||||
<p>{{ strata(m) }}</p>
|
||||
<p class="muted">
|
||||
Clave <code>{{ m.name }}</code> · versión {{ m.version }}
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
} @empty {
|
||||
<p role="status">
|
||||
No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de
|
||||
información.
|
||||
</p>
|
||||
<tr>
|
||||
<td>{{ m.title }}</td>
|
||||
<td>
|
||||
<code>{{ m.name }}</code> v{{ m.version }}
|
||||
</td>
|
||||
<td>{{ scoring[code(m.scoring) ?? ''] }}</td>
|
||||
<td>{{ improvement[code(m.improvementNotation) ?? ''] ?? '—' }}</td>
|
||||
<td>{{ types(m) }}</td>
|
||||
<td>{{ strata(m) }}</td>
|
||||
</tr>
|
||||
}
|
||||
</section>
|
||||
</section>
|
||||
`,
|
||||
styles: `
|
||||
:host {
|
||||
display: block;
|
||||
padding-top: 16px;
|
||||
}
|
||||
.card {
|
||||
background: var(--mat-sys-surface);
|
||||
border: 1px solid var(--mat-sys-outline-variant);
|
||||
border-radius: 12px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
h2,
|
||||
h3 {
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
}
|
||||
h4 {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
details {
|
||||
border-bottom: 1px solid var(--mat-sys-outline-variant);
|
||||
padding: 8px 0;
|
||||
}
|
||||
summary {
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
}
|
||||
.indicator-detail {
|
||||
padding: 4px 0 8px 16px;
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
`,
|
||||
styles: ':host { display: block; padding-top: 16px; overflow-x: auto; }',
|
||||
})
|
||||
export class TabDefiniciones {
|
||||
readonly domain = input.required<string>();
|
||||
readonly measures = input.required<Measure[]>();
|
||||
protected readonly scoring = SCORING;
|
||||
protected readonly improvement = IMPROVEMENT;
|
||||
protected readonly code = code;
|
||||
protected readonly domainName = computed(
|
||||
() => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(),
|
||||
);
|
||||
/** The periodicities any of its indicators admits. */
|
||||
protected readonly available = computed(() =>
|
||||
[...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p),
|
||||
);
|
||||
protected types(m: Measure): string[] {
|
||||
return periodTypes(m).map((p) => PERIODS[p] ?? p);
|
||||
protected types(m: Measure): string {
|
||||
return periodTypes(m)
|
||||
.map((p) => PERIODS[p] ?? p)
|
||||
.join(', ');
|
||||
}
|
||||
protected strata(m: Measure): string {
|
||||
const names = (m.group?.[0]?.stratifier ?? []).map((s) => code(s.code) ?? label(s.code));
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<div class="filters card">
|
||||
<h2 class="filters-title">Filtros</h2>
|
||||
<div class="field">
|
||||
<span class="label">Intervalo de análisis</span>
|
||||
<mat-button-toggle-group
|
||||
@@ -15,7 +14,7 @@
|
||||
<mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
|
||||
@for (p of options(); track p) {
|
||||
<mat-option [value]="p">{{ p }}</mat-option>
|
||||
<mat-option [value]="p">{{ label(p) }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@@ -26,251 +25,216 @@
|
||||
>
|
||||
Aplicar
|
||||
</button>
|
||||
@if (applied(); as p) {
|
||||
<span class="muted applied">Mostrando {{ label(p) }}</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="los indicadores" text="Calculando los indicadores…" />
|
||||
<p class="muted">Calculando…</p>
|
||||
}
|
||||
|
||||
@if (reports.error()) {
|
||||
<div class="load-error" role="alert">
|
||||
<p>No se obtuvieron los indicadores del periodo.</p>
|
||||
<button mat-stroked-button (click)="reports.reload()">Reintentar</button>
|
||||
</div>
|
||||
}
|
||||
@if (page(); as pg) {
|
||||
@if (applied(); as period) {
|
||||
<section class="card opportunity" aria-labelledby="opportunity-title">
|
||||
<div class="section-head">
|
||||
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
|
||||
<span class="period">Periodo {{ period }}</span>
|
||||
</div>
|
||||
<div class="kpis">
|
||||
@for (k of pg.kpis; track k.title) {
|
||||
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
|
||||
<mat-card-content>
|
||||
<h3 class="kpi-title">{{ k.title }}</h3>
|
||||
@if (reports.isLoading() && k.measure) {
|
||||
<app-loading [what]="k.title.toLowerCase()" />
|
||||
} @else {
|
||||
<div class="kpi-value" [class.pending]="!k.measure">
|
||||
@let v = kpiParts(kpiValue(k));
|
||||
{{ v[0] }}
|
||||
@if (v[1]) {
|
||||
<span class="kpi-qualifier">{{ v[1] }}</span>
|
||||
}
|
||||
</div>
|
||||
<div class="kpi-detail">{{ kpiNote(k) }}</div>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
@for (section of pg.opportunity ?? []; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="card clinical-page" aria-labelledby="clinical-title">
|
||||
<h2 id="clinical-title">Indicadores clínicos</h2>
|
||||
@for (section of pg.clinical; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
<ng-template #sectionView let-section let-period="period">
|
||||
@switch (section.kind) {
|
||||
@case ('route') {
|
||||
<h3 class="route-title">{{ section.title }}</h3>
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="los tiempos de la ruta" [figure]="true" />
|
||||
} @else if (routeOf(section); as fig) {
|
||||
<app-plot [figure]="fig" [height]="300" />
|
||||
} @else {
|
||||
<p class="state">Sin tiempos publicados en el periodo.</p>
|
||||
}
|
||||
}
|
||||
@case ('tea-summary') {
|
||||
@if (teaSummary(); as t) {
|
||||
<mat-card appearance="outlined" class="summary">
|
||||
<mat-card-content>
|
||||
<h2 class="box-title">Resumen</h2>
|
||||
<p>
|
||||
Al cierre del periodo <mark>{{ period }}</mark>, se evaluaron
|
||||
<mark>{{ t.evaluated }}</mark> niños entre 16 y 36 meses;
|
||||
<mark>{{ t.mchatOnly }}</mark> únicamente tienen M-CHAT,
|
||||
<mark>{{ t.psychology }}</mark> hasta la evaluación psicológica y
|
||||
<mark>{{ t.neuropediatrics }}</mark> presentan evaluación neuropediátrica. En este
|
||||
periodo el <mark>{{ t.confirmed }}</mark> de los pacientes tiene diagnóstico
|
||||
confirmado de TEA (CIE-10 F84.0). Las ventanas de tiempo<sup>*</sup> de tamizaje
|
||||
son: <mark>{{ t.toAdos }}</mark> de M-CHAT (psicología) a ADOS-2,
|
||||
<mark>{{ t.toDiagnosis }}</mark> de ADOS-2 a diagnóstico. El tiempo<sup>*</sup> de
|
||||
tamizaje completo de M-CHAT a diagnóstico fue de <mark>{{ t.whole }}</mark>.
|
||||
</p>
|
||||
<p>
|
||||
De los <mark>{{ t.diagnosed }}</mark> niños con diagnóstico confirmado en este
|
||||
periodo, <mark>{{ t.eeg }}</mark> presentan estudio de EEG y faltan
|
||||
<mark>{{ t.missing }}</mark> por realizarlo. <mark>{{ t.unusable }}</mark> estudios
|
||||
de EEG no son aceptables para un análisis.
|
||||
</p>
|
||||
<p class="state">*tomando la mediana de los tiempos</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
} @else if (reports.isLoading()) {
|
||||
<app-loading what="el resumen del periodo" />
|
||||
}
|
||||
}
|
||||
@case ('grid') {
|
||||
<div class="grid-figures">
|
||||
@for (f of section.figures; track f.title) {
|
||||
<mat-card appearance="outlined" class="figure-card" [attr.data-figure]="f.kind">
|
||||
<mat-card-content>
|
||||
<h2 class="box-title">{{ f.title }}</h2>
|
||||
<p class="state">Filtro general aplicado: {{ period }}</p>
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="la figura" [figure]="true" />
|
||||
} @else if (figureOf(f); as fig) {
|
||||
<app-plot [figure]="fig" [height]="320" />
|
||||
} @else {
|
||||
<div class="empty-figure">Sin datos publicados</div>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@case ('boxes') {
|
||||
@if (section.title) {
|
||||
<h3 class="boxes-title">{{ section.title }}</h3>
|
||||
}
|
||||
<div class="box-grid" [class.standalone]="!section.title">
|
||||
@for (b of section.cards; track b.title) {
|
||||
<mat-card
|
||||
appearance="outlined"
|
||||
class="box-card"
|
||||
[attr.data-measure]="b.measure ?? null"
|
||||
>
|
||||
<mat-card-content>
|
||||
<h2 class="box-title">{{ b.title }}</h2>
|
||||
@if (!b.measure) {
|
||||
<p class="state">{{ pending }}</p>
|
||||
<div class="empty-figure">Sin datos publicados</div>
|
||||
} @else {
|
||||
<p class="state">Filtro general aplicado: {{ period }}</p>
|
||||
@if (section.subtitles) {
|
||||
<h2 class="box-subtitle">{{ measureTitle(b.measure) }}</h2>
|
||||
<p class="state">Figura: Caja de cuartiles</p>
|
||||
}
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="la figura" [figure]="true" />
|
||||
} @else if (boxOf(b.measure); as fig) {
|
||||
<app-plot [figure]="fig" [height]="320" />
|
||||
} @else {
|
||||
<div class="empty-figure">Sin datos publicados</div>
|
||||
}
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@case ('card') {
|
||||
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
|
||||
<mat-card-content>
|
||||
<h3 class="kpi-title">{{ section.title }}</h3>
|
||||
<div class="kpi-value">
|
||||
@let w = kpiParts(kpiValue(section));
|
||||
{{ w[0] }}
|
||||
@if (w[1]) {
|
||||
<span class="kpi-qualifier">{{ w[1] }}</span>
|
||||
}
|
||||
</div>
|
||||
<div class="kpi-detail">{{ kpiNote(section) }}</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
@default {
|
||||
<mat-card appearance="outlined" class="figure-card">
|
||||
<mat-card-content>
|
||||
@if (section.title) {
|
||||
<h2 class="figure-card-title">{{ section.title }}</h2>
|
||||
}
|
||||
<div class="figure-row">
|
||||
@for (f of section.figures; track f.title) {
|
||||
<div class="figure" [attr.data-figure]="f.kind">
|
||||
<h3 [class.light]="f.kind === 'share-donut'">{{ titled(f.title) }}</h3>
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="la figura" [figure]="true" />
|
||||
} @else if (figureOf(f); as fig) {
|
||||
<app-plot [figure]="fig" [height]="360" />
|
||||
} @else {
|
||||
<p class="state">Sin datos en el periodo.</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
}
|
||||
</ng-template>
|
||||
} @else {
|
||||
@if (kpis().length) {
|
||||
<h2>Indicadores de oportunidad</h2>
|
||||
<div class="kpis">
|
||||
@for (m of kpis(); track m.id) {
|
||||
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
|
||||
<mat-card-content>
|
||||
<div class="kpi-title">{{ m.title }}</div>
|
||||
<div class="kpi-value">{{ score(m) }}</div>
|
||||
<div class="kpi-detail muted">{{ detail(m) }}</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (layout().route.length) {
|
||||
<mat-card appearance="outlined" class="route">
|
||||
<mat-card-header>
|
||||
<mat-card-title>Ruta del tamizaje</mat-card-title>
|
||||
<mat-button-toggle-group
|
||||
[value]="routeView()"
|
||||
(change)="routeView.set($event.value)"
|
||||
class="route-toggle"
|
||||
>
|
||||
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<app-plot [figure]="route()" [height]="260" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
|
||||
<h2>Indicadores clínicos</h2>
|
||||
<div class="clinical">
|
||||
@for (m of clinical(); track m.id) {
|
||||
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
|
||||
<mat-card-header>
|
||||
<mat-card-title>{{ m.title }}</mat-card-title>
|
||||
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
|
||||
</mat-card-header>
|
||||
@if (kpis().length) {
|
||||
<h2>Indicadores de oportunidad</h2>
|
||||
<div class="kpis">
|
||||
@for (m of kpis(); track m.id) {
|
||||
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
|
||||
<mat-card-content>
|
||||
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
|
||||
<h3 class="figure-title">{{ f.title }}</h3>
|
||||
<app-plot [figure]="f.figure" [height]="260" />
|
||||
} @empty {
|
||||
<p class="muted">Sin datos en el periodo.</p>
|
||||
}
|
||||
<div class="kpi-title">{{ m.title }}</div>
|
||||
<div class="kpi-value">{{ score(m) }}</div>
|
||||
<div class="kpi-detail muted">{{ detail(m) }}</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (layout().route.length) {
|
||||
<mat-card appearance="outlined" class="route">
|
||||
<mat-card-header>
|
||||
<mat-card-title>{{ domain() === 'cacu' ? 'Tiempos de la ruta del tamizaje' : 'Ruta del tamizaje' }}</mat-card-title>
|
||||
<mat-button-toggle-group
|
||||
[value]="routeView()"
|
||||
(change)="routeView.set($event.value)"
|
||||
class="route-toggle"
|
||||
>
|
||||
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
|
||||
@if (domain() === 'cacu') { <mat-button-toggle value="icd10">Desglose por CIE-10</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (domain() !== 'cacu') { <app-plot [figure]="route()" [height]="260" /> }
|
||||
@else if (routeView() === 'icd10') {
|
||||
<p class="muted">Desglose exploratorio basado en la asociación temporal existente; no confirma un vínculo clínico entre la toma y el diagnóstico.</p>
|
||||
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
|
||||
@else if (icd(); as r) {
|
||||
<p class="muted">{{ r.populations['measure-observation'] ?? 0 }} observaciones · escala 0 a {{ icdMax() }} días.</p>
|
||||
<table class="distribution route-table" aria-label="Tiempos por CIE-10"><thead><tr><th>CIE-10 y descripción</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead><tbody>
|
||||
@for (row of icdRows(); track row.label) {
|
||||
<tr><th scope="row">{{ row.label }}<span class="bar-track duration-track" aria-hidden="true"><span class="bar" [style.width.%]="icdMax() ? 100 * row.median / icdMax() : 0"></span><span class="quartile" [style.left.%]="icdMax() ? 100 * (row.low ?? 0) / icdMax() : 0"></span><span class="quartile" [style.left.%]="icdMax() ? 100 * (row.high ?? 0) / icdMax() : 0"></span></span></th><td>{{ row.median }} días</td><td>{{ row.count }}</td><td>{{ row.low }}–{{ row.high }}</td></tr>
|
||||
} @empty { <tr><td colspan="4">Sin observaciones en el periodo.</td></tr> }
|
||||
</tbody></table>
|
||||
} @else { <p class="muted">Desglose no disponible en este servidor o periodo.</p> }
|
||||
} @else {
|
||||
@if (routeView() === 'step') {
|
||||
<p class="muted">Representación ilustrativa: las barras se desplazan según las medianas publicadas por tramo; no representan la duración acumulada observada de una misma cohorte.</p>
|
||||
<app-plot [figure]="stepRoute()" [height]="stepRouteHeight()" />
|
||||
<details class="route-values">
|
||||
<summary>Cuartiles y valores por tramo</summary>
|
||||
<p class="muted">Q1, mediana y Q3 corresponden a las observaciones disponibles de cada tramo. Los tramos sin datos se indican como no disponibles.</p>
|
||||
<table class="distribution route-table" aria-label="Valores estadísticos de tiempos por tramo">
|
||||
<thead><tr><th>Tramo</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead>
|
||||
<tbody>@for (row of routeRows(); track row.label) {
|
||||
<tr><th scope="row">{{ row.label }}</th><td>{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}</td>
|
||||
<td>{{ row.reading?.score !== undefined ? (row.reading?.populations?.['measure-observation'] ?? '—') : '—' }}</td>
|
||||
<td>{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</details>
|
||||
} @else {
|
||||
<p class="muted">Escala: 0 a {{ routeMax() }} días. Las marcas indican el primer y tercer cuartil.</p>
|
||||
<table class="distribution route-table" aria-label="Tiempos de la ruta del tamizaje">
|
||||
<thead><tr><th>Etapa</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead>
|
||||
<tbody>
|
||||
@for (row of routeRows(); track row.label) {
|
||||
<tr><th scope="row">{{ row.label }}
|
||||
@if (row.reading?.score !== undefined) {
|
||||
<span class="bar-track duration-track" aria-hidden="true">
|
||||
<span class="bar" [style.width.%]="routeMax() ? 100 * row.reading!.score! / routeMax() : 0"></span>
|
||||
@if (row.reading!.low !== undefined && row.reading!.high !== undefined) {
|
||||
<span class="quartile" [style.left.%]="routeMax() ? 100 * row.reading!.low! / routeMax() : 0"></span>
|
||||
<span class="quartile" [style.left.%]="routeMax() ? 100 * row.reading!.high! / routeMax() : 0"></span>
|
||||
}
|
||||
</span>
|
||||
}
|
||||
</th><td>{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}</td>
|
||||
<td>{{ row.reading?.populations?.['measure-observation'] ?? '—' }}</td>
|
||||
<td>{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
|
||||
<h2>Indicadores clínicos</h2>
|
||||
@if (domain() === 'cacu') {
|
||||
<mat-card appearance="outlined" class="results-card">
|
||||
<mat-card-header><mat-card-title>Resultados de citología, VPH y biopsia</mat-card-title></mat-card-header>
|
||||
<mat-card-content class="results-grid">
|
||||
<section aria-labelledby="cytology-title">
|
||||
<h3 id="cytology-title">Distribución de resultados citológicos</h3>
|
||||
@if (reports.isLoading()) {
|
||||
<p class="muted">Calculando…</p>
|
||||
} @else if (cytology(); as distribution) {
|
||||
<p class="muted">{{ distribution.total }} pacientes con resultado elegible · {{ distribution.outside }} fuera de la distribución</p>
|
||||
<p class="muted">Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.</p>
|
||||
<p class="muted">Escala de las barras: 0 a {{ distribution.max }} pacientes.</p>
|
||||
<table class="distribution" aria-label="Distribución de resultados citológicos">
|
||||
<thead><tr><th>Categoría</th><th>Pacientes</th><th>%</th></tr></thead>
|
||||
<tbody>
|
||||
@for (row of distribution.rows; track row.label) {
|
||||
<tr>
|
||||
<th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="distribution.max ? 100 * row.count / distribution.max : 0" [style.background]="row.color"></span></span></th>
|
||||
<td>{{ row.count }}</td>
|
||||
<td>{{ distribution.total ? (100 * row.count / distribution.total).toFixed(1) + ' %' : '—' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@if (!distribution.total) { <p class="muted">Sin resultados elegibles en el periodo.</p> }
|
||||
} @else {
|
||||
<p class="muted">{{ hasCytologyMeasure() ? 'Distribución no disponible para este periodo.' : 'Medida no publicada por el servidor.' }}</p>
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="hpv-title">
|
||||
<h3 id="hpv-title">Resultados de VPH por genotipo</h3>
|
||||
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
|
||||
@else if (hpv(); as d) {
|
||||
<p class="muted">{{ d.total }} reportes VPH elegibles · periodo por fecha de toma. {{ d.outside }} fuera de las categorías mostradas.</p>
|
||||
<p class="muted">Escala de las barras: 0 a {{ d.max }} reportes. El contrato actual no representa resultados indeterminados.</p>
|
||||
<table class="distribution" aria-label="Resultados de VPH por genotipo">
|
||||
<thead><tr><th>Categoría</th><th>Reportes</th><th>%</th></tr></thead>
|
||||
<tbody>
|
||||
@for (row of d.rows; track row.label) {
|
||||
@if (row.label === 'No clasificable o inconsistente') { <tr><th scope="row">Indeterminado</th><td colspan="2">No disponible en el contrato actual</td></tr> }
|
||||
<tr><th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="d.max ? 100 * row.count / d.max : 0" [style.background]="row.color"></span></span></th>
|
||||
<td>{{ row.count }}</td><td>{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@if (!d.total) { <p class="muted">Sin reportes elegibles en el periodo.</p> }
|
||||
} @else { <p class="muted">{{ hasHpvMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución no publicada por el servidor.' }}</p> }
|
||||
</section>
|
||||
<section class="biopsy" aria-labelledby="biopsy-title">
|
||||
<h3 id="biopsy-title">Resultado de la biopsia</h3>
|
||||
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
|
||||
@else if (biopsy(); as d) {
|
||||
<p class="muted">{{ d.total }} reportes con histología clasificable · periodo por fecha de reporte.</p>
|
||||
<p class="muted">{{ d.noData }} reportes sin grado · {{ d.outside - d.noData }} con grado no clasificable. Las órdenes sin reporte no están incluidas.</p>
|
||||
<p class="muted">Escala de las barras: 0 a {{ d.max }} reportes.</p>
|
||||
<table class="distribution" aria-label="Resultados de biopsia cervical">
|
||||
<thead><tr><th>Categoría</th><th>Reportes</th><th>%</th></tr></thead>
|
||||
<tbody>
|
||||
@for (row of d.rows; track row.label; let i = $index) {
|
||||
@if (i === 0) { <tr class="group"><th scope="rowgroup" colspan="3">Menor que LIEAG · {{ d.rows[0].count + d.rows[1].count }}</th></tr> }
|
||||
@if (i === 2) { <tr class="group"><th scope="rowgroup" colspan="3">LIEAG o más · {{ d.rows[2].count + d.rows[3].count + d.rows[4].count }}</th></tr> }
|
||||
<tr><th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="d.max ? 100 * row.count / d.max : 0" [style.background]="row.color"></span></span></th>
|
||||
<td>{{ row.count }}</td><td>{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@if (!d.total) { <p class="muted">Sin reportes con grado clasificable en el periodo.</p> }
|
||||
} @else { <p class="muted">{{ hasBiopsyMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución general no publicada por el servidor.' }}</p> }
|
||||
</section>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<div class="confirmation-cards">
|
||||
<mat-card appearance="outlined"><mat-card-header><mat-card-title>Tasa de confirmación histopatológica de referencia a colposcopia</mat-card-title></mat-card-header>
|
||||
<mat-card-content><p>No disponible: no se identifican las referencias emitidas a colposcopia. Las colposcopias inferidas no acreditan ese denominador.</p></mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card appearance="outlined"><mat-card-header><mat-card-title>Tasa de confirmación histopatológica de referencia a biopsia</mat-card-title></mat-card-header>
|
||||
<mat-card-content>
|
||||
<p>La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones.</p>
|
||||
<p class="muted">Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud.</p>
|
||||
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
|
||||
@else if (!requestsMeasure()) { <p>No disponible: medida no publicada por el servidor.</p> }
|
||||
@else if (requests()?.error) { <p role="alert">Error al consultar las solicitudes de biopsia.</p> }
|
||||
@else if (requests(); as r) {
|
||||
@if (validRequests()) {
|
||||
@if (r.populations['initial-population']; as total) {
|
||||
<p>Denominador: {{ total }} solicitudes registradas (no pacientes).</p>
|
||||
<p>LIEAG o más: {{ category(r, 'high_grade') }} / {{ total }} · {{ (100 * category(r, 'high_grade') / total).toFixed(1) }} %</p>
|
||||
<p>Menor que LIEAG: {{ category(r, 'below_high_grade') }} / {{ total }} · {{ (100 * category(r, 'below_high_grade') / total).toFixed(1) }} %</p>
|
||||
<p class="muted">Pendientes: {{ category(r, 'pending') }} · Sin grado: {{ category(r, 'no_grade') }} · No clasificables: {{ category(r, 'unclassified') }} · Fechas inconsistentes: {{ category(r, 'inconsistent') }} · Registros fusionados ambiguos: {{ category(r, 'ambiguous') }}.</p>
|
||||
} @else { <p>Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).</p> }
|
||||
} @else { <p role="alert">Los datos de solicitudes recibidos están incompletos o son inconsistentes.</p> }
|
||||
} @else { <p>No disponible para este periodo.</p> }
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
<div class="clinical">
|
||||
@for (m of clinical(); track m.id) {
|
||||
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
|
||||
<mat-card-header>
|
||||
<mat-card-title>{{ measureTitle(m) }}</mat-card-title>
|
||||
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
|
||||
@if (ppvNote(m); as note) { <mat-card-subtitle class="ppv-note">{{ note }}</mat-card-subtitle> }
|
||||
@if (domain() === 'cacu' && m.name === 'CACU_EU7') { <mat-card-subtitle>El tamizaje inicial o subsecuente es el que declara el formulario o se deduce de la ruta; «Sin dato» si no consta.</mat-card-subtitle> }
|
||||
@if (domain() === 'cacu' && m.name === 'CACU_CONFIRMACION_CITOLOGIA') { <mat-card-subtitle>Pacientes con citología ASC-H, LIEAG o carcinoma in situ; incluye casos sin biopsia.</mat-card-subtitle> }
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
|
||||
<h3 class="figure-title">{{ f.title }}</h3>
|
||||
<app-plot [figure]="f.figure" [height]="260" />
|
||||
} @empty {
|
||||
<p class="muted">Sin datos en el periodo.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -61,14 +61,6 @@ h2 {
|
||||
font-size: 2rem;
|
||||
font-weight: 500;
|
||||
margin: var(--space-2) 0;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.kpi-qualifier {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.kpi-detail {
|
||||
@@ -86,11 +78,46 @@ h2 {
|
||||
gap: var(--space-3);
|
||||
justify-content: space-between;
|
||||
}
|
||||
.route-toggle { flex-wrap: wrap; max-width: 100%; }
|
||||
.route-values summary { color: var(--color-text-secondary); cursor: pointer; padding: var(--space-2) 0; }
|
||||
.route-values summary:focus-visible { outline: 2px solid var(--color-action); outline-offset: 2px; }
|
||||
|
||||
.route-table td { font-variant-numeric: tabular-nums; }
|
||||
.route-table th:first-child { width: 70%; }
|
||||
.duration-track { position: relative; }
|
||||
.duration-track .bar { background: #42a77e; }
|
||||
.quartile { position: absolute; top: -3px; width: 2px; height: 14px; background: #17324d; }
|
||||
.confirmation-cards { display: grid; grid-template-columns: 1fr; gap: var(--space-4); margin-bottom: var(--space-4); }
|
||||
.confirmation-cards { align-items: start; }
|
||||
.confirmation-cards p { margin: var(--space-2) 0; }
|
||||
@media (min-width: 850px) { .confirmation-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
|
||||
.clinical {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
grid-template-columns: 1fr;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.results-card { margin-bottom: var(--space-4); }
|
||||
.results-grid { display: grid; gap: var(--space-4); grid-template-columns: 1fr; }
|
||||
.results-grid section { min-width: 0; }
|
||||
.results-grid h3 { font-size: 1rem; font-weight: 500; margin: var(--space-3) 0; }
|
||||
.results-grid p { font-size: 13px; margin: var(--space-2) 0; }
|
||||
.distribution { border-collapse: collapse; width: 100%; font-size: 13px; }
|
||||
.distribution th { font-weight: 500; text-align: left; }
|
||||
.distribution td, .distribution thead th:not(:first-child) { text-align: right; white-space: nowrap; padding-left: 12px; }
|
||||
.distribution tbody th { padding: 5px 0; }
|
||||
.distribution .group th { background: #edf2f4; padding: 6px 8px; font-weight: 600; }
|
||||
.bar-track { display: block; height: 8px; background: #eef1f3; margin-top: 3px; }
|
||||
.bar { display: block; height: 100%; }
|
||||
.results-grid .distribution tbody th:has(.distribution-label) { display: flex; align-items: center; gap: 10px; }
|
||||
.results-grid .distribution-label { flex: 0 1 45%; min-width: 0; }
|
||||
.results-grid .bar-track { flex: 1; min-width: 40px; height: 16px; margin: 0; }
|
||||
.results-grid .distribution td { padding-left: 8px; }
|
||||
@media (min-width: 850px) {
|
||||
.results-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.biopsy { grid-column: 1 / -1; }
|
||||
}
|
||||
|
||||
@media (min-width: 1304px) {
|
||||
@@ -105,203 +132,3 @@ h2 {
|
||||
font-weight: 500;
|
||||
margin: var(--space-3) 0 0;
|
||||
}
|
||||
|
||||
/* The old app's page: white sections with a title, cards inside. */
|
||||
.card.opportunity,
|
||||
.card.clinical-page {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 24px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.section-head {
|
||||
align-items: baseline;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
.period {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
margin: 0 0 20px;
|
||||
}
|
||||
|
||||
h3.kpi-title {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
min-height: 2.6em;
|
||||
}
|
||||
|
||||
.kpi-detail {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
h3.route-title {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
margin: 24px 0 8px;
|
||||
}
|
||||
|
||||
.figure-card {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
h2.figure-card-title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.figure-row {
|
||||
display: grid;
|
||||
gap: 24px;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
@media (min-width: 1100px) {
|
||||
.figure-row {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.figure h3 {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.state {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.filters {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
h2.filters-title {
|
||||
flex-basis: 100%;
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h3.boxes-title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
margin: 24px 0 12px;
|
||||
}
|
||||
|
||||
.box-grid {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
@media (min-width: 1000px) {
|
||||
.box-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
h2.box-title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
margin: 0 0 4px;
|
||||
}
|
||||
|
||||
h2.box-subtitle {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.empty-figure {
|
||||
align-items: center;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
color: var(--color-text-secondary);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.kpi-value.pending {
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.figure h3.light {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.kpi.closing {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.summary {
|
||||
margin-bottom: 24px;
|
||||
|
||||
p {
|
||||
font-size: 20px;
|
||||
line-height: 2.1;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
p.state {
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
mark {
|
||||
background: #f1f5df;
|
||||
border: 1px solid #d8e3a8;
|
||||
border-radius: 4px;
|
||||
font-weight: 700;
|
||||
padding: 1px 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.grid-figures {
|
||||
display: grid;
|
||||
gap: 24px;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
@media (min-width: 1100px) {
|
||||
.grid-figures {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1000px) {
|
||||
.box-grid.standalone {
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.load-error {
|
||||
align-items: center;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
@@ -9,19 +8,7 @@ import type { Measure, MeasureReport } from 'fhir/r4';
|
||||
import { Fhir, resources } from '../fhir';
|
||||
import { Figure, Plot } from '../plot';
|
||||
import { LAYOUTS } from './layout';
|
||||
import {
|
||||
ageShare,
|
||||
ageStack,
|
||||
boxFigure,
|
||||
countBars,
|
||||
fill,
|
||||
nestedDonut,
|
||||
rateDots,
|
||||
routeFigure,
|
||||
scenarioBars,
|
||||
shareDonut,
|
||||
} from './figures';
|
||||
import { FigureSpec, Kpi, PAGES, Section } from './pages';
|
||||
import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results';
|
||||
import {
|
||||
detail,
|
||||
donut,
|
||||
@@ -35,18 +22,17 @@ import {
|
||||
Reading,
|
||||
scoring,
|
||||
STRATA,
|
||||
PPV_NOTES,
|
||||
measureTitle,
|
||||
strataBars,
|
||||
} from './measures';
|
||||
import { Loading } from '../loading';
|
||||
|
||||
/** The period's indicators: the timeliness KPIs, the screening route, and a card per
|
||||
* clinical measure with its figures. */
|
||||
@Component({
|
||||
selector: 'app-tab-indicadores',
|
||||
imports: [
|
||||
Loading,
|
||||
FormsModule,
|
||||
NgTemplateOutlet,
|
||||
MatButtonModule,
|
||||
MatButtonToggleModule,
|
||||
MatCardModule,
|
||||
@@ -66,14 +52,11 @@ export class TabIndicadores {
|
||||
protected readonly chosen = signal<string | undefined>(undefined);
|
||||
/** The period the figures show (set by Aplicar). */
|
||||
protected readonly applied = signal<string | undefined>(undefined);
|
||||
protected readonly routeView = signal<'sample' | 'step'>('sample');
|
||||
protected readonly routeView = signal<'sample' | 'step' | 'icd10'>('sample');
|
||||
|
||||
protected readonly layout = computed(
|
||||
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
|
||||
);
|
||||
protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
|
||||
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */
|
||||
protected readonly page = computed(() => PAGES[this.domain()]);
|
||||
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
|
||||
protected readonly kpis = computed(() =>
|
||||
this.layout()
|
||||
@@ -84,6 +67,7 @@ export class TabIndicadores {
|
||||
const placed = new Set([
|
||||
...this.layout().kpis,
|
||||
...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]),
|
||||
...(this.domain() === 'cacu' ? ['CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS', 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', 'CACU_TIEMPO_DIAGNOSTICO_CIE10'] : []),
|
||||
]);
|
||||
return this.measures().filter((m) => !placed.has(m.name!));
|
||||
});
|
||||
@@ -92,7 +76,7 @@ export class TabIndicadores {
|
||||
private readonly latest = resource({
|
||||
params: () => ({
|
||||
domain: this.domain(),
|
||||
anchor: this.byName().get(this.page()?.anchor ?? this.layout().anchor) ?? this.measures()[0],
|
||||
anchor: this.byName().get(this.layout().anchor) ?? this.measures()[0],
|
||||
all: this.options(),
|
||||
}),
|
||||
loader: async ({ params }) => {
|
||||
@@ -114,23 +98,25 @@ export class TabIndicadores {
|
||||
if (!params.period) return new Map<string, Reading | undefined>();
|
||||
const found = await Promise.all(
|
||||
params.measures.map(async (m) => {
|
||||
const page = await this.fhir.search(params.domain, 'MeasureReport', {
|
||||
measure: m.id!,
|
||||
'reporting-period': params.period,
|
||||
});
|
||||
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
|
||||
try {
|
||||
const page = await this.fhir.search(params.domain, 'MeasureReport', {
|
||||
measure: m.id!,
|
||||
'reporting-period': params.period,
|
||||
});
|
||||
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
|
||||
} catch (error) {
|
||||
if (params.domain === 'cacu' && m.name === 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION')
|
||||
return [m.name, { populations: {}, strata: {}, error: true } as Reading] as const;
|
||||
if (params.domain === 'cacu' && ['CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS', 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', 'CACU_TIEMPO_DIAGNOSTICO_CIE10'].includes(m.name!))
|
||||
return [m.name!, undefined] as const;
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return new Map(found);
|
||||
},
|
||||
});
|
||||
|
||||
/** The period's readings; none while they load or when reading them failed (an errored
|
||||
* resource throws on `value()`). */
|
||||
protected loaded(): Map<string, Reading | undefined> | undefined {
|
||||
return this.reports.hasValue() ? this.reports.value() : undefined;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const latest = this.latest.value();
|
||||
@@ -144,7 +130,7 @@ export class TabIndicadores {
|
||||
protected readonly label = periodLabel;
|
||||
protected readonly strataNames = STRATA;
|
||||
protected r(m: Measure): Reading | undefined {
|
||||
return this.loaded()?.get(m.name!);
|
||||
return this.reports.value()?.get(m.name!);
|
||||
}
|
||||
protected score(m: Measure): string {
|
||||
return formatScore(m, this.r(m));
|
||||
@@ -167,24 +153,95 @@ export class TabIndicadores {
|
||||
}),
|
||||
);
|
||||
});
|
||||
protected readonly routeRows = computed(() => {
|
||||
const view = this.routeView();
|
||||
return this.layout().route.map((s) => {
|
||||
const m = this.byName().get(view === 'sample' ? s.fromSample : s.fromStep);
|
||||
return { label: view === 'sample' ? s.label : s.step, reading: m && this.r(m) };
|
||||
});
|
||||
});
|
||||
protected readonly routeMax = computed(() => Math.max(0, ...this.routeRows().map(({reading}) =>
|
||||
Math.max(reading?.score ?? 0, reading?.high ?? 0))));
|
||||
/** Illustrative cascade of the published step medians; missing steps do not advance the offset. */
|
||||
protected readonly stepRoute = computed<Figure>(() => {
|
||||
const rows = this.routeRows().filter(row => row.reading?.score !== undefined);
|
||||
let offset = 0;
|
||||
const bars = rows.map((row, index) => {
|
||||
const score = row.reading!.score!;
|
||||
const base = offset;
|
||||
offset += score;
|
||||
return { label: row.label, count: row.reading!.populations['measure-observation'] ?? 0, score, base,
|
||||
color: index === 0 ? '#C9CDD2' : '#A8C243' };
|
||||
});
|
||||
const max = Math.max(1, offset);
|
||||
return {
|
||||
data: [{ type: 'bar', orientation: 'h', y: bars.map(row => `${row.label}<br>n = ${row.count}`),
|
||||
x: bars.map(row => row.score), base: bars.map(row => row.base),
|
||||
marker: { color: bars.map(row => row.color) }, text: bars.map(row => `+${row.score} d`),
|
||||
textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' },
|
||||
cliponaxis: false, hovertemplate: '%{y}<br>Mediana del tramo: %{x} días<extra></extra>' }],
|
||||
layout: { autosize: true, showlegend: false, bargap: 0.48,
|
||||
height: Math.max(210, bars.length * 76 + 94), margin: { t: 12, l: 8, r: 28, b: 52 },
|
||||
xaxis: { title: { text: 'Días' }, range: [0, max * 1.12], nticks: 5, fixedrange: true, zeroline: false },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
|
||||
};
|
||||
});
|
||||
protected readonly stepRouteHeight = computed(() => Math.max(210,
|
||||
this.routeRows().filter(row => row.reading?.score !== undefined).length * 76 + 94));
|
||||
protected readonly icd = computed(() => this.reports.value()?.get('CACU_TIEMPO_DIAGNOSTICO_CIE10'));
|
||||
protected readonly icdRows = computed(() => {
|
||||
const r = this.icd();
|
||||
return Object.entries(r?.stratumScores?.['diagnosis_code'] ?? {}).map(([label, score]) => ({
|
||||
label: label.replace('sin_codigo', 'Sin código disponible').replace('ambiguo', 'Diagnóstico ambiguo'),
|
||||
count: r?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0, ...score,
|
||||
}));
|
||||
});
|
||||
protected readonly icdMax = computed(() => Math.max(0, ...this.icdRows().map(r => Math.max(r.median, r.high ?? 0))));
|
||||
protected readonly requestsMeasure = computed(() => this.byName().has('CACU_BIOPSIA_SOLICITUD_CONFIRMACION'));
|
||||
protected readonly requests = computed(() => this.reports.value()?.get('CACU_BIOPSIA_SOLICITUD_CONFIRMACION'));
|
||||
protected readonly validRequests = computed(() => {
|
||||
const r = this.requests();
|
||||
const total = r?.populations['initial-population'];
|
||||
const cells = r?.strata['category'];
|
||||
if (!r || r.error || total === undefined || !cells) return false;
|
||||
const counts = Object.values(cells).map((cell) => cell['initial-population']);
|
||||
return Number.isInteger(total) && total >= 0 && counts.every((n) => Number.isInteger(n) && n >= 0)
|
||||
&& counts.reduce((sum, n) => sum + n, 0) === total;
|
||||
});
|
||||
protected category(r: Reading, key: string): number {
|
||||
return r.strata['category']?.[key]?.['initial-population'] ?? 0;
|
||||
}
|
||||
|
||||
/** Each clinical card's figures, built once per loaded period. */
|
||||
protected readonly figureSets = computed(
|
||||
() =>
|
||||
new Map(this.clinical().map((m) => [m.name!, this.build(m, this.loaded()?.get(m.name!))])),
|
||||
new Map(
|
||||
this.clinical().map((m) => [m.name!, this.build(m, this.reports.value()?.get(m.name!))]),
|
||||
),
|
||||
);
|
||||
|
||||
protected readonly cytology = computed(() =>
|
||||
cytologyDistribution(this.reports.value()?.get('CACU_EU7')),
|
||||
);
|
||||
protected readonly hasCytologyMeasure = computed(() => this.byName().has('CACU_EU7'));
|
||||
protected readonly hpv = computed(() => hpvDistribution(this.reports.value()?.get('CACU_VPH_GENOTIPO')));
|
||||
protected readonly biopsy = computed(() => biopsyDistribution(this.reports.value()?.get('CACU_BIOPSIA_RESULTADOS')));
|
||||
protected readonly hasHpvMeasure = computed(() => this.byName().has('CACU_VPH_GENOTIPO'));
|
||||
protected readonly hasBiopsyMeasure = computed(() => this.byName().has('CACU_BIOPSIA_RESULTADOS'));
|
||||
|
||||
/** A clinical card's figures: the overall split, then one per stratum. */
|
||||
private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] {
|
||||
if (!r || !(r.populations['initial-population'] ?? 0)) return [];
|
||||
const strata = Object.keys(r.strata).filter(
|
||||
(s) => s !== 'category' && !s.includes('-') && Object.keys(r.strata[s]).length,
|
||||
(s) => s !== 'category' && Object.keys(r.strata[s]).length,
|
||||
);
|
||||
const kind = scoring(m);
|
||||
if (kind === 'continuous-variable')
|
||||
return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }];
|
||||
return [
|
||||
{ title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) },
|
||||
...(this.domain() === 'cacu' && m.name === 'CACU_EU7' && this.cytology()
|
||||
? []
|
||||
: [{ title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) }]),
|
||||
...strata.map((s) => ({
|
||||
title: `Por ${STRATA[s]?.toLowerCase() ?? s}`,
|
||||
figure: strataBars(m, r, s),
|
||||
@@ -192,102 +249,8 @@ export class TabIndicadores {
|
||||
];
|
||||
}
|
||||
protected readonly name = name;
|
||||
|
||||
/** A measure's reading in the applied period, by code. */
|
||||
protected rd(code: string): Reading | undefined {
|
||||
return this.loaded()?.get(code);
|
||||
}
|
||||
protected kpi(code: string): Measure | undefined {
|
||||
return this.byName().get(code);
|
||||
}
|
||||
/** A card's value and note, from its templates (a card with no measure: its words). */
|
||||
/** "27 días (mediana)" as the value and its qualifier, shown smaller beneath it. */
|
||||
protected kpiParts(text: string): [string, string] {
|
||||
const found = /^(.*?)\s*(\([^)]*\))$/.exec(text);
|
||||
return found ? [found[1], found[2]] : [text, ''];
|
||||
}
|
||||
|
||||
protected kpiValue(k: Kpi): string {
|
||||
if (!k.measure) return k.value ?? '';
|
||||
const r = this.rd(k.measure);
|
||||
return r && r.score !== undefined && k.value ? fill(k.value, r) : '';
|
||||
}
|
||||
protected kpiNote(k: Kpi): string {
|
||||
if (!k.measure) return k.note ?? '';
|
||||
const r = this.rd(k.measure);
|
||||
if (!r || r.score === undefined) return 'Sin valor disponible';
|
||||
return k.note ? fill(k.note, r) : '';
|
||||
}
|
||||
/** A figure's title, with the applied period in it. */
|
||||
protected titled(title: string): string {
|
||||
return title.replace('{p}', this.applied() ?? '');
|
||||
}
|
||||
/** A duration's box, or nothing to draw. */
|
||||
protected boxOf(measure: string | undefined): Figure | undefined {
|
||||
const r = measure ? this.rd(measure) : undefined;
|
||||
return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined;
|
||||
}
|
||||
/** TEA's summary of the period: its numbers from the measures (none: no summary). */
|
||||
protected readonly teaSummary = computed(() => {
|
||||
const rd = (c: string) => this.loaded()?.get(c);
|
||||
const status = rd('M28_CASOS_POR_ESTADO');
|
||||
if (!status) return undefined;
|
||||
const n = (r: Reading | undefined, pop: string) => r?.populations[pop] ?? 0;
|
||||
const cat = (r: Reading | undefined, c: string) =>
|
||||
r?.strata['category']?.[c]?.['initial-population'] ?? 0;
|
||||
const days = (c: string) => {
|
||||
const v = rd(c)?.score;
|
||||
return v === undefined
|
||||
? '—'
|
||||
: `${v.toLocaleString('es-MX', { maximumFractionDigits: 1 })} días`;
|
||||
};
|
||||
const confirmed = rd('M24_CONFIRMACION_DIAGNOSTICO')?.score;
|
||||
const withEeg = rd('M21_DIAGNOSTICADOS_CON_EEG');
|
||||
return {
|
||||
evaluated: n(status, 'initial-population'),
|
||||
mchatOnly: cat(status, 'mchat_only'),
|
||||
psychology: cat(status, 'psychology'),
|
||||
neuropediatrics: cat(status, 'neuropediatrics') + cat(status, 'eeg'),
|
||||
confirmed:
|
||||
confirmed === undefined
|
||||
? '—'
|
||||
: `${(confirmed * 100).toLocaleString('es-MX', { maximumFractionDigits: 1 })}%`,
|
||||
toAdos: days('M26_DIAS_MCHAT_ADOS2'),
|
||||
toDiagnosis: days('M27_DIAS_ADOS2_DIAGNOSTICO'),
|
||||
whole: days('M25_DIAS_MCHAT_DIAGNOSTICO'),
|
||||
diagnosed: n(withEeg, 'denominator'),
|
||||
eeg: n(withEeg, 'numerator'),
|
||||
missing: n(rd('M22_DIAGNOSTICADOS_SIN_EEG'), 'numerator'),
|
||||
unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'),
|
||||
};
|
||||
});
|
||||
protected measureTitle(code: string | undefined): string {
|
||||
return (code && this.byName().get(code)?.title) || '';
|
||||
}
|
||||
/** A clinical section's route or figures, drawn from the applied period's reports. */
|
||||
protected routeOf(section: Section): Figure | undefined {
|
||||
if (section.kind !== 'route') return undefined;
|
||||
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) }));
|
||||
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined;
|
||||
}
|
||||
protected figureOf(spec: FigureSpec): Figure | undefined {
|
||||
const r = this.rd(spec.measure);
|
||||
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
|
||||
switch (spec.kind) {
|
||||
case 'donut':
|
||||
return nestedDonut(r, spec.catalog, spec.center);
|
||||
case 'share-donut':
|
||||
return shareDonut(r, spec.catalog, spec.center);
|
||||
case 'counts':
|
||||
return countBars(r, spec.catalog, spec.axis, this.applied() ?? '');
|
||||
case 'age-stack':
|
||||
return ageStack(r, spec.names);
|
||||
case 'age-share':
|
||||
return ageShare(r, spec.names[0]);
|
||||
case 'scenario-bars':
|
||||
return scenarioBars(r, spec.catalog, spec.stratum, name);
|
||||
case 'rates':
|
||||
return rateDots(r, spec);
|
||||
}
|
||||
protected readonly measureTitle = measureTitle;
|
||||
protected ppvNote(m: Measure): string | undefined {
|
||||
return PPV_NOTES[m.name ?? '']?.note;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user