Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6df008bf8a | |||
| 48e6c9f390 | |||
| f0dd3ec52f | |||
| 61aeed35ff | |||
| d8cb6420a4 | |||
| d3c04a5fcf | |||
| 3655b9857c | |||
| 3e213c4fc0 | |||
| bd897baa2d | |||
| b291885b97 | |||
| b847e04697 | |||
| e5556ebf41 | |||
| 08a1bf910e | |||
| 7e21ebbc7b | |||
| fde3ec08e1 | |||
| 3f6fa28590 | |||
| adff5bac5c | |||
| e2d1c9f277 | |||
| 0760721144 | |||
| 56d1ef2e8a | |||
| 053679c817 | |||
| ffa732df12 | |||
| 786b199203 | |||
| 5d03f333f7 | |||
| f7cc141625 | |||
| 84dcebda55 | |||
| 12b056343b | |||
| 38ece960f9 | |||
| b3e5a69783 | |||
| 8442ad5fe6 | |||
| 6732893bcc | |||
| 5ce225df5a | |||
| 8b1cbec66a | |||
| 43b5523f99 |
@@ -39,6 +39,9 @@
|
|||||||
"material-symbols/outlined.css",
|
"material-symbols/outlined.css",
|
||||||
"src/styles.scss"
|
"src/styles.scss"
|
||||||
],
|
],
|
||||||
|
"define": {
|
||||||
|
"global": "globalThis"
|
||||||
|
},
|
||||||
"allowedCommonJsDependencies": [
|
"allowedCommonJsDependencies": [
|
||||||
"plotly.js-cartesian-dist-min"
|
"plotly.js-cartesian-dist-min"
|
||||||
]
|
]
|
||||||
|
|||||||
-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)];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
+101
-633
@@ -1,8 +1,6 @@
|
|||||||
import { readFileSync } from 'node:fs';
|
import { statSync } from 'node:fs';
|
||||||
import { expect, Page, test } from '@playwright/test';
|
import { expect, Locator, 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[] {
|
function watch(page: Page): string[] {
|
||||||
const problems: string[] = [];
|
const problems: string[] = [];
|
||||||
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
|
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
|
||||||
@@ -11,7 +9,6 @@ function watch(page: Page): string[] {
|
|||||||
return problems;
|
return problems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The pages show only to someone signed in (the API itself answers everyone).
|
|
||||||
test.beforeEach(async ({ page }) => {
|
test.beforeEach(async ({ page }) => {
|
||||||
const signed = await page.request.post('/api/auth/login', {
|
const signed = await page.request.post('/api/auth/login', {
|
||||||
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
|
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
|
||||||
@@ -19,652 +16,123 @@ test.beforeEach(async ({ page }) => {
|
|||||||
expect(signed.status()).toBe(204);
|
expect(signed.status()).toBe(204);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
|
async function downloaded(page: Page, button: Locator, kind: 'pdf' | 'xlsx'): Promise<string> {
|
||||||
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
|
const [file] = await Promise.all([page.waitForEvent('download'), button.click()]);
|
||||||
await page.goto('/conectar');
|
const name = file.suggestedFilename();
|
||||||
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
|
expect(name).toMatch(new RegExp(`^tea-[a-z]+-\\d{4}-\\d{2}-\\d{2}\\.${kind}$`));
|
||||||
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
|
expect(name).not.toMatch(/N-?\d{4}/);
|
||||||
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
|
expect(statSync(await file.path()).size).toBeGreaterThan(0);
|
||||||
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
|
return name;
|
||||||
await page.getByRole('button', { name: 'Ingresar' }).click();
|
}
|
||||||
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
|
|
||||||
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
|
|
||||||
await page.getByRole('button', { name: 'Ingresar' }).click();
|
|
||||||
await expect(page).toHaveURL(/\/conectar$/);
|
|
||||||
await page.getByRole('button', { name: 'Cuenta' }).click();
|
|
||||||
await page.getByRole('menuitem', { name: 'Salir' }).click();
|
|
||||||
await expect(page).toHaveURL(/\/login/);
|
|
||||||
await page.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
|
test('tea indicators: every tab loads, and the follow-up list exports to Excel', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const problems = watch(page);
|
const problems = watch(page);
|
||||||
const report = page.waitForResponse(
|
const listed = page.waitForResponse(
|
||||||
(r) =>
|
(r) => r.url().includes('/tea/fhir/Measure') && !r.url().includes('MeasureReport'),
|
||||||
r.url().includes('MeasureReport') &&
|
|
||||||
r.url().includes('measure=cacu-eu7') &&
|
|
||||||
!r.url().includes('%2C'),
|
|
||||||
);
|
);
|
||||||
await page.goto('/indicadores/cacu');
|
await page.goto('/indicadores/tea');
|
||||||
const eu7 = await (await report).json();
|
const measures = (await (await listed).json()).entry.length;
|
||||||
const count = eu7.entry[0].resource.group[0].population.find(
|
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||||
(p: any) => p.code.coding[0].code === 'initial-population',
|
await expect(page.locator('app-tab-indicadores [data-measure]').first()).toBeVisible();
|
||||||
).count;
|
|
||||||
// the card says it as the old one did: "<n> pacientes"
|
|
||||||
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
|
|
||||||
`${count.toLocaleString('es-MX')} pacientes`,
|
|
||||||
);
|
|
||||||
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
|
|
||||||
|
|
||||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
||||||
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14);
|
await expect(page.getByText('Progresión del proceso diagnóstico')).toBeVisible();
|
||||||
|
await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
|
const rows = page.locator('app-tab-seguimiento table tbody tr');
|
||||||
|
await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/);
|
||||||
|
const name = await downloaded(
|
||||||
|
page,
|
||||||
|
page.getByRole('button', { name: 'Exportar a Excel' }),
|
||||||
|
'xlsx',
|
||||||
|
);
|
||||||
|
expect(name).toMatch(/^tea-seguimiento-/);
|
||||||
|
|
||||||
|
await page.getByRole('tab', { name: 'Análisis de riesgo' }).click();
|
||||||
|
await expect(page.locator('app-tab-riesgos app-tea-list')).toBeVisible();
|
||||||
|
await expect(page.getByText('Cargando pacientes…')).toHaveCount(0);
|
||||||
|
|
||||||
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
||||||
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14);
|
await expect(page.locator('app-tab-definiciones details')).toHaveCount(measures);
|
||||||
|
expect(problems).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
|
test('tea patient: the record and the risk page load and export to PDF', async ({ page }) => {
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
const problems = watch(page);
|
||||||
const bundle = await (await list).json();
|
|
||||||
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
|
|
||||||
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
|
|
||||||
const rows = page.locator('table.worklist tbody tr');
|
|
||||||
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 \d+, \d+ registros/)).toBeVisible();
|
|
||||||
|
|
||||||
await page.getByRole('button', { name: 'Anterior' }).click();
|
|
||||||
await rows.first().locator('a').first().click();
|
|
||||||
await expect(page.getByText('Historial médico')).toBeVisible();
|
|
||||||
await expect(page.getByText('Pruebas y resultados')).toBeVisible();
|
|
||||||
await expect(
|
|
||||||
page.locator('app-paciente table').nth(1).locator('tbody tr').first(),
|
|
||||||
).not.toContainText('Sin estudios');
|
|
||||||
|
|
||||||
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.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 page.goto('/indicadores/tea');
|
||||||
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
|
const first = page.locator('app-tab-seguimiento table tbody tr').first();
|
||||||
|
await expect(first.locator('td').first()).toHaveText(/^N-?\d{4}$/);
|
||||||
|
await first.getByRole('link', { name: 'Expediente' }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/);
|
||||||
|
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
|
||||||
|
await expect(page.locator('app-tea-section').first()).toBeVisible();
|
||||||
|
const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf');
|
||||||
|
expect(record).toMatch(/^tea-seguimiento-/);
|
||||||
|
|
||||||
|
await page.getByRole('link', { name: 'Riesgo' }).click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible();
|
||||||
|
await expect(page.locator('app-tea-section').first()).toBeVisible();
|
||||||
|
expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch(
|
||||||
|
/^tea-riesgos-/,
|
||||||
|
);
|
||||||
expect(problems).toEqual([]);
|
expect(problems).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('conectar: open the hospital pipeline, preview a source, run it to success', async ({
|
test('tea gobernanza: every section in sync mode, and the preview saved as PDF', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const problems = watch(page);
|
const problems = watch(page);
|
||||||
await page.goto('/conectar');
|
await page.goto('/gobernanza/tea');
|
||||||
await page.getByText('cacu', { exact: true }).click();
|
await page.getByLabel('Modo').selectOption('sync');
|
||||||
await expect(page.locator('vflow')).toBeVisible();
|
await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).toBeVisible();
|
||||||
// a node's caption: its kind, then its name
|
|
||||||
await page.locator('.node-caption', { hasText: 'Pacientes' }).click();
|
|
||||||
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
|
|
||||||
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
|
|
||||||
await page.getByRole('button', { name: 'Vista previa' }).click();
|
|
||||||
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
|
|
||||||
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
|
|
||||||
await page;
|
|
||||||
await page
|
|
||||||
.locator('.node-caption', { hasText: 'Traducir códigos' })
|
|
||||||
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
|
|
||||||
.click();
|
|
||||||
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
|
|
||||||
await expect
|
|
||||||
.poll(() =>
|
|
||||||
page
|
|
||||||
.locator('app-concept-map-editor input')
|
|
||||||
.evaluateAll((els) => els.map((e) => (e as HTMLInputElement).value)),
|
|
||||||
)
|
|
||||||
.toContain('LIEAG');
|
|
||||||
await page.getByRole('button', { name: 'Ejecutar' }).click();
|
|
||||||
await expect(page.getByText('SUCCESS')).toBeVisible({ timeout: 10 * 60_000 });
|
|
||||||
expect(problems).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('revision: what the hospital source holds, and a decision through the page', async ({
|
await page.getByRole('button', { name: 'Entrenar modelos' }).click();
|
||||||
page,
|
await expect(page.getByRole('heading', { name: 'Entrenar modelos', level: 3 })).toBeVisible();
|
||||||
}) => {
|
await expect(page.locator('app-governance-training formly-form')).toBeVisible();
|
||||||
const problems = watch(page);
|
|
||||||
await page.goto('/revision');
|
|
||||||
await page.getByRole('tab', { name: 'Personas' }).click();
|
|
||||||
await page.locator('mat-form-field', { hasText: 'Canalización' }).click();
|
|
||||||
await page.getByRole('option', { name: 'site', exact: true }).click();
|
|
||||||
await expect(page.getByText(/Posibles pacientes duplicadas \([1-9]/)).toBeVisible();
|
|
||||||
await page.getByRole('button', { name: 'Distintas' }).first().click();
|
|
||||||
await expect(page.getByText('Decisión registrada.')).toBeVisible();
|
|
||||||
expect(problems).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('gobernanza: a version with its reports, its curves, and promotion refused without validation', async ({
|
const monitor = page.locator('app-gobernanza > section > section app-run-monitor');
|
||||||
page,
|
await page.getByRole('button', { name: 'Analizar EEG' }).click();
|
||||||
}) => {
|
await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible();
|
||||||
const problems = watch(page);
|
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
|
||||||
await page.goto('/gobernanza/cama');
|
await page.getByRole('button', { name: 'Calcular riesgos' }).click();
|
||||||
await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
|
await expect(page.getByRole('heading', { name: 'Cálculo de riesgos' })).toBeVisible();
|
||||||
const version = page.locator('tr', { hasText: 'v1' });
|
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
|
||||||
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
|
await page.getByRole('button', { name: 'Promover candidatas' }).click();
|
||||||
await version.getByRole('button', { name: 'Ver gráficas' }).click();
|
await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible();
|
||||||
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
|
|
||||||
await version.getByRole('button', { name: 'Promover' }).click();
|
const studies = page.locator('app-eeg-studies');
|
||||||
await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
|
await expect(studies.locator('table.eegs tbody tr').first()).toContainText(/Válido|No válido/);
|
||||||
|
await studies.locator('table.eegs tbody button:enabled').first().click();
|
||||||
|
await expect(studies.getByRole('heading', { name: /^EEG .* meses$/ })).toBeVisible();
|
||||||
|
await studies.getByRole('button', { name: 'Analizar', exact: true }).click();
|
||||||
|
await expect(studies.locator('app-run-monitor').first().getByRole('status')).toHaveText(
|
||||||
|
'SUCCESS',
|
||||||
|
{ timeout: 10 * 60_000 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const preview = page.locator('app-eeg-preview');
|
||||||
|
await preview.getByLabel('EDF').setInputFiles(process.env['TEA_EDF']!);
|
||||||
|
await preview.getByLabel('ADOS-2 (PDF)').setInputFiles(process.env['TEA_ADOS2']!);
|
||||||
|
await preview.getByLabel('Fecha de nacimiento').fill(process.env['TEA_BIRTH']!);
|
||||||
|
await preview.getByRole('button', { name: 'Vista previa' }).click();
|
||||||
|
const dialog = page.getByRole('dialog', { name: 'Vista previa del estudio' });
|
||||||
|
await expect(dialog.getByText('Resultado de la vista previa')).toBeVisible({
|
||||||
|
timeout: 10 * 60_000,
|
||||||
|
});
|
||||||
|
await expect(dialog.locator('dt').first()).toHaveText(/^[AB]-\d+ \S/);
|
||||||
|
expect(
|
||||||
|
await downloaded(page, dialog.getByRole('button', { name: 'Guardar como PDF' }), 'pdf'),
|
||||||
|
).toMatch(/^tea-gobernanza-/);
|
||||||
|
await dialog.getByRole('button', { name: 'Cerrar' }).click();
|
||||||
|
|
||||||
|
const bundles = page.locator('app-governance-bundles');
|
||||||
|
await bundles.getByLabel('Versiones').selectOption('all');
|
||||||
|
await bundles.getByRole('button', { name: 'Exportar bundle' }).click();
|
||||||
|
await expect(bundles.getByRole('alert')).toContainText('nothing to export');
|
||||||
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
|
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
|
|
||||||
const problems = watch(page);
|
|
||||||
await page.goto('/conectar');
|
|
||||||
await page.getByLabel('Nueva canalización').fill('asistente');
|
|
||||||
await page.getByLabel('Nueva canalización').press('Enter');
|
|
||||||
await page.getByRole('button', { name: 'Fuente de datos' }).click();
|
|
||||||
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
|
|
||||||
await page.locator('[data-type="sqlserver"]').click();
|
|
||||||
await page.locator('[data-field="host"]').fill(site.hostname);
|
|
||||||
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
|
|
||||||
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
|
|
||||||
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
|
|
||||||
await page.getByRole('button', { name: 'Probar conexión' }).click();
|
|
||||||
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
|
|
||||||
await page.locator('mat-select[data-field="table"]').click();
|
|
||||||
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
|
|
||||||
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
|
|
||||||
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
|
|
||||||
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
|
|
||||||
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
|
|
||||||
// A wrong password says so in words, not a stack trace.
|
|
||||||
await page.getByRole('button', { name: 'Editar conexión' }).click();
|
|
||||||
await page.locator('[data-field="password"]').fill('not-it');
|
|
||||||
await page.getByRole('button', { name: 'Probar conexión' }).click();
|
|
||||||
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
|
|
||||||
await page.getByRole('button', { name: 'Cancelar' }).click();
|
|
||||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
|
||||||
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
|
|
||||||
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
|
|
||||||
expect(problems).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
|
|
||||||
* opportunity section on, in order, and the kind of each plot (its traces' types). */
|
|
||||||
function captured(domain: string) {
|
|
||||||
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
|
|
||||||
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
|
|
||||||
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
|
|
||||||
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
|
|
||||||
const old = items
|
|
||||||
.slice(from)
|
|
||||||
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
|
|
||||||
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
|
|
||||||
return domain === 'cacu' ? rearranged(old) : old;
|
|
||||||
}
|
|
||||||
/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the
|
|
||||||
* opportunity section, under its cards, and the cytology distribution is a table in the joint
|
|
||||||
* results card (its nested donut is not drawn any more). Nothing else of the old page moves. */
|
|
||||||
function rearranged(old: any[]) {
|
|
||||||
const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje');
|
|
||||||
const moved = old.splice(route, 2); // its heading and its plot
|
|
||||||
old.splice(
|
|
||||||
old.findIndex((i) => i.text === 'Indicadores clínicos'),
|
|
||||||
0,
|
|
||||||
moved[0],
|
|
||||||
moved[1],
|
|
||||||
);
|
|
||||||
// the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the
|
|
||||||
// cytology section, under another title) are not headings of this page any more
|
|
||||||
return old.filter(
|
|
||||||
(i) =>
|
|
||||||
!/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test(
|
|
||||||
i.text ?? '',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
/** Sections this platform adds to an old page, by domain, in the order they appear. The old
|
|
||||||
* headings still have to appear, in their order; nothing else may appear (a figure's own
|
|
||||||
* `h3.figure-title` inside a measure's card is the card's, not a section). */
|
|
||||||
const ADDED: Record<string, string[]> = {
|
|
||||||
cacu: [
|
|
||||||
'Resultados de citología, VPH y biopsia',
|
|
||||||
'Resultados de VPH por genotipo',
|
|
||||||
'Resultados de biopsia cervical',
|
|
||||||
'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
|
|
||||||
'VPP tras colposcopía registrada',
|
|
||||||
],
|
|
||||||
};
|
|
||||||
/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */
|
|
||||||
function oldThenAdded(actual: string[], old: string[], added: string[]) {
|
|
||||||
const extra: string[] = [];
|
|
||||||
let found = 0;
|
|
||||||
for (const heading of actual) {
|
|
||||||
if (found < old.length && heading === old[found]) found++;
|
|
||||||
else extra.push(heading);
|
|
||||||
}
|
|
||||||
return { allOldInOrder: found === old.length, extra, added };
|
|
||||||
}
|
|
||||||
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
|
|
||||||
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
|
|
||||||
|
|
||||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
|
||||||
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
const old = captured(domain);
|
|
||||||
await page.goto(`/indicadores/${domain}`);
|
|
||||||
const tab = page.locator('app-tab-indicadores');
|
|
||||||
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
|
|
||||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
|
||||||
// textContent: a heading inside a collapsed section (CaCu's original confirmation measure)
|
|
||||||
// is still a heading of the page, though the browser gives it no rendered text.
|
|
||||||
const headings = await tab
|
|
||||||
.locator('h2, h3:not(.figure-title)')
|
|
||||||
.evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()));
|
|
||||||
const from = headings.indexOf('Indicadores de oportunidad');
|
|
||||||
const seen = oldThenAdded(
|
|
||||||
headings.slice(from).map(period),
|
|
||||||
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
|
|
||||||
ADDED[domain] ?? [],
|
|
||||||
);
|
|
||||||
expect(seen.allOldInOrder).toBe(true);
|
|
||||||
expect(seen.extra).toEqual(seen.added);
|
|
||||||
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
|
|
||||||
const drawn = await tab
|
|
||||||
.locator('.js-plotly-plot')
|
|
||||||
.evaluateAll((els) =>
|
|
||||||
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
|
|
||||||
);
|
|
||||||
const kinds = new Set(
|
|
||||||
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
|
|
||||||
);
|
|
||||||
for (const types of drawn) expect(kinds).toContain(kindOf(types));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
|
||||||
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
const tabs = JSON.parse(
|
|
||||||
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
|
|
||||||
).tabs;
|
|
||||||
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
|
|
||||||
['h2', 'h3', 'plot'].includes(i.kind),
|
|
||||||
);
|
|
||||||
await page.goto(`/indicadores/${domain}`);
|
|
||||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
|
||||||
const tab = page.locator('app-tab-trazabilidad');
|
|
||||||
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
|
|
||||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
|
||||||
const headings = await tab
|
|
||||||
.locator('h2, h3')
|
|
||||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
|
||||||
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
|
|
||||||
const drawn = await tab
|
|
||||||
.locator('.js-plotly-plot')
|
|
||||||
.evaluateAll((els) =>
|
|
||||||
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
|
|
||||||
);
|
|
||||||
const kinds = new Set(
|
|
||||||
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
|
|
||||||
);
|
|
||||||
for (const types of drawn) expect(kinds).toContain(kindOf(types));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
|
||||||
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
const tabs = JSON.parse(
|
|
||||||
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
|
|
||||||
).tabs;
|
|
||||||
const old = (tabs['Datos y definiciones'] as any[])
|
|
||||||
.filter((i) => ['h2', 'h3'].includes(i.kind))
|
|
||||||
.map((i) => i.text);
|
|
||||||
await page.goto(`/indicadores/${domain}`);
|
|
||||||
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
|
||||||
const tab = page.locator('app-tab-definiciones');
|
|
||||||
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
|
|
||||||
const headings = await tab
|
|
||||||
.locator('h2, h3')
|
|
||||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
|
||||||
expect(headings).toEqual(old);
|
|
||||||
await tab.locator('summary').first().click();
|
|
||||||
await expect(
|
|
||||||
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
|
|
||||||
).toBeVisible();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
const asked: string[] = [];
|
|
||||||
page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url()));
|
|
||||||
await page.goto('/indicadores/cacu');
|
|
||||||
const tab = page.locator('app-tab-indicadores');
|
|
||||||
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
|
|
||||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
|
||||||
|
|
||||||
// cumulative (the default), step by step with its warning and quartiles, and by ICD-10
|
|
||||||
// the route's times are in the opportunity section, after its cards and before the clinical ones
|
|
||||||
const opportunity = tab.locator('section.opportunity');
|
|
||||||
await expect(opportunity.locator('.route-card')).toBeVisible();
|
|
||||||
await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0);
|
|
||||||
expect(
|
|
||||||
await opportunity.evaluate((el) => {
|
|
||||||
const kpis = el.querySelector('.kpis')!;
|
|
||||||
const card = el.querySelector('.route-card')!;
|
|
||||||
return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING);
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible();
|
|
||||||
await tab.getByRole('radio', { name: 'Por pasos' }).click();
|
|
||||||
// by steps: independent bars from zero in a table, every step kept, and the medians not added
|
|
||||||
const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' });
|
|
||||||
await expect(steps).toBeVisible();
|
|
||||||
await expect(steps.locator('tbody tr')).toHaveCount(4);
|
|
||||||
await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible();
|
|
||||||
await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0);
|
|
||||||
await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click();
|
|
||||||
await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible();
|
|
||||||
await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click();
|
|
||||||
await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible();
|
|
||||||
await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible();
|
|
||||||
|
|
||||||
// the sections of the new measures: each one in the place of its subject
|
|
||||||
for (const measure of [
|
|
||||||
'CACU_VPH_GENOTIPO',
|
|
||||||
'CACU_VPH',
|
|
||||||
'CACU_BIOPSIA_RESULTADOS',
|
|
||||||
'CACU_VPP_COLPOSCOPIA',
|
|
||||||
])
|
|
||||||
await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible();
|
|
||||||
// a PPV says what it is and what it is not
|
|
||||||
await expect(
|
|
||||||
tab
|
|
||||||
.locator('[data-measure="CACU_VPP_COLPOSCOPIA"]')
|
|
||||||
.getByText('no un vínculo clínico confirmado'),
|
|
||||||
).toBeVisible();
|
|
||||||
// the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut
|
|
||||||
const joint = tab.locator('.results-card');
|
|
||||||
const [cyto, hpv, biopsy] = await Promise.all(
|
|
||||||
['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) =>
|
|
||||||
joint.locator(`section[data-measure="${m}"]`).boundingBox(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2);
|
|
||||||
expect(cyto!.x).toBeLessThan(hpv!.x);
|
|
||||||
expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1);
|
|
||||||
expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8);
|
|
||||||
await expect(
|
|
||||||
joint.getByRole('table', { name: 'Distribución de resultados citológicos' }),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(joint.getByText('Menor que LIEAG')).toBeVisible();
|
|
||||||
await expect(joint.getByText('LIEAG o más')).toBeVisible();
|
|
||||||
// three HPV categories are not listed, and the page says so only when it has such reports
|
|
||||||
const hpvRows = await joint
|
|
||||||
.locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th')
|
|
||||||
.allInnerTexts();
|
|
||||||
for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable'])
|
|
||||||
expect(hpvRows.join('|')).not.toContain(hidden);
|
|
||||||
// the cytology column reads one way at a time: the general table, or the clinical scenarios
|
|
||||||
const cytology = joint.locator('section[data-measure="CACU_EU7"]');
|
|
||||||
await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked();
|
|
||||||
await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0);
|
|
||||||
await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click();
|
|
||||||
await expect(cytology.locator('.js-plotly-plot')).toBeVisible();
|
|
||||||
await expect(cytology.getByRole('table')).toHaveCount(0);
|
|
||||||
await expect(
|
|
||||||
cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(cytology.locator('.legend li')).toHaveCount(6);
|
|
||||||
await cytology.getByRole('radio', { name: 'Distribución general' }).click();
|
|
||||||
await expect(
|
|
||||||
cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(
|
|
||||||
joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'),
|
|
||||||
).toHaveCount(0);
|
|
||||||
await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0);
|
|
||||||
// the confirmation card: one perspective at a time, each with its own PPV and its readings
|
|
||||||
const confirmation = tab.locator('.confirmation-card');
|
|
||||||
await expect(
|
|
||||||
confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible();
|
|
||||||
await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked();
|
|
||||||
for (const [perspective, measure, title] of [
|
|
||||||
['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'],
|
|
||||||
['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'],
|
|
||||||
]) {
|
|
||||||
await confirmation.getByRole('radio', { name: perspective, exact: true }).click();
|
|
||||||
await expect(confirmation.locator('app-ppv-card')).toHaveCount(1);
|
|
||||||
const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`);
|
|
||||||
await expect(ppv.getByRole('heading', { name: title })).toBeVisible();
|
|
||||||
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
|
|
||||||
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
|
|
||||||
await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked();
|
|
||||||
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
|
|
||||||
await expect(ppv.locator('.ppv-rows')).toHaveCount(0);
|
|
||||||
for (const mode of [
|
|
||||||
'Citología previa',
|
|
||||||
'VPH previo',
|
|
||||||
'Nivel de histología',
|
|
||||||
'Ronda de tamizaje',
|
|
||||||
]) {
|
|
||||||
await ppv.getByRole('radio', { name: mode, exact: true }).click();
|
|
||||||
await expect(ppv.getByRole('table', { name: mode })).toBeVisible();
|
|
||||||
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0);
|
|
||||||
await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
|
|
||||||
// the score line and the methodological note stay in view in every reading
|
|
||||||
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
|
|
||||||
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
|
|
||||||
}
|
|
||||||
await ppv.getByRole('radio', { name: 'Total' }).click();
|
|
||||||
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
|
|
||||||
}
|
|
||||||
// the biopsy requests are one more reading of the biopsy perspective, with their own heading
|
|
||||||
const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]');
|
|
||||||
await expect(
|
|
||||||
biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }),
|
|
||||||
).toBeVisible();
|
|
||||||
await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click();
|
|
||||||
await expect(
|
|
||||||
biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount(
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
await expect(biopsyPpv.locator('.measure-score')).toContainText(
|
|
||||||
'solicitudes registradas (no pacientes)',
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'),
|
|
||||||
).toBeVisible();
|
|
||||||
await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible();
|
|
||||||
await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible();
|
|
||||||
await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
|
|
||||||
await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos');
|
|
||||||
await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0);
|
|
||||||
await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click();
|
|
||||||
await expect(
|
|
||||||
biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }),
|
|
||||||
).toBeVisible();
|
|
||||||
// the original confirmation measure is not shown on this tab any more
|
|
||||||
await expect(confirmation.locator('details')).toHaveCount(0);
|
|
||||||
await expect(tab.getByText('medida original')).toHaveCount(0);
|
|
||||||
await expect(tab.getByText('Denominador: ')).toHaveCount(0);
|
|
||||||
// the tabs are short and the full explanation is in the tab's content
|
|
||||||
await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
|
|
||||||
const colposcopy = confirmation.locator('app-ppv-card');
|
|
||||||
await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click();
|
|
||||||
await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas');
|
|
||||||
await expect(colposcopy.getByRole('radio')).toHaveCount(5);
|
|
||||||
const tops = await colposcopy
|
|
||||||
.locator('mat-button-toggle')
|
|
||||||
.evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size);
|
|
||||||
expect(tops).toBe(1); // one line on desktop
|
|
||||||
// the patients by HPV result: the whole as a donut, then one breakdown at a time
|
|
||||||
const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]');
|
|
||||||
await expect(vph.locator('.measure-score')).toContainText('pacientes');
|
|
||||||
await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible();
|
|
||||||
await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked();
|
|
||||||
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
|
|
||||||
for (const mode of [
|
|
||||||
'Por grupo de edad',
|
|
||||||
'Por estatus de seguimiento',
|
|
||||||
'Por genotipo',
|
|
||||||
'Por tamizaje inicial o subsecuente',
|
|
||||||
]) {
|
|
||||||
await vph.getByRole('radio', { name: mode, exact: true }).click();
|
|
||||||
await expect(vph.getByRole('table', { name: mode })).toBeVisible();
|
|
||||||
await expect(vph.locator('.js-plotly-plot')).toHaveCount(0);
|
|
||||||
await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
|
|
||||||
await expect(vph.locator('.measure-score')).toContainText('pacientes');
|
|
||||||
}
|
|
||||||
await vph.getByRole('radio', { name: 'Total' }).click();
|
|
||||||
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
|
|
||||||
// the two HPV measures are told apart: reports against patients
|
|
||||||
await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText(
|
|
||||||
'Pacientes evaluadas por resultado de VPH',
|
|
||||||
);
|
|
||||||
await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText(
|
|
||||||
'Cuenta reportes, no pacientes',
|
|
||||||
);
|
|
||||||
expect(asked).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
const problems = watch(page);
|
|
||||||
await page.goto('/indicadores/cacu');
|
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
|
||||||
const rows = page.locator('table.worklist tbody tr:not(.stage-panel)');
|
|
||||||
await expect(rows.first().locator('a')).toBeVisible();
|
|
||||||
const total = async () =>
|
|
||||||
Number(
|
|
||||||
/(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0,
|
|
||||||
);
|
|
||||||
|
|
||||||
// her age at the cut-off, and the stages: a compact line with a chevron that opens the panel
|
|
||||||
await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible();
|
|
||||||
await expect(rows.first().locator('app-stages .node')).toHaveCount(5);
|
|
||||||
await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click();
|
|
||||||
const panel = page.locator('tr.stage-panel');
|
|
||||||
await expect(panel).toContainText('Toma de muestra');
|
|
||||||
await expect(panel).toContainText('Desde anterior');
|
|
||||||
await expect(panel.locator('.node')).toHaveCount(5);
|
|
||||||
await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click();
|
|
||||||
await expect(panel).toHaveCount(0);
|
|
||||||
|
|
||||||
// the age filters apply before the page is cut; the name search of Rebuild is still there
|
|
||||||
const all = await total();
|
|
||||||
await page.getByLabel('Edad mínima').fill('200');
|
|
||||||
await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible();
|
|
||||||
await page.getByLabel('Edad mínima').fill('45');
|
|
||||||
await expect(async () => expect(await total()).toBeLessThan(all)).toPass();
|
|
||||||
await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible();
|
|
||||||
await page.getByRole('button', { name: 'Limpiar edades' }).click();
|
|
||||||
await expect(async () => expect(await total()).toBe(all)).toPass();
|
|
||||||
|
|
||||||
// the whole query, as the two files
|
|
||||||
const [pdf] = await Promise.all([
|
|
||||||
page.waitForEvent('download'),
|
|
||||||
page.getByRole('button', { name: 'Exportar PDF' }).click(),
|
|
||||||
]);
|
|
||||||
expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf');
|
|
||||||
expect(
|
|
||||||
readFileSync((await pdf.path())!)
|
|
||||||
.subarray(0, 5)
|
|
||||||
.toString(),
|
|
||||||
).toBe('%PDF-');
|
|
||||||
const [xlsx] = await Promise.all([
|
|
||||||
page.waitForEvent('download'),
|
|
||||||
page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(),
|
|
||||||
]);
|
|
||||||
expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx');
|
|
||||||
expect(
|
|
||||||
readFileSync((await xlsx.path())!)
|
|
||||||
.subarray(0, 2)
|
|
||||||
.toString(),
|
|
||||||
).toBe('PK');
|
|
||||||
|
|
||||||
// her record: age, the detailed stages, the scales, and the file
|
|
||||||
await rows.first().locator('a').first().click();
|
|
||||||
await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:');
|
|
||||||
await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5);
|
|
||||||
await expect(page.getByText('Desde toma:').first()).toBeVisible();
|
|
||||||
await expect(page.getByText('Riesgo inmediato')).toBeVisible();
|
|
||||||
await expect(page.getByText('Riesgo a 5 años')).toBeVisible();
|
|
||||||
const [ficha] = await Promise.all([
|
|
||||||
page.waitForEvent('download'),
|
|
||||||
page.getByRole('button', { name: 'Exportar ficha PDF' }).click(),
|
|
||||||
]);
|
|
||||||
expect(
|
|
||||||
readFileSync((await ficha.path())!)
|
|
||||||
.subarray(0, 5)
|
|
||||||
.toString(),
|
|
||||||
).toBe('%PDF-');
|
|
||||||
expect(problems).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
/** Waits for a page's data: no loading indicator left. */
|
|
||||||
async function loaded(page: Page): Promise<void> {
|
|
||||||
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
|
|
||||||
timeout: 5 * 60_000,
|
|
||||||
});
|
|
||||||
await page.waitForTimeout(1000); // plots finish drawing
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const width of [1440, 820]) {
|
|
||||||
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
await page.setViewportSize({ width, height: 1000 });
|
|
||||||
const found: string[] = [];
|
|
||||||
const check = async (where: string) => {
|
|
||||||
await loaded(page);
|
|
||||||
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
|
|
||||||
};
|
|
||||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
|
||||||
await page.goto(`/indicadores/${domain}`);
|
|
||||||
const tabs = page.locator('.mdc-tab');
|
|
||||||
for (let i = 0; i < (await tabs.count()); i++) {
|
|
||||||
await tabs.nth(i).click();
|
|
||||||
await check(`${domain} tab ${i + 1}`);
|
|
||||||
}
|
|
||||||
// the record of the risk list's first patient
|
|
||||||
await tabs.nth(2).click();
|
|
||||||
await loaded(page);
|
|
||||||
const first = page.locator('table a[href*="/pacientes/"]').first();
|
|
||||||
if (await first.count()) {
|
|
||||||
await first.click();
|
|
||||||
await check(`${domain} record`);
|
|
||||||
}
|
|
||||||
await page.goto(`/gobernanza/${domain}`);
|
|
||||||
await check(`${domain} gobernanza`);
|
|
||||||
}
|
|
||||||
await page.goto('/conectar');
|
|
||||||
await check('conectar');
|
|
||||||
// a pipeline open, a node chosen, in both of its panel's tabs
|
|
||||||
await page.locator('.pipelines [mat-list-item]').first().click();
|
|
||||||
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
|
|
||||||
await check('conectar node');
|
|
||||||
await page.getByRole('tab', { name: 'Avanzado' }).click();
|
|
||||||
await check('conectar node, advanced');
|
|
||||||
await page.goto('/revision');
|
|
||||||
const tabs = page.locator('.mdc-tab');
|
|
||||||
for (let i = 0; i < (await tabs.count()); i++) {
|
|
||||||
await tabs.nth(i).click();
|
|
||||||
await check(`revision tab ${i + 1}`);
|
|
||||||
}
|
|
||||||
expect(found).toEqual([]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
+2507
-407
File diff suppressed because it is too large
Load Diff
Generated
+2266
-130
File diff suppressed because it is too large
Load Diff
+5
-2
@@ -29,9 +29,11 @@
|
|||||||
"d3-zoom": "3.0.0",
|
"d3-zoom": "3.0.0",
|
||||||
"material-symbols": "0.48.3",
|
"material-symbols": "0.48.3",
|
||||||
"ngx-vflow": "2.7.0",
|
"ngx-vflow": "2.7.0",
|
||||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
"pdfmake": "0.3.15",
|
||||||
|
"plotly.js": "4.1.2",
|
||||||
"rxjs": "~7.8.0",
|
"rxjs": "~7.8.0",
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.3.0",
|
||||||
|
"write-excel-file": "4.1.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@angular/build": "^22.3.0",
|
"@angular/build": "^22.3.0",
|
||||||
@@ -42,6 +44,7 @@
|
|||||||
"@types/d3-selection": "3.0.13",
|
"@types/d3-selection": "3.0.13",
|
||||||
"@types/d3-zoom": "3.0.9",
|
"@types/d3-zoom": "3.0.9",
|
||||||
"@types/fhir": "0.0.44",
|
"@types/fhir": "0.0.44",
|
||||||
|
"@types/pdfmake": "0.3.3",
|
||||||
"@types/plotly.js": "3.0.15",
|
"@types/plotly.js": "3.0.15",
|
||||||
"jsdom": "^31.0.0",
|
"jsdom": "^31.0.0",
|
||||||
"ng-openapi-gen": "^1.1.0",
|
"ng-openapi-gen": "^1.1.0",
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { defineConfig } from '@playwright/test';
|
import { defineConfig } from '@playwright/test';
|
||||||
|
|
||||||
/** The pages against a running API (API_URL), served by the dev server with the same
|
|
||||||
* proxy the app uses in production (`/api`). Run by WebApi/tests/test_webapp.py, which
|
|
||||||
* starts the platform and loads the synthetic hospital first. */
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
testDir: 'e2e',
|
testDir: 'e2e',
|
||||||
timeout: 15 * 60_000,
|
timeout: 15 * 60_000,
|
||||||
@@ -12,10 +9,9 @@ export default defineConfig({
|
|||||||
use: {
|
use: {
|
||||||
baseURL: 'http://127.0.0.1:4310',
|
baseURL: 'http://127.0.0.1:4310',
|
||||||
viewport: { width: 1440, height: 1000 },
|
viewport: { width: 1440, height: 1000 },
|
||||||
actionTimeout: 60_000, // a stuck step fails, not the whole run
|
actionTimeout: 60_000,
|
||||||
},
|
},
|
||||||
webServer: {
|
webServer: {
|
||||||
// IPv4 explicitly: `localhost` may resolve to ::1 only (CI containers), where the url below never answers.
|
|
||||||
command: 'npx ng serve --host 127.0.0.1 --port 4310 --proxy-config proxy.e2e.mjs',
|
command: 'npx ng serve --host 127.0.0.1 --port 4310 --proxy-config proxy.e2e.mjs',
|
||||||
env: { NG_CLI_ANALYTICS: 'false' },
|
env: { NG_CLI_ANALYTICS: 'false' },
|
||||||
url: 'http://127.0.0.1:4310',
|
url: 'http://127.0.0.1:4310',
|
||||||
|
|||||||
@@ -1,2 +1 @@
|
|||||||
// `/api` to the API the e2e run started (API_URL).
|
|
||||||
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
|
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import type { Observation, ObservationComponent } from 'fhir/r4';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { ados2Component, ados2Groups } from './ados2';
|
||||||
|
import { EXT } from './fhir';
|
||||||
|
|
||||||
|
function item(
|
||||||
|
field: string,
|
||||||
|
domain: string,
|
||||||
|
subdomain: string,
|
||||||
|
code: string,
|
||||||
|
title: string,
|
||||||
|
value?: number,
|
||||||
|
): ObservationComponent {
|
||||||
|
return {
|
||||||
|
code: {
|
||||||
|
coding: [{ code: `ados2.${field}` }, { code, display: title }],
|
||||||
|
text: title,
|
||||||
|
},
|
||||||
|
extension: [
|
||||||
|
{ url: EXT + 'ados2-domain', valueCoding: { code: domain[0], display: domain } },
|
||||||
|
{ url: EXT + 'ados2-subdomain', valueCoding: { code: subdomain, display: subdomain } },
|
||||||
|
],
|
||||||
|
valueQuantity: value == null ? undefined : { value },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const AS = 'Afectación social (AS)';
|
||||||
|
const CRR = 'Comportamiento restringido y repetitivo (CRR)';
|
||||||
|
|
||||||
|
const observation: Observation = {
|
||||||
|
resourceType: 'Observation',
|
||||||
|
status: 'final',
|
||||||
|
code: { coding: [{ code: 'ados2' }] },
|
||||||
|
component: [
|
||||||
|
{ code: { coding: [{ code: 'ados2.module' }] }, valueCodeableConcept: { text: 'Módulo 1' } },
|
||||||
|
item('pointing', AS, 'Comunicación', 'A-7', 'Señalar', 2),
|
||||||
|
item('gestures', AS, 'Comunicación', 'A-8', 'Gestos', 1),
|
||||||
|
item(
|
||||||
|
'unusual_eye_contact',
|
||||||
|
AS,
|
||||||
|
'Interacción social recíproca',
|
||||||
|
'B-1',
|
||||||
|
'Contacto visual inusual',
|
||||||
|
),
|
||||||
|
item(
|
||||||
|
'intonation',
|
||||||
|
CRR,
|
||||||
|
'Comportamientos restringidos y repetitivos',
|
||||||
|
'A-3',
|
||||||
|
'Entonación de las vocalizaciones o verbalizaciones',
|
||||||
|
3,
|
||||||
|
),
|
||||||
|
{ code: { coding: [{ code: 'ados2.response_to_name' }] } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('Ítems del ADOS-2', () => {
|
||||||
|
it('agrupa los ítems del módulo por dominio y subdominio en su orden', () => {
|
||||||
|
expect(ados2Groups(observation)).toEqual([
|
||||||
|
{
|
||||||
|
domain: AS,
|
||||||
|
subdomains: [
|
||||||
|
{
|
||||||
|
subdomain: 'Comunicación',
|
||||||
|
items: [
|
||||||
|
{ code: 'A-7', title: 'Señalar', score: 2 },
|
||||||
|
{ code: 'A-8', title: 'Gestos', score: 1 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
subdomain: 'Interacción social recíproca',
|
||||||
|
items: [{ code: 'B-1', title: 'Contacto visual inusual', score: undefined }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
domain: CRR,
|
||||||
|
subdomains: [
|
||||||
|
{
|
||||||
|
subdomain: 'Comportamientos restringidos y repetitivos',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
code: 'A-3',
|
||||||
|
title: 'Entonación de las vocalizaciones o verbalizaciones',
|
||||||
|
score: 3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(ados2Groups(undefined)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encuentra el ítem de una asociación por su número', () => {
|
||||||
|
expect(ados2Component(observation, 2)?.code.text).toBe('Señalar');
|
||||||
|
expect(ados2Component(observation, 8)?.code.coding?.[0].code).toBe('ados2.response_to_name');
|
||||||
|
expect(ados2Component(observation, 0)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import type { Observation, ObservationComponent } from 'fhir/r4';
|
||||||
|
import { code, ext } from './fhir';
|
||||||
|
|
||||||
|
export const ADOS2_ITEMS = [
|
||||||
|
'vocalization_directed',
|
||||||
|
'pointing',
|
||||||
|
'gestures',
|
||||||
|
'unusual_eye_contact',
|
||||||
|
'facial_expressions',
|
||||||
|
'gaze_integration',
|
||||||
|
'shared_enjoyment',
|
||||||
|
'response_to_name',
|
||||||
|
'ignoring',
|
||||||
|
'requesting',
|
||||||
|
'showing',
|
||||||
|
'joint_attention_initiation',
|
||||||
|
'joint_attention_response',
|
||||||
|
'social_overtures_quality',
|
||||||
|
'social_overtures_caregiver',
|
||||||
|
'reciprocal_communication',
|
||||||
|
'rapport_quality',
|
||||||
|
'intonation',
|
||||||
|
'stereotyped_language',
|
||||||
|
'unusual_sensory_interest',
|
||||||
|
'hand_finger_mannerisms',
|
||||||
|
'repetitive_interests',
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface Ados2Item {
|
||||||
|
code: string;
|
||||||
|
title: string;
|
||||||
|
score?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Ados2Subdomain {
|
||||||
|
subdomain: string;
|
||||||
|
items: Ados2Item[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Ados2Domain {
|
||||||
|
domain: string;
|
||||||
|
subdomains: Ados2Subdomain[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function coded(component: ObservationComponent, name: string): string {
|
||||||
|
const coding = ext(component, name)?.valueCoding;
|
||||||
|
return coding?.display ?? coding?.code ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ados2Groups(observation: Observation | undefined): Ados2Domain[] {
|
||||||
|
const groups: Ados2Domain[] = [];
|
||||||
|
for (const component of observation?.component ?? []) {
|
||||||
|
const item = component.code.coding?.[1];
|
||||||
|
if (!ext(component, 'ados2-domain') || !item?.code) continue;
|
||||||
|
const domain = coded(component, 'ados2-domain');
|
||||||
|
const subdomain = coded(component, 'ados2-subdomain');
|
||||||
|
let group = groups.at(-1);
|
||||||
|
if (!group || group.domain !== domain) {
|
||||||
|
group = { domain, subdomains: [] };
|
||||||
|
groups.push(group);
|
||||||
|
}
|
||||||
|
let sub = group.subdomains.at(-1);
|
||||||
|
if (!sub || sub.subdomain !== subdomain) {
|
||||||
|
sub = { subdomain, items: [] };
|
||||||
|
group.subdomains.push(sub);
|
||||||
|
}
|
||||||
|
sub.items.push({
|
||||||
|
code: item.code,
|
||||||
|
title: component.code.text ?? item.display ?? item.code,
|
||||||
|
score: component.valueQuantity?.value,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ados2Component(
|
||||||
|
observation: Observation | undefined,
|
||||||
|
number: number,
|
||||||
|
): ObservationComponent | undefined {
|
||||||
|
const field = ADOS2_ITEMS[number - 1];
|
||||||
|
return observation?.component?.find((c) => field && code(c.code) === `ados2.${field}`);
|
||||||
|
}
|
||||||
@@ -7,17 +7,17 @@ import { filter, map } from 'rxjs/operators';
|
|||||||
import { StrictHttpResponse } from '../../strict-http-response';
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
import { RequestBuilder } from '../../request-builder';
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
import { Document } from '../../models/document';
|
import { AnalyzeRequest } from '../../models/analyze-request';
|
||||||
|
|
||||||
export interface Export$Params {
|
export interface AnalyzeEegs$Params {
|
||||||
kind: string;
|
body: AnalyzeRequest
|
||||||
body: Document
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function export$(http: HttpClient, rootUrl: string, params: Export$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
|
export function analyzeEegs(http: HttpClient, rootUrl: string, params: AnalyzeEegs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
const rb = new RequestBuilder(rootUrl, export$.PATH, 'post');
|
[key: string]: string;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, analyzeEegs.PATH, 'post');
|
||||||
if (params) {
|
if (params) {
|
||||||
rb.path('kind', params.kind, {});
|
|
||||||
rb.body(params.body, 'application/json');
|
rb.body(params.body, 'application/json');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,9 +26,11 @@ export function export$(http: HttpClient, rootUrl: string, params: Export$Params
|
|||||||
).pipe(
|
).pipe(
|
||||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
map((r: HttpResponse<any>) => {
|
map((r: HttpResponse<any>) => {
|
||||||
return r as StrictHttpResponse<any>;
|
return r as StrictHttpResponse<{
|
||||||
|
[key: string]: string;
|
||||||
|
}>;
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export$.PATH = '/cacu/exports/{kind}';
|
analyzeEegs.PATH = '/tea/eegs/analyze';
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
|
||||||
|
export interface EegStudiesSummary$Params {
|
||||||
|
}
|
||||||
|
|
||||||
|
export function eegStudiesSummary(http: HttpClient, rootUrl: string, params?: EegStudiesSummary$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: number;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, eegStudiesSummary.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<{
|
||||||
|
[key: string]: number;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
eegStudiesSummary.PATH = '/tea/eegs/summary';
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/* 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 { Health } from '../../models/health';
|
||||||
|
|
||||||
|
export interface ExecutionHealth$Params {
|
||||||
|
mode?: ('sync' | 'local' | 'remote' | null);
|
||||||
|
scheduler?: (string | null);
|
||||||
|
reference?: (string | null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function executionHealth(http: HttpClient, rootUrl: string, params?: ExecutionHealth$Params, context?: HttpContext): Observable<StrictHttpResponse<Health>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, executionHealth.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.query('mode', params.mode, {});
|
||||||
|
rb.query('scheduler', params.scheduler, {});
|
||||||
|
rb.query('reference', params.reference, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Health>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
executionHealth.PATH = '/execution/health';
|
||||||
+6
-5
@@ -7,12 +7,13 @@ import { filter, map } from 'rxjs/operators';
|
|||||||
import { StrictHttpResponse } from '../../strict-http-response';
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
import { RequestBuilder } from '../../request-builder';
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Options } from '../../models/options';
|
||||||
|
|
||||||
export interface Capabilities$Params {
|
export interface ExecutionOptions$Params {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function capabilities(http: HttpClient, rootUrl: string, params?: Capabilities$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
|
export function executionOptions(http: HttpClient, rootUrl: string, params?: ExecutionOptions$Params, context?: HttpContext): Observable<StrictHttpResponse<Options>> {
|
||||||
const rb = new RequestBuilder(rootUrl, capabilities.PATH, 'get');
|
const rb = new RequestBuilder(rootUrl, executionOptions.PATH, 'get');
|
||||||
if (params) {
|
if (params) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,9 +22,9 @@ export function capabilities(http: HttpClient, rootUrl: string, params?: Capabil
|
|||||||
).pipe(
|
).pipe(
|
||||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
map((r: HttpResponse<any>) => {
|
map((r: HttpResponse<any>) => {
|
||||||
return r as StrictHttpResponse<any>;
|
return r as StrictHttpResponse<Options>;
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
capabilities.PATH = '/cacu/exports/capabilities';
|
executionOptions.PATH = '/execution/options';
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface EegSummary$Params {
|
||||||
|
domain: Domain;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* months: the domain's follow-up list over that window up to the cut-off
|
||||||
|
*/
|
||||||
|
'follow-up-window'?: (number | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* explicit window start that overrides follow-up-window
|
||||||
|
*/
|
||||||
|
'follow-up-start'?: (string | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* default: the last day with data
|
||||||
|
*/
|
||||||
|
'follow-up-cutoff'?: (string | null);
|
||||||
|
'follow-up-status'?: (string | null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function eegSummary(http: HttpClient, rootUrl: string, params: EegSummary$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, eegSummary.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.query('follow-up-window', params['follow-up-window'], {});
|
||||||
|
rb.query('follow-up-start', params['follow-up-start'], {});
|
||||||
|
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
|
||||||
|
rb.query('follow-up-status', params['follow-up-status'], {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return http.request(
|
||||||
|
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
|
||||||
|
).pipe(
|
||||||
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
|
map((r: HttpResponse<any>) => {
|
||||||
|
return r as StrictHttpResponse<{
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
eegSummary.PATH = '/{domain}/fhir/Patient/$eeg-summary';
|
||||||
@@ -16,7 +16,6 @@ export interface SearchDiagnosticReport$Params {
|
|||||||
* Patient/<id>, comma-separated
|
* Patient/<id>, comma-separated
|
||||||
*/
|
*/
|
||||||
subject?: (string | null);
|
subject?: (string | null);
|
||||||
'stage-cutoff'?: (string | null);
|
|
||||||
'_count'?: (number | null);
|
'_count'?: (number | null);
|
||||||
'_offset'?: number;
|
'_offset'?: number;
|
||||||
}
|
}
|
||||||
@@ -27,7 +26,6 @@ export function searchDiagnosticReport(http: HttpClient, rootUrl: string, params
|
|||||||
if (params) {
|
if (params) {
|
||||||
rb.path('domain', params.domain, {});
|
rb.path('domain', params.domain, {});
|
||||||
rb.query('subject', params.subject, {});
|
rb.query('subject', params.subject, {});
|
||||||
rb.query('stage-cutoff', params['stage-cutoff'], {});
|
|
||||||
rb.query('_count', params['_count'], {});
|
rb.query('_count', params['_count'], {});
|
||||||
rb.query('_offset', params['_offset'], {});
|
rb.query('_offset', params['_offset'], {});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ export interface SearchPatient$Params {
|
|||||||
*/
|
*/
|
||||||
'follow-up-window'?: (number | null);
|
'follow-up-window'?: (number | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* explicit window start that overrides follow-up-window
|
||||||
|
*/
|
||||||
|
'follow-up-start'?: (string | null);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* default: the last day with data
|
* default: the last day with data
|
||||||
*/
|
*/
|
||||||
@@ -34,16 +39,6 @@ export interface SearchPatient$Params {
|
|||||||
*/
|
*/
|
||||||
identifier?: (string | null);
|
identifier?: (string | null);
|
||||||
|
|
||||||
/**
|
|
||||||
* CaCu: completed years at the cut-off
|
|
||||||
*/
|
|
||||||
'follow-up-age-min'?: (number | null);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* CaCu: completed years at the cut-off
|
|
||||||
*/
|
|
||||||
'follow-up-age-max'?: (number | null);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* -recent or -risk-<outcome>
|
* -recent or -risk-<outcome>
|
||||||
*/
|
*/
|
||||||
@@ -74,12 +69,11 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
|
|||||||
rb.path('domain', params.domain, {});
|
rb.path('domain', params.domain, {});
|
||||||
rb.query('_id', params['_id'], {});
|
rb.query('_id', params['_id'], {});
|
||||||
rb.query('follow-up-window', params['follow-up-window'], {});
|
rb.query('follow-up-window', params['follow-up-window'], {});
|
||||||
|
rb.query('follow-up-start', params['follow-up-start'], {});
|
||||||
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
|
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
|
||||||
rb.query('follow-up-status', params['follow-up-status'], {});
|
rb.query('follow-up-status', params['follow-up-status'], {});
|
||||||
rb.query('name', params.name, {});
|
rb.query('name', params.name, {});
|
||||||
rb.query('identifier', params.identifier, {});
|
rb.query('identifier', params.identifier, {});
|
||||||
rb.query('follow-up-age-min', params['follow-up-age-min'], {});
|
|
||||||
rb.query('follow-up-age-max', params['follow-up-age-max'], {});
|
|
||||||
rb.query('_sort', params['_sort'], {});
|
rb.query('_sort', params['_sort'], {});
|
||||||
rb.query('risk-horizon', params['risk-horizon'], {});
|
rb.query('risk-horizon', params['risk-horizon'], {});
|
||||||
rb.query('_revinclude', params['_revinclude'], {});
|
rb.query('_revinclude', params['_revinclude'], {});
|
||||||
|
|||||||
@@ -7,10 +7,12 @@ import { filter, map } from 'rxjs/operators';
|
|||||||
import { StrictHttpResponse } from '../../strict-http-response';
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
import { RequestBuilder } from '../../request-builder';
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Analyze } from '../../models/analyze';
|
||||||
import { Domain } from '../../models/domain';
|
import { Domain } from '../../models/domain';
|
||||||
|
|
||||||
export interface Analyze$Params {
|
export interface Analyze$Params {
|
||||||
domain: Domain;
|
domain: Domain;
|
||||||
|
body?: Analyze
|
||||||
}
|
}
|
||||||
|
|
||||||
export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
@@ -19,6 +21,7 @@ export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Param
|
|||||||
const rb = new RequestBuilder(rootUrl, analyze.PATH, 'post');
|
const rb = new RequestBuilder(rootUrl, analyze.PATH, 'post');
|
||||||
if (params) {
|
if (params) {
|
||||||
rb.path('domain', params.domain, {});
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.body(params.body, 'application/json');
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.request(
|
return http.request(
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface Curve$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
version: number;
|
||||||
|
feature?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function curve(http: HttpClient, rootUrl: string, params: Curve$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, curve.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
rb.path('version', params.version, {});
|
||||||
|
rb.query('feature', params.feature, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}>>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
curve.PATH = '/models/{domain}/{name}/versions/{version}/curve';
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface ExportModels$Params {
|
||||||
|
domain: Domain;
|
||||||
|
names?: (Array<string> | null);
|
||||||
|
versions?: 'champion' | 'latest' | 'all';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exportModels(http: HttpClient, rootUrl: string, params: ExportModels$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, exportModels.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.query('names', params.names, {});
|
||||||
|
rb.query('versions', params.versions, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return http.request(
|
||||||
|
rb.build({ responseType: 'blob', accept: 'application/zip', context })
|
||||||
|
).pipe(
|
||||||
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
|
map((r: HttpResponse<any>) => {
|
||||||
|
return r as StrictHttpResponse<any>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
exportModels.PATH = '/models/{domain}/export';
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
/* 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 { BodyImportModels } from '../../models/body-import-models';
|
||||||
|
import { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface ImportModels$Params {
|
||||||
|
domain: Domain;
|
||||||
|
sha256: string;
|
||||||
|
body: BodyImportModels
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importModels(http: HttpClient, rootUrl: string, params: ImportModels$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: string;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, importModels.PATH, 'post');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.query('sha256', params.sha256, {});
|
||||||
|
rb.body(params.body, 'multipart/form-data');
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
importModels.PATH = '/models/{domain}/import';
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface Lineage$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
version: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lineage(http: HttpClient, rootUrl: string, params: Lineage$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, lineage.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
rb.path('version', params.version, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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]: any;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
lineage.PATH = '/models/{domain}/{name}/versions/{version}/lineage';
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface Retire$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
version: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function retire(http: HttpClient, rootUrl: string, params: Retire$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: string;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, retire.PATH, 'post');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
rb.path('version', params.version, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
retire.PATH = '/models/{domain}/{name}/versions/{version}/retire';
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Domain } from '../../models/domain';
|
||||||
|
import { TrainingConfig } from '../../models/training-config';
|
||||||
|
|
||||||
|
export interface TrainingConfig$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trainingConfig(http: HttpClient, rootUrl: string, params: TrainingConfig$Params, context?: HttpContext): Observable<StrictHttpResponse<TrainingConfig>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, trainingConfig.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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<TrainingConfig>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
trainingConfig.PATH = '/models/{domain}/{name}/training-config';
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface TrainingInputs$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trainingInputs(http: HttpClient, rootUrl: string, params: TrainingInputs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, trainingInputs.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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]: any;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
trainingInputs.PATH = '/models/{domain}/{name}/inputs';
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/* 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 { BodyUploadTrainingInputs } from '../../models/body-upload-training-inputs';
|
||||||
|
import { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface UploadTrainingInputs$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
set: string;
|
||||||
|
body: BodyUploadTrainingInputs
|
||||||
|
}
|
||||||
|
|
||||||
|
export function uploadTrainingInputs(http: HttpClient, rootUrl: string, params: UploadTrainingInputs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, uploadTrainingInputs.PATH, 'post');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
rb.path('set', params.set, {});
|
||||||
|
rb.body(params.body, 'multipart/form-data');
|
||||||
|
}
|
||||||
|
|
||||||
|
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]: any;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadTrainingInputs.PATH = '/models/{domain}/{name}/inputs/{set}/files';
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface VersionChecks$Params {
|
||||||
|
domain: Domain;
|
||||||
|
name: string;
|
||||||
|
version: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function versionChecks(http: HttpClient, rootUrl: string, params: VersionChecks$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, versionChecks.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('name', params.name, {});
|
||||||
|
rb.path('version', params.version, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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]: any;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
versionChecks.PATH = '/models/{domain}/{name}/versions/{version}/checks';
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { PreviewStatus } from '../../models/preview-status';
|
||||||
|
|
||||||
|
export interface PreviewStatus$Params {
|
||||||
|
run_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function previewStatus(http: HttpClient, rootUrl: string, params: PreviewStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<PreviewStatus>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, previewStatus.PATH, 'get');
|
||||||
|
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<PreviewStatus>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
previewStatus.PATH = '/tea/preview/{run_id}';
|
||||||
@@ -7,17 +7,18 @@ import { filter, map } from 'rxjs/operators';
|
|||||||
import { StrictHttpResponse } from '../../strict-http-response';
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
import { RequestBuilder } from '../../request-builder';
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { BodyStartPreview } from '../../models/body-start-preview';
|
||||||
|
|
||||||
export interface TerminateRun$Params {
|
export interface StartPreview$Params {
|
||||||
run_id: string;
|
body: BodyStartPreview
|
||||||
}
|
}
|
||||||
|
|
||||||
export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
export function startPreview(http: HttpClient, rootUrl: string, params: StartPreview$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
[key: string]: string;
|
[key: string]: string;
|
||||||
}>> {
|
}>> {
|
||||||
const rb = new RequestBuilder(rootUrl, terminateRun.PATH, 'post');
|
const rb = new RequestBuilder(rootUrl, startPreview.PATH, 'post');
|
||||||
if (params) {
|
if (params) {
|
||||||
rb.path('run_id', params.run_id, {});
|
rb.body(params.body, 'multipart/form-data');
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.request(
|
return http.request(
|
||||||
@@ -32,4 +33,4 @@ export function terminateRun(http: HttpClient, rootUrl: string, params: Terminat
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
terminateRun.PATH = '/runs/{run_id}/terminate';
|
startPreview.PATH = '/tea/preview';
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Cancel } from '../../models/cancel';
|
||||||
|
|
||||||
|
export interface CancelRun$Params {
|
||||||
|
run_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cancelRun(http: HttpClient, rootUrl: string, params: CancelRun$Params, context?: HttpContext): Observable<StrictHttpResponse<Cancel>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, cancelRun.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<Cancel>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelRun.PATH = '/runs/{run_id}/cancel';
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/* 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 { Domain } from '../../models/domain';
|
||||||
|
import { RunSummary } from '../../models/run-summary';
|
||||||
|
|
||||||
|
export interface RunHistory$Params {
|
||||||
|
job?: (string | null);
|
||||||
|
domain?: (Domain | null);
|
||||||
|
limit?: number;
|
||||||
|
before?: (string | null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runHistory(http: HttpClient, rootUrl: string, params?: RunHistory$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<RunSummary>>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, runHistory.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.query('job', params.job, {});
|
||||||
|
rb.query('domain', params.domain, {});
|
||||||
|
rb.query('limit', params.limit, {});
|
||||||
|
rb.query('before', params.before, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
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<RunSummary>>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
runHistory.PATH = '/runs';
|
||||||
@@ -7,17 +7,18 @@ import { filter, map } from 'rxjs/operators';
|
|||||||
import { StrictHttpResponse } from '../../strict-http-response';
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
import { RequestBuilder } from '../../request-builder';
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Run } from '../../models/run';
|
||||||
|
|
||||||
export interface RunStatus$Params {
|
export interface RunStatus$Params {
|
||||||
run_id: string;
|
run_id: string;
|
||||||
|
outputs?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<Run>> {
|
||||||
[key: string]: string;
|
|
||||||
}>> {
|
|
||||||
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
|
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
|
||||||
if (params) {
|
if (params) {
|
||||||
rb.path('run_id', params.run_id, {});
|
rb.path('run_id', params.run_id, {});
|
||||||
|
rb.query('outputs', params.outputs, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.request(
|
return http.request(
|
||||||
@@ -25,9 +26,7 @@ export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$P
|
|||||||
).pipe(
|
).pipe(
|
||||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
map((r: HttpResponse<any>) => {
|
map((r: HttpResponse<any>) => {
|
||||||
return r as StrictHttpResponse<{
|
return r as StrictHttpResponse<Run>;
|
||||||
[key: string]: string;
|
|
||||||
}>;
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,14 +5,14 @@ export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth
|
|||||||
export { authCookieLogin as authCookieLogin } 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 type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
|
||||||
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
|
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
|
||||||
export type { Capabilities$Params as Capabilities$Params } from './fn/exports/capabilities';
|
|
||||||
export { capabilities as capabilities } from './fn/exports/capabilities';
|
|
||||||
export type { Export$Params as Export$Params } from './fn/exports/export';
|
|
||||||
export { export$ as export$ } from './fn/exports/export';
|
|
||||||
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
|
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
|
||||||
export { domains as domains } from './fn/operations/domains';
|
export { domains as domains } from './fn/operations/domains';
|
||||||
export type { Health$Params as Health$Params } from './fn/operations/health';
|
export type { Health$Params as Health$Params } from './fn/operations/health';
|
||||||
export { health as health } from './fn/operations/health';
|
export { health as health } from './fn/operations/health';
|
||||||
|
export type { ExecutionHealth$Params as ExecutionHealth$Params } from './fn/execution/execution-health';
|
||||||
|
export { executionHealth as executionHealth } from './fn/execution/execution-health';
|
||||||
|
export type { ExecutionOptions$Params as ExecutionOptions$Params } from './fn/execution/execution-options';
|
||||||
|
export { executionOptions as executionOptions } from './fn/execution/execution-options';
|
||||||
export type { ConceptMaps$Params as ConceptMaps$Params } from './fn/ingest/concept-maps';
|
export type { ConceptMaps$Params as ConceptMaps$Params } from './fn/ingest/concept-maps';
|
||||||
export { conceptMaps as conceptMaps } from './fn/ingest/concept-maps';
|
export { conceptMaps as conceptMaps } from './fn/ingest/concept-maps';
|
||||||
export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/get-concept-map';
|
export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/get-concept-map';
|
||||||
@@ -49,12 +49,28 @@ export type { Models$Params as Models$Params } from './fn/models/models';
|
|||||||
export { models as models } from './fn/models/models';
|
export { models as models } from './fn/models/models';
|
||||||
export type { Analyze$Params as Analyze$Params } from './fn/models/analyze';
|
export type { Analyze$Params as Analyze$Params } from './fn/models/analyze';
|
||||||
export { analyze as analyze } from './fn/models/analyze';
|
export { analyze as analyze } from './fn/models/analyze';
|
||||||
|
export type { ExportModels$Params as ExportModels$Params } from './fn/models/export-models';
|
||||||
|
export { exportModels as exportModels } from './fn/models/export-models';
|
||||||
|
export type { ImportModels$Params as ImportModels$Params } from './fn/models/import-models';
|
||||||
|
export { importModels as importModels } from './fn/models/import-models';
|
||||||
export type { Score$Params as Score$Params } from './fn/models/score';
|
export type { Score$Params as Score$Params } from './fn/models/score';
|
||||||
export { score as score } from './fn/models/score';
|
export { score as score } from './fn/models/score';
|
||||||
export type { Train$Params as Train$Params } from './fn/models/train';
|
export type { Train$Params as Train$Params } from './fn/models/train';
|
||||||
export { train as train } from './fn/models/train';
|
export { train as train } from './fn/models/train';
|
||||||
|
export type { TrainingInputs$Params as TrainingInputs$Params } from './fn/models/training-inputs';
|
||||||
|
export { trainingInputs as trainingInputs } from './fn/models/training-inputs';
|
||||||
|
export type { UploadTrainingInputs$Params as UploadTrainingInputs$Params } from './fn/models/upload-training-inputs';
|
||||||
|
export { uploadTrainingInputs as uploadTrainingInputs } from './fn/models/upload-training-inputs';
|
||||||
|
export type { TrainingConfig$Params as TrainingConfig$Params } from './fn/models/training-config';
|
||||||
|
export { trainingConfig as trainingConfig } from './fn/models/training-config';
|
||||||
export type { Versions$Params as Versions$Params } from './fn/models/versions';
|
export type { Versions$Params as Versions$Params } from './fn/models/versions';
|
||||||
export { versions as versions } from './fn/models/versions';
|
export { versions as versions } from './fn/models/versions';
|
||||||
|
export type { VersionChecks$Params as VersionChecks$Params } from './fn/models/version-checks';
|
||||||
|
export { versionChecks as versionChecks } from './fn/models/version-checks';
|
||||||
|
export type { Curve$Params as Curve$Params } from './fn/models/curve';
|
||||||
|
export { curve as curve } from './fn/models/curve';
|
||||||
|
export type { Lineage$Params as Lineage$Params } from './fn/models/lineage';
|
||||||
|
export { lineage as lineage } from './fn/models/lineage';
|
||||||
export type { Promote$Params as Promote$Params } from './fn/models/promote';
|
export type { Promote$Params as Promote$Params } from './fn/models/promote';
|
||||||
export { promote as promote } from './fn/models/promote';
|
export { promote as promote } from './fn/models/promote';
|
||||||
export type { AddClinicalValidation$Params as AddClinicalValidation$Params } from './fn/models/add-clinical-validation';
|
export type { AddClinicalValidation$Params as AddClinicalValidation$Params } from './fn/models/add-clinical-validation';
|
||||||
@@ -63,6 +79,8 @@ export type { ReadReport$Json$Params as ReadReport$Json$Params } from './fn/mode
|
|||||||
export { readReport$Json as readReport$Json } from './fn/models/read-report-json';
|
export { readReport$Json as readReport$Json } from './fn/models/read-report-json';
|
||||||
export type { ReadReport$Any$Params as ReadReport$Any$Params } from './fn/models/read-report-any';
|
export type { ReadReport$Any$Params as ReadReport$Any$Params } from './fn/models/read-report-any';
|
||||||
export { readReport$Any as readReport$Any } from './fn/models/read-report-any';
|
export { readReport$Any as readReport$Any } from './fn/models/read-report-any';
|
||||||
|
export type { Retire$Params as Retire$Params } from './fn/models/retire';
|
||||||
|
export { retire as retire } from './fn/models/retire';
|
||||||
export type { Conflicts$Params as Conflicts$Params } from './fn/review/conflicts';
|
export type { Conflicts$Params as Conflicts$Params } from './fn/review/conflicts';
|
||||||
export { conflicts as conflicts } from './fn/review/conflicts';
|
export { conflicts as conflicts } from './fn/review/conflicts';
|
||||||
export type { Correct$Params as Correct$Params } from './fn/review/correct';
|
export type { Correct$Params as Correct$Params } from './fn/review/correct';
|
||||||
@@ -77,14 +95,24 @@ export type { Reject$Params as Reject$Params } from './fn/review/reject';
|
|||||||
export { reject as reject } from './fn/review/reject';
|
export { reject as reject } from './fn/review/reject';
|
||||||
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
|
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
|
||||||
export { unrecognised as unrecognised } from './fn/review/unrecognised';
|
export { unrecognised as unrecognised } from './fn/review/unrecognised';
|
||||||
|
export type { RunHistory$Params as RunHistory$Params } from './fn/runs/run-history';
|
||||||
|
export { runHistory as runHistory } from './fn/runs/run-history';
|
||||||
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
|
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
|
||||||
export { runStatus as runStatus } from './fn/runs/run-status';
|
export { runStatus as runStatus } from './fn/runs/run-status';
|
||||||
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
|
export type { CancelRun$Params as CancelRun$Params } from './fn/runs/cancel-run';
|
||||||
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
|
export { cancelRun as cancelRun } from './fn/runs/cancel-run';
|
||||||
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
|
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
|
||||||
export { studies as studies } from './fn/eeg/studies';
|
export { studies as studies } from './fn/eeg/studies';
|
||||||
|
export type { AnalyzeEegs$Params as AnalyzeEegs$Params } from './fn/eeg/analyze-eegs';
|
||||||
|
export { analyzeEegs as analyzeEegs } from './fn/eeg/analyze-eegs';
|
||||||
|
export type { EegStudiesSummary$Params as EegStudiesSummary$Params } from './fn/eeg/eeg-studies-summary';
|
||||||
|
export { eegStudiesSummary as eegStudiesSummary } from './fn/eeg/eeg-studies-summary';
|
||||||
export type { Study$Params as Study$Params } from './fn/eeg/study';
|
export type { Study$Params as Study$Params } from './fn/eeg/study';
|
||||||
export { study as study } from './fn/eeg/study';
|
export { study as study } from './fn/eeg/study';
|
||||||
|
export type { StartPreview$Params as StartPreview$Params } from './fn/preview/start-preview';
|
||||||
|
export { startPreview as startPreview } from './fn/preview/start-preview';
|
||||||
|
export type { PreviewStatus$Params as PreviewStatus$Params } from './fn/preview/preview-status';
|
||||||
|
export { previewStatus as previewStatus } from './fn/preview/preview-status';
|
||||||
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
|
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
|
||||||
export { usersCurrentUser as usersCurrentUser } 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 type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
|
||||||
@@ -115,6 +143,8 @@ export type { SearchObservation$Params as SearchObservation$Params } from './fn/
|
|||||||
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
|
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
|
||||||
export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/search-patient';
|
export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/search-patient';
|
||||||
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
|
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
|
||||||
|
export type { EegSummary$Params as EegSummary$Params } from './fn/fhir/eeg-summary';
|
||||||
|
export { eegSummary as eegSummary } from './fn/fhir/eeg-summary';
|
||||||
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
|
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
|
||||||
export { readPatient as readPatient } from './fn/fhir/read-patient';
|
export { readPatient as readPatient } from './fn/fhir/read-patient';
|
||||||
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
|
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
|
||||||
|
|||||||
+25
-2
@@ -2,22 +2,30 @@
|
|||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
export type { Analysis } from './models/analysis';
|
export type { Analysis } from './models/analysis';
|
||||||
|
export type { Analyze } from './models/analyze';
|
||||||
|
export type { AnalyzeRequest } from './models/analyze-request';
|
||||||
export type { Answers } from './models/answers';
|
export type { Answers } from './models/answers';
|
||||||
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
|
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
|
||||||
|
export type { BodyImportModels } from './models/body-import-models';
|
||||||
|
export type { BodyStartPreview } from './models/body-start-preview';
|
||||||
export type { BodyUpload } from './models/body-upload';
|
export type { BodyUpload } from './models/body-upload';
|
||||||
|
export type { BodyUploadTrainingInputs } from './models/body-upload-training-inputs';
|
||||||
export type { Browsed } from './models/browsed';
|
export type { Browsed } from './models/browsed';
|
||||||
|
export type { Cancel } from './models/cancel';
|
||||||
export type { Catalog } from './models/catalog';
|
export type { Catalog } from './models/catalog';
|
||||||
export type { Condition } from './models/condition';
|
export type { Condition } from './models/condition';
|
||||||
export type { Correction } from './models/correction';
|
export type { Correction } from './models/correction';
|
||||||
export type { Document } from './models/document';
|
|
||||||
export type { Domain } from './models/domain';
|
export type { Domain } from './models/domain';
|
||||||
|
export type { Edf } from './models/edf';
|
||||||
export type { Entry } from './models/entry';
|
export type { Entry } from './models/entry';
|
||||||
export type { ErrorModel } from './models/error-model';
|
export type { ErrorModel } from './models/error-model';
|
||||||
|
export type { Execution } from './models/execution';
|
||||||
export type { Extract } from './models/extract';
|
export type { Extract } from './models/extract';
|
||||||
export type { Fhir } from './models/fhir';
|
export type { Fhir } from './models/fhir';
|
||||||
export type { FieldSpec } from './models/field-spec';
|
export type { FieldSpec } from './models/field-spec';
|
||||||
export type { Group } from './models/group';
|
export type { Group } from './models/group';
|
||||||
export type { Guided } from './models/guided';
|
export type { Guided } from './models/guided';
|
||||||
|
export type { Health } from './models/health';
|
||||||
export type { HttpValidationError } from './models/http-validation-error';
|
export type { HttpValidationError } from './models/http-validation-error';
|
||||||
export type { Join } from './models/join';
|
export type { Join } from './models/join';
|
||||||
export type { Link } from './models/link';
|
export type { Link } from './models/link';
|
||||||
@@ -27,28 +35,43 @@ export type { Map } from './models/map';
|
|||||||
export type { Metric } from './models/metric';
|
export type { Metric } from './models/metric';
|
||||||
export type { Model } from './models/model';
|
export type { Model } from './models/model';
|
||||||
export type { Option } from './models/option';
|
export type { Option } from './models/option';
|
||||||
|
export type { Options } from './models/options';
|
||||||
export type { PersonDecision } from './models/person-decision';
|
export type { PersonDecision } from './models/person-decision';
|
||||||
export type { Pipeline } from './models/pipeline';
|
export type { Pipeline } from './models/pipeline';
|
||||||
export type { Position } from './models/position';
|
export type { Position } from './models/position';
|
||||||
|
export type { PreviewAdos2 } from './models/preview-ados-2';
|
||||||
|
export type { PreviewEeg } from './models/preview-eeg';
|
||||||
|
export type { PreviewMetric } from './models/preview-metric';
|
||||||
|
export type { PreviewResult } from './models/preview-result';
|
||||||
|
export type { PreviewStatus } from './models/preview-status';
|
||||||
|
export type { Progress } from './models/progress';
|
||||||
export type { Provider } from './models/provider';
|
export type { Provider } from './models/provider';
|
||||||
export type { Read } from './models/read';
|
export type { Read } from './models/read';
|
||||||
export type { Rejection } from './models/rejection';
|
export type { Rejection } from './models/rejection';
|
||||||
export type { Relation } from './models/relation';
|
|
||||||
export type { Route } from './models/route';
|
export type { Route } from './models/route';
|
||||||
|
export type { Run } from './models/run';
|
||||||
export type { RunRequest } from './models/run-request';
|
export type { RunRequest } from './models/run-request';
|
||||||
|
export type { RunSummary } from './models/run-summary';
|
||||||
export type { SavedPipeline } from './models/saved-pipeline';
|
export type { SavedPipeline } from './models/saved-pipeline';
|
||||||
|
export type { Scope } from './models/scope';
|
||||||
|
export type { Score } from './models/score';
|
||||||
export type { SignIn } from './models/sign-in';
|
export type { SignIn } from './models/sign-in';
|
||||||
export type { Site } from './models/site';
|
export type { Site } from './models/site';
|
||||||
export type { Source } from './models/source';
|
export type { Source } from './models/source';
|
||||||
export type { SourceRef } from './models/source-ref';
|
export type { SourceRef } from './models/source-ref';
|
||||||
export type { SourceType } from './models/source-type';
|
export type { SourceType } from './models/source-type';
|
||||||
|
export type { Step } from './models/step';
|
||||||
export type { Study } from './models/study';
|
export type { Study } from './models/study';
|
||||||
export type { Target } from './models/target';
|
export type { Target } from './models/target';
|
||||||
|
export type { Tasks } from './models/tasks';
|
||||||
export type { Tested } from './models/tested';
|
export type { Tested } from './models/tested';
|
||||||
export type { Training } from './models/training';
|
export type { Training } from './models/training';
|
||||||
|
export type { TrainingConfig } from './models/training-config';
|
||||||
|
export type { TrainingSource } from './models/training-source';
|
||||||
export type { Uploaded } from './models/uploaded';
|
export type { Uploaded } from './models/uploaded';
|
||||||
export type { UserCreate } from './models/user-create';
|
export type { UserCreate } from './models/user-create';
|
||||||
export type { UserRead } from './models/user-read';
|
export type { UserRead } from './models/user-read';
|
||||||
export type { UserUpdate } from './models/user-update';
|
export type { UserUpdate } from './models/user-update';
|
||||||
export type { ValidationError } from './models/validation-error';
|
export type { ValidationError } from './models/validation-error';
|
||||||
export type { Version } from './models/version';
|
export type { Version } from './models/version';
|
||||||
|
export type { Worker } from './models/worker';
|
||||||
|
|||||||
@@ -2,12 +2,16 @@
|
|||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
import { Metric } from '../models/metric';
|
import { Metric } from '../models/metric';
|
||||||
import { Relation } from '../models/relation';
|
|
||||||
export interface Analysis {
|
export interface Analysis {
|
||||||
age_months: (number | null);
|
age_months: (number | null);
|
||||||
|
checks: Array<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>;
|
||||||
id: string;
|
id: string;
|
||||||
level: (string | null);
|
level: (string | null);
|
||||||
metrics: Array<Metric>;
|
metrics: Array<Metric>;
|
||||||
relation?: Array<Relation>;
|
regions: Array<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>;
|
||||||
valid: (boolean | null);
|
valid: (boolean | null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Execution } from '../models/execution';
|
||||||
|
import { Scope } from '../models/scope';
|
||||||
|
export interface AnalyzeRequest {
|
||||||
|
execution?: (Execution | null);
|
||||||
|
scope?: Scope;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Execution } from '../models/execution';
|
||||||
|
export interface Analyze {
|
||||||
|
execution?: (Execution | null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface BodyImportModels {
|
||||||
|
file: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface BodyStartPreview {
|
||||||
|
ados2?: (Blob | null);
|
||||||
|
birth_date?: (string | null);
|
||||||
|
edf: Blob;
|
||||||
|
pipeline?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface BodyUploadTrainingInputs {
|
||||||
|
files: Array<Blob>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Cancel {
|
||||||
|
id: string;
|
||||||
|
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
/* eslint-disable */
|
|
||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
|
||||||
|
|
||||||
export interface Document {
|
|
||||||
columns: Array<string>;
|
|
||||||
parameters: Array<Array<string>>;
|
|
||||||
risk_scales?: Array<{
|
|
||||||
[key: string]: any;
|
|
||||||
}>;
|
|
||||||
row_stages?: Array<Array<{
|
|
||||||
[key: string]: string;
|
|
||||||
}>>;
|
|
||||||
rows: Array<Array<string>>;
|
|
||||||
timeline?: Array<{
|
|
||||||
[key: string]: string;
|
|
||||||
}>;
|
|
||||||
title: string;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Position } from '../models/position';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EDF files (a column of file hashes) to the facts their header holds: patient code, sex,
|
||||||
|
* birth date, recording date, record code, duration and channel count, as `edf_*` columns.
|
||||||
|
* An unreadable file keeps its row with `edf_error` set.
|
||||||
|
*
|
||||||
|
* Use a filesystem source (`dlt.sources.filesystem:filesystem`) with the uploads folder as
|
||||||
|
* `bucket_url`, `file_glob: "*.edf"`, and `then: "persistance.readers:read_bytes"`. Read its
|
||||||
|
* `content` column with this node. Map `edf_patient_code`, `edf_birth_date`, and `edf_sex` to
|
||||||
|
* identity's `record_number`, `birth_date`, and `sex`, using the site's formats and ConceptMap.
|
||||||
|
*
|
||||||
|
* The patient code must match the hospital's record number including its prefix. Feed the
|
||||||
|
* identity map into the pipeline's link node alongside the hospital identity source. Map
|
||||||
|
* `edf_study_date` to `study_date` (format `%Y-%m-%d`), `edf_record_code` to `lab_record_id`,
|
||||||
|
* and `content` to `edf`, then feed that map and the link into a target with entity `eeg`.
|
||||||
|
*/
|
||||||
|
export interface Edf {
|
||||||
|
column: string;
|
||||||
|
id: string;
|
||||||
|
inputs?: Array<string>;
|
||||||
|
kind?: 'edf';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cómo se ve en el diagrama.
|
||||||
|
*/
|
||||||
|
label?: string;
|
||||||
|
position?: (Position | null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a request or a job config carries: None means the deployment's default.
|
||||||
|
*/
|
||||||
|
export interface Execution {
|
||||||
|
mode?: ('sync' | 'local' | 'remote' | null);
|
||||||
|
scheduler?: (string | null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Health {
|
||||||
|
dashboard_ok?: (boolean | null);
|
||||||
|
dashboard_url?: (string | null);
|
||||||
|
error?: (string | null);
|
||||||
|
expected_workers?: (number | null);
|
||||||
|
latency_ms?: (number | null);
|
||||||
|
mode: 'sync' | 'local' | 'remote';
|
||||||
|
reachable: boolean;
|
||||||
|
reference?: ({
|
||||||
|
[key: string]: any;
|
||||||
|
} | null);
|
||||||
|
scheduler: (string | null);
|
||||||
|
threads?: (number | null);
|
||||||
|
version_error?: (string | null);
|
||||||
|
versions_ok?: (boolean | null);
|
||||||
|
workers?: (number | null);
|
||||||
|
}
|
||||||
@@ -1,16 +1,10 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
import { Site } from '../models/site';
|
|
||||||
export interface Metric {
|
export interface Metric {
|
||||||
code: string;
|
code: string;
|
||||||
electrodes?: Array<Site>;
|
|
||||||
median?: (number | null);
|
|
||||||
model: (string | null);
|
model: (string | null);
|
||||||
outside: (number | null);
|
outside: (number | null);
|
||||||
p5?: (number | null);
|
|
||||||
p95?: (number | null);
|
|
||||||
value: number;
|
value: number;
|
||||||
z: (number | null);
|
z: (number | null);
|
||||||
zones?: Array<Site>;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Options {
|
||||||
|
default_mode: 'sync' | 'local' | 'remote';
|
||||||
|
schedulers: Array<string>;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Edf } from '../models/edf';
|
||||||
import { Extract } from '../models/extract';
|
import { Extract } from '../models/extract';
|
||||||
import { Fhir } from '../models/fhir';
|
import { Fhir } from '../models/fhir';
|
||||||
import { Join } from '../models/join';
|
import { Join } from '../models/join';
|
||||||
@@ -11,5 +12,5 @@ import { Route } from '../models/route';
|
|||||||
import { Source } from '../models/source';
|
import { Source } from '../models/source';
|
||||||
import { Target } from '../models/target';
|
import { Target } from '../models/target';
|
||||||
export interface Pipeline {
|
export interface Pipeline {
|
||||||
nodes: Array<(Source | Read | Route | Map | Extract | Fhir | Join | Link | Target)>;
|
nodes: Array<(Source | Read | Route | Map | Extract | Edf | Fhir | Join | Link | Target)>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface PreviewAdos2 {
|
||||||
|
classification: (string | null);
|
||||||
|
css: (number | null);
|
||||||
|
evaluation_date: (string | null);
|
||||||
|
items: {
|
||||||
|
[key: string]: (number | null);
|
||||||
|
};
|
||||||
|
module: (string | null);
|
||||||
|
read: Array<string>;
|
||||||
|
titles: {
|
||||||
|
[key: string]: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { PreviewMetric } from '../models/preview-metric';
|
||||||
|
export interface PreviewEeg {
|
||||||
|
age_months: (number | null);
|
||||||
|
bad_channels: (number | null);
|
||||||
|
channels: (number | null);
|
||||||
|
checks: Array<{
|
||||||
|
[key: string]: any;
|
||||||
|
}>;
|
||||||
|
clean_fraction: (number | null);
|
||||||
|
duration_min: (number | null);
|
||||||
|
error: (string | null);
|
||||||
|
level: string;
|
||||||
|
line_noise_db: (number | null);
|
||||||
|
metrics: Array<PreviewMetric>;
|
||||||
|
recorded_on: (string | null);
|
||||||
|
sleep: (boolean | null);
|
||||||
|
valid: (boolean | null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Score } from '../models/score';
|
||||||
|
import { Site } from '../models/site';
|
||||||
|
export interface PreviewMetric {
|
||||||
|
code: string;
|
||||||
|
electrodes: {
|
||||||
|
[key: string]: Site;
|
||||||
|
};
|
||||||
|
model: (string | null);
|
||||||
|
score: (Score | null);
|
||||||
|
value: (number | null);
|
||||||
|
zones: {
|
||||||
|
[key: string]: Site;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { PreviewAdos2 } from '../models/preview-ados-2';
|
||||||
|
import { PreviewEeg } from '../models/preview-eeg';
|
||||||
|
export interface PreviewResult {
|
||||||
|
ados2: (PreviewAdos2 | null);
|
||||||
|
eeg: PreviewEeg;
|
||||||
|
warnings: Array<string>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { PreviewResult } from '../models/preview-result';
|
||||||
|
export interface PreviewStatus {
|
||||||
|
result: (PreviewResult | null);
|
||||||
|
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Tasks } from '../models/tasks';
|
||||||
|
import { Worker } from '../models/worker';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The run tag's JSON; the API returns it as it is.
|
||||||
|
*/
|
||||||
|
export interface Progress {
|
||||||
|
done: number;
|
||||||
|
elapsed_s: number;
|
||||||
|
eta_s: (number | null);
|
||||||
|
mode: 'sync' | 'local' | 'remote';
|
||||||
|
phase: string;
|
||||||
|
scheduler: (string | null);
|
||||||
|
tasks?: (Tasks | null);
|
||||||
|
total: number;
|
||||||
|
updated_at: string;
|
||||||
|
workers?: Array<Worker>;
|
||||||
|
}
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface RunSummary {
|
||||||
|
domain: (string | null);
|
||||||
|
ended: (number | null);
|
||||||
|
id: string;
|
||||||
|
job: string;
|
||||||
|
started: (number | null);
|
||||||
|
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Progress } from '../models/progress';
|
||||||
|
import { Step } from '../models/step';
|
||||||
|
export interface Run {
|
||||||
|
domain: (string | null);
|
||||||
|
ended: (number | null);
|
||||||
|
error: (string | null);
|
||||||
|
id: string;
|
||||||
|
info: Array<string>;
|
||||||
|
job: string;
|
||||||
|
outputs?: ({
|
||||||
|
[key: string]: any;
|
||||||
|
} | null);
|
||||||
|
progress: (Progress | null);
|
||||||
|
started: (number | null);
|
||||||
|
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
|
||||||
|
status: string;
|
||||||
|
steps: Array<Step>;
|
||||||
|
warnings: Array<string>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which EEGs an analysis takes: the pending ones, the first `n` of them, or the named
|
||||||
|
* ones (re-analysis), each named by the `id` that `/tea/eegs` shows.
|
||||||
|
*/
|
||||||
|
export interface Scope {
|
||||||
|
ids?: Array<string>;
|
||||||
|
mode?: 'pending' | 'first_n' | 'ids';
|
||||||
|
n?: (number | null);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Score {
|
||||||
|
median: (number | null);
|
||||||
|
outside: (number | null);
|
||||||
|
p5: (number | null);
|
||||||
|
p95: (number | null);
|
||||||
|
z: (number | null);
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Score } from '../models/score';
|
||||||
export interface Site {
|
export interface Site {
|
||||||
site: string;
|
score: (Score | null);
|
||||||
value: number;
|
value: (number | null);
|
||||||
z: (number | null);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Step {
|
||||||
|
ended: (number | null);
|
||||||
|
key: string;
|
||||||
|
started: (number | null);
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Tasks {
|
||||||
|
erred?: number;
|
||||||
|
memory?: number;
|
||||||
|
processing?: number;
|
||||||
|
queued?: number;
|
||||||
|
waiting?: number;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface TrainingConfig {
|
||||||
|
defaults: {
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
domain: string;
|
||||||
|
json_schema: {
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface TrainingSource {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carpeta dentro de TEA_REFERENCE_ROOT
|
||||||
|
*/
|
||||||
|
folder?: (string | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* site: los niños del sitio sin el diagnóstico a la fecha de corte; folder: una carpeta de EDF con edades.csv (path, age en meses)
|
||||||
|
*/
|
||||||
|
kind?: 'site' | 'folder';
|
||||||
|
line_hz?: 50 | 60;
|
||||||
|
}
|
||||||
@@ -1,7 +1,15 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { Execution } from '../models/execution';
|
||||||
|
import { TrainingSource } from '../models/training-source';
|
||||||
export interface Training {
|
export interface Training {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha de corte de los datos (por omisión, hoy)
|
||||||
|
*/
|
||||||
as_of?: (string | null);
|
as_of?: (string | null);
|
||||||
|
execution?: (Execution | null);
|
||||||
models?: Array<string>;
|
models?: Array<string>;
|
||||||
|
source?: (TrainingSource | null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,5 +11,6 @@ export interface Version {
|
|||||||
[key: string]: string;
|
[key: string]: string;
|
||||||
};
|
};
|
||||||
reports: Array<string>;
|
reports: Array<string>;
|
||||||
|
status: 'champion' | 'retired' | 'candidate';
|
||||||
version: number;
|
version: number;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
export interface Worker {
|
||||||
|
cpu_pct: number;
|
||||||
|
executing: number;
|
||||||
|
memory_bytes: number;
|
||||||
|
memory_limit: (number | null);
|
||||||
|
name: string;
|
||||||
|
threads: number;
|
||||||
|
}
|
||||||
@@ -13,6 +13,12 @@ export const routes: Routes = [
|
|||||||
canActivate: [domainAllowed],
|
canActivate: [domainAllowed],
|
||||||
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
|
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'indicadores/tea/pacientes/:id/riesgo',
|
||||||
|
canActivate: [domainAllowed],
|
||||||
|
data: { domain: 'tea', risk: true },
|
||||||
|
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'indicadores/:domain/pacientes/:id',
|
path: 'indicadores/:domain/pacientes/:id',
|
||||||
canActivate: [domainAllowed],
|
canActivate: [domainAllowed],
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ export const signedIn: CanActivateFn = async (_route, state) => {
|
|||||||
/** A domain's pages show only to whom may see it. */
|
/** A domain's pages show only to whom may see it. */
|
||||||
export const domainAllowed: CanActivateFn = (route) => {
|
export const domainAllowed: CanActivateFn = (route) => {
|
||||||
const auth = inject(Auth);
|
const auth = inject(Auth);
|
||||||
const domain = route.paramMap.get('domain');
|
const domain = route.paramMap.get('domain') ?? route.data['domain'];
|
||||||
if (!domain || auth.canSee(domain)) return true;
|
if (!domain || auth.canSee(domain)) return true;
|
||||||
const first = auth.user()?.domains[0];
|
const first = auth.user()?.domains[0];
|
||||||
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
|
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { MatDialog } from '@angular/material/dialog';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { CardActions } from './card-actions';
|
||||||
|
|
||||||
|
describe('CardActions', () => {
|
||||||
|
it('opens the published definition and emits back only through the filtered action', async () => {
|
||||||
|
const fixture = TestBed.createComponent(CardActions);
|
||||||
|
fixture.componentRef.setInput('measures', [
|
||||||
|
{
|
||||||
|
resourceType: 'Measure',
|
||||||
|
status: 'active',
|
||||||
|
title: 'Oportunidad',
|
||||||
|
description: 'Definición publicada',
|
||||||
|
group: [
|
||||||
|
{
|
||||||
|
population: [
|
||||||
|
{
|
||||||
|
code: { text: 'Numerador' },
|
||||||
|
criteria: { language: 'text/plain', description: 'Casos oportunos' },
|
||||||
|
},
|
||||||
|
{ criteria: { language: 'text/plain' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const back = vi.fn();
|
||||||
|
fixture.componentInstance.back.subscribe(back);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const host: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(host.textContent).not.toContain('Volver');
|
||||||
|
host.querySelector<HTMLButtonElement>('[aria-label="Ver definición"]')!.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
|
||||||
|
const dialog = document.querySelector('[role="dialog"]')!;
|
||||||
|
expect(dialog.textContent).toContain('Oportunidad');
|
||||||
|
expect(dialog.textContent).toContain('Definición publicada');
|
||||||
|
expect(dialog.textContent).toContain('Numerador');
|
||||||
|
expect(dialog.textContent).toContain('Casos oportunos');
|
||||||
|
expect(dialog.textContent).toContain('Sin definición publicada');
|
||||||
|
TestBed.inject(MatDialog).closeAll();
|
||||||
|
|
||||||
|
fixture.componentRef.setInput('filtered', true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
[...host.querySelectorAll('button')]
|
||||||
|
.find((button) => button.textContent?.trim() === 'Volver')!
|
||||||
|
.click();
|
||||||
|
expect(back).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { Component, inject, input, output, TemplateRef } from '@angular/core';
|
||||||
|
import { NgTemplateOutlet } from '@angular/common';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||||
|
import { MatMenuModule } from '@angular/material/menu';
|
||||||
|
import type { Measure } from 'fhir/r4';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-card-actions',
|
||||||
|
imports: [NgTemplateOutlet, MatButtonModule, MatDialogModule, MatMenuModule],
|
||||||
|
template: `
|
||||||
|
<button mat-icon-button type="button" aria-label="Ver definición" (click)="open(definition)">
|
||||||
|
?
|
||||||
|
</button>
|
||||||
|
@if (settings(); as content) {
|
||||||
|
<button mat-button type="button" [matMenuTriggerFor]="menu">Configuración</button>
|
||||||
|
<mat-menu #menu="matMenu">
|
||||||
|
<ng-template matMenuContent>
|
||||||
|
<ng-container [ngTemplateOutlet]="content" />
|
||||||
|
</ng-template>
|
||||||
|
</mat-menu>
|
||||||
|
}
|
||||||
|
@if (filtered()) {
|
||||||
|
<button mat-button type="button" (click)="back.emit()">Volver</button>
|
||||||
|
}
|
||||||
|
|
||||||
|
<ng-template #definition>
|
||||||
|
<h2 mat-dialog-title>Definición</h2>
|
||||||
|
<mat-dialog-content>
|
||||||
|
@for (measure of measures(); track $index) {
|
||||||
|
<h3>{{ measure.title }}</h3>
|
||||||
|
@if (measure.description) {
|
||||||
|
<p>{{ measure.description }}</p>
|
||||||
|
}
|
||||||
|
@for (group of measure.group ?? []; track $index) {
|
||||||
|
@for (population of group.population ?? []; track $index) {
|
||||||
|
<p>
|
||||||
|
@if (population.code?.text; as text) {
|
||||||
|
<strong>{{ text }}</strong>
|
||||||
|
}
|
||||||
|
@if (population.criteria.description; as description) {
|
||||||
|
{{ description }}
|
||||||
|
} @else if (!population.code?.text) {
|
||||||
|
Sin definición publicada
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
} @empty {
|
||||||
|
<p>Sin definición publicada</p>
|
||||||
|
}
|
||||||
|
} @empty {
|
||||||
|
<p>Sin definición publicada</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</mat-dialog-content>
|
||||||
|
<mat-dialog-actions align="end">
|
||||||
|
<button mat-button type="button" mat-dialog-close>Cerrar</button>
|
||||||
|
</mat-dialog-actions>
|
||||||
|
</ng-template>
|
||||||
|
`,
|
||||||
|
styles: ':host { display: inline-flex; align-items: center; gap: var(--space-1); }',
|
||||||
|
})
|
||||||
|
export class CardActions {
|
||||||
|
private readonly dialog = inject(MatDialog);
|
||||||
|
readonly measures = input.required<Measure[]>();
|
||||||
|
readonly settings = input<TemplateRef<unknown>>();
|
||||||
|
readonly filtered = input(false);
|
||||||
|
readonly back = output<void>();
|
||||||
|
|
||||||
|
protected open(template: TemplateRef<unknown>): void {
|
||||||
|
this.dialog.open(template);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,7 +59,6 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
|
|
||||||
export const KINDS: Record<Kind, string> = {
|
export const KINDS: Record<Kind, string> = {
|
||||||
source: 'Fuente de datos',
|
source: 'Fuente de datos',
|
||||||
read: 'Leer documentos',
|
read: 'Leer documentos',
|
||||||
@@ -67,6 +66,7 @@ export const KINDS: Record<Kind, string> = {
|
|||||||
map: 'Traducir códigos',
|
map: 'Traducir códigos',
|
||||||
extract: 'Extraer datos',
|
extract: 'Extraer datos',
|
||||||
fhir: 'Leer FHIR',
|
fhir: 'Leer FHIR',
|
||||||
|
edf: 'Leer EDF',
|
||||||
join: 'Unir',
|
join: 'Unir',
|
||||||
link: 'Identificar a la persona',
|
link: 'Identificar a la persona',
|
||||||
target: 'Guardar en la plataforma',
|
target: 'Guardar en la plataforma',
|
||||||
@@ -79,6 +79,7 @@ export const HELP: Record<Kind, string> = {
|
|||||||
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
|
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
|
||||||
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
|
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
|
||||||
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
|
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
|
||||||
|
edf: 'Lee la cabecera de cada registro EDF: paciente, fechas, duración y canales.',
|
||||||
join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
|
join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
|
||||||
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
|
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
|
||||||
target: 'Guarda los estudios ya revisados en la plataforma.',
|
target: 'Guarda los estudios ya revisados en la plataforma.',
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ export interface SourceDialogData {
|
|||||||
guided?: Guided | null;
|
guided?: Guided | null;
|
||||||
label?: string;
|
label?: string;
|
||||||
}
|
}
|
||||||
|
const NONE: string[] = [];
|
||||||
|
|
||||||
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
|
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
|
||||||
export interface SourceDialogResult {
|
export interface SourceDialogResult {
|
||||||
guided: Guided;
|
guided: Guided;
|
||||||
@@ -203,17 +205,17 @@ export class SourceDialog {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The tables a database listed, for its table field. */
|
|
||||||
/** A list answer (the columns picked), as a list. */
|
/** A list answer (the columns picked), as a list. */
|
||||||
protected listed(name: string): string[] {
|
protected listed(name: string): string[] {
|
||||||
const v = this.value(name);
|
const v = this.value(name);
|
||||||
return Array.isArray(v) ? (v as string[]) : [];
|
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. */
|
/** The columns to pick from: the first rows', and those already picked. */
|
||||||
protected columnOptions(name: string): string[] {
|
protected columnOptions(name: string): string[] {
|
||||||
return [...new Set([...this.columns(), ...this.listed(name)])];
|
return [...new Set([...this.columns(), ...this.listed(name)])];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The tables a database listed, for its table field. */
|
||||||
protected tables(): string[] {
|
protected tables(): string[] {
|
||||||
return this.tableList();
|
return this.tableList();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,3 @@
|
|||||||
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). */
|
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
|
||||||
export const ZONE_NAMES: Record<string, string> = {
|
export const ZONE_NAMES: Record<string, string> = {
|
||||||
frontal_left: 'Frontal izquierda',
|
frontal_left: 'Frontal izquierda',
|
||||||
@@ -57,88 +46,3 @@ export const OUTCOME_NAMES: Record<string, string> = {
|
|||||||
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
|
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
|
||||||
CSS: 'Puntuación de severidad (CSS)',
|
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',
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,57 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import type { Bundle, Patient } from 'fhir/r4';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { allRows, downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index';
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => {
|
||||||
|
const toFile = vi.fn();
|
||||||
|
const download = vi.fn();
|
||||||
|
return {
|
||||||
|
toFile,
|
||||||
|
write: vi.fn().mockReturnValue({ toFile }),
|
||||||
|
download,
|
||||||
|
createPdf: vi.fn().mockReturnValue({ download }),
|
||||||
|
addVirtualFileSystem: vi.fn(),
|
||||||
|
fonts: { 'Roboto-Regular.ttf': 'base64' },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock('write-excel-file/browser', () => ({ default: mocks.write }));
|
||||||
|
vi.mock('pdfmake/build/pdfmake', () => ({
|
||||||
|
default: { createPdf: mocks.createPdf, addVirtualFileSystem: mocks.addVirtualFileSystem },
|
||||||
|
}));
|
||||||
|
vi.mock('pdfmake/build/vfs_fonts', () => ({ default: mocks.fonts }));
|
||||||
|
|
||||||
|
const name = 'tea-indicadores-2026-11-30';
|
||||||
|
|
||||||
|
describe('export', () => {
|
||||||
|
it('writes capped data with a frozen header, a filter, and a parameters sheet', async () => {
|
||||||
|
const sheet = {
|
||||||
|
name: 'Indicadores',
|
||||||
|
columns: [{ header: 'Total', key: 'total', type: 'number' as const }],
|
||||||
|
rows: Array.from({ length: MAX_ROWS + 1 }, (_, total) => ({ total })),
|
||||||
|
};
|
||||||
|
await downloadXlsx(name, [sheet], { Periodo: '2026-11' });
|
||||||
|
|
||||||
|
expect(mocks.write).toHaveBeenCalledWith(
|
||||||
|
[
|
||||||
|
expect.objectContaining({ sheet: 'Indicadores', stickyRowsCount: 1 }),
|
||||||
|
expect.objectContaining({
|
||||||
|
sheet: 'Parámetros',
|
||||||
|
data: [expect.any(Array), ['Periodo', '2026-11']],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
const [[dataSheet], options] = mocks.write.mock.calls[0];
|
||||||
|
expect(dataSheet.data).toHaveLength(MAX_ROWS + 2);
|
||||||
|
expect(dataSheet.data[MAX_ROWS]).toEqual([MAX_ROWS - 1]);
|
||||||
|
expect(dataSheet.data.at(-1)).toEqual([expect.stringContaining(String(MAX_ROWS))]);
|
||||||
|
const { transform } = options.features[0].files.transform['xl/worksheets/sheet{id}.xml'];
|
||||||
|
const xml = '<worksheet><sheetData><row/></sheetData></worksheet>';
|
||||||
|
expect(transform(xml, {}, { sheetIndex: 0 })).toContain(
|
||||||
|
`</sheetData><autoFilter ref="A1:A${MAX_ROWS + 1}"/>`,
|
||||||
|
);
|
||||||
|
expect(transform(xml, {}, { sheetIndex: 1 })).toBe(xml);
|
||||||
|
expect(mocks.toFile).toHaveBeenCalledWith(`${name}.xlsx`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts domain, page, and date and refuses an id-like part', async () => {
|
||||||
|
expect(safeName(['tea', 'indicadores', '2026-11-30'])).toBe(name);
|
||||||
|
expect(() => safeName(['tea', 'patient-4821', '2026-11-30'])).toThrow();
|
||||||
|
await expect(downloadPdf('tea-patient-4821-2026-11-30', [])).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('follows next links, skipping empty entries and stopping inside the last page', async () => {
|
||||||
|
const patient = (id: string): Patient => ({ resourceType: 'Patient', id });
|
||||||
|
const bundle = (patients: Patient[], next: string): Bundle => ({
|
||||||
|
resourceType: 'Bundle',
|
||||||
|
type: 'searchset',
|
||||||
|
entry: [{}, ...patients.map((resource) => ({ resource }))],
|
||||||
|
link: [{ relation: 'next', url: next }],
|
||||||
|
});
|
||||||
|
const getPage = vi
|
||||||
|
.fn<(url: string) => Promise<Bundle>>()
|
||||||
|
.mockResolvedValueOnce(bundle([patient('1')], '/page/2'))
|
||||||
|
.mockResolvedValueOnce(bundle([patient('2'), patient('3')], '/page/3'));
|
||||||
|
|
||||||
|
await expect(allRows<Patient>('/page/1', getPage, 2)).resolves.toEqual([
|
||||||
|
patient('1'),
|
||||||
|
patient('2'),
|
||||||
|
]);
|
||||||
|
expect(getPage.mock.calls).toEqual([['/page/1'], ['/page/2']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes the institutional header and generated timestamp footer to pdfmake', async () => {
|
||||||
|
const content = [{ text: 'Indicadores' }];
|
||||||
|
await downloadPdf(name, content);
|
||||||
|
|
||||||
|
expect(mocks.addVirtualFileSystem).toHaveBeenCalledWith(mocks.fonts);
|
||||||
|
expect(mocks.createPdf).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
content,
|
||||||
|
header: expect.objectContaining({ stack: ['ISSSTELEON', 'Plataforma de Indicadores'] }),
|
||||||
|
footer: expect.any(Function),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const [definition] = mocks.createPdf.mock.calls[0];
|
||||||
|
expect(definition.footer(2, 4).text).toMatch(/^Página 2 de 4 · Generado el .+$/);
|
||||||
|
expect(mocks.download).toHaveBeenCalledWith(`${name}.pdf`);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { Bundle } from 'fhir/r4';
|
||||||
|
import { MAX_ROWS } from './xlsx';
|
||||||
|
|
||||||
|
export async function allRows<T>(
|
||||||
|
first: string,
|
||||||
|
getPage: (url: string) => Promise<Bundle>,
|
||||||
|
max = MAX_ROWS,
|
||||||
|
): Promise<T[]> {
|
||||||
|
const rows: T[] = [];
|
||||||
|
let next: string | undefined = first;
|
||||||
|
while (next && rows.length < max) {
|
||||||
|
const page = await getPage(next);
|
||||||
|
for (const { resource } of page.entry ?? []) {
|
||||||
|
if (resource) rows.push(resource as T);
|
||||||
|
if (rows.length >= max) return rows;
|
||||||
|
}
|
||||||
|
next = page.link?.find(({ relation }) => relation === 'next')?.url;
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export { allRows } from './fetch-all';
|
||||||
|
export { downloadPdf, type PdfContent } from './pdf';
|
||||||
|
export { safeName } from './safe-name';
|
||||||
|
export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx';
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { Content } from 'pdfmake/interfaces';
|
||||||
|
import { validateName } from './safe-name';
|
||||||
|
|
||||||
|
export type { Content as PdfContent } from 'pdfmake/interfaces';
|
||||||
|
|
||||||
|
export async function downloadPdf(name: string, content: Content[]): Promise<void> {
|
||||||
|
const filename = `${validateName(name)}.pdf`;
|
||||||
|
const [{ default: pdfMake }, { default: fonts }] = await Promise.all([
|
||||||
|
import('pdfmake/build/pdfmake'),
|
||||||
|
import('pdfmake/build/vfs_fonts'),
|
||||||
|
]);
|
||||||
|
pdfMake.addVirtualFileSystem(fonts);
|
||||||
|
const generatedAt = new Intl.DateTimeFormat('es-MX', {
|
||||||
|
dateStyle: 'medium',
|
||||||
|
timeStyle: 'short',
|
||||||
|
}).format(new Date());
|
||||||
|
await pdfMake
|
||||||
|
.createPdf({
|
||||||
|
content,
|
||||||
|
pageMargins: [40, 65, 40, 45],
|
||||||
|
header: {
|
||||||
|
stack: ['ISSSTELEON', 'Plataforma de Indicadores'],
|
||||||
|
margin: [40, 20, 40, 0],
|
||||||
|
},
|
||||||
|
footer: (page, pages) => ({
|
||||||
|
text: `Página ${page} de ${pages} · Generado el ${generatedAt}`,
|
||||||
|
margin: [40, 10, 40, 0],
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.download(filename);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
const domains = new Set(['cacu', 'cama', 'tea']);
|
||||||
|
const pages = new Set([
|
||||||
|
'indicadores',
|
||||||
|
'trazabilidad',
|
||||||
|
'riesgos',
|
||||||
|
'seguimiento',
|
||||||
|
'definiciones',
|
||||||
|
'gobernanza',
|
||||||
|
'revision',
|
||||||
|
'conectar',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function safeName(parts: string[]): string {
|
||||||
|
const [domain, page, date] = parts;
|
||||||
|
if (
|
||||||
|
parts.length !== 3 ||
|
||||||
|
!domains.has(domain) ||
|
||||||
|
!pages.has(page) ||
|
||||||
|
!/^\d{4}-\d{2}-\d{2}$/.test(date)
|
||||||
|
) {
|
||||||
|
throw new Error('El nombre debe contener un dominio, una página y una fecha.');
|
||||||
|
}
|
||||||
|
const parsed = new Date(date);
|
||||||
|
if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
|
||||||
|
throw new Error('La fecha del nombre no es válida.');
|
||||||
|
}
|
||||||
|
return parts.join('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateName(name: string): string {
|
||||||
|
const match = /^([^-]+)-([^-]+)-(\d{4}-\d{2}-\d{2})$/.exec(name);
|
||||||
|
if (!match) throw new Error('El nombre de exportación no es válido.');
|
||||||
|
return safeName(match.slice(1));
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import type { Cell, Row } from 'write-excel-file/browser';
|
||||||
|
import { validateName } from './safe-name';
|
||||||
|
|
||||||
|
export const MAX_ROWS = 5000;
|
||||||
|
|
||||||
|
export type Sheet = {
|
||||||
|
name: string;
|
||||||
|
columns: { header: string; key: string; type?: 'string' | 'number' | 'date' }[];
|
||||||
|
rows: Record<string, unknown>[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function cell(value: unknown, type?: Sheet['columns'][number]['type']): Cell {
|
||||||
|
if (value == null || value === '') return null;
|
||||||
|
if (type === 'date' || (!type && value instanceof Date)) {
|
||||||
|
const date = value instanceof Date ? value : new Date(String(value));
|
||||||
|
return Number.isFinite(date.getTime()) ? { value: date, format: 'yyyy-mm-dd' } : null;
|
||||||
|
}
|
||||||
|
if (type === 'number') {
|
||||||
|
const number = typeof value === 'string' && value.trim() ? Number(value) : value;
|
||||||
|
return typeof number === 'number' && Number.isFinite(number) ? number : null;
|
||||||
|
}
|
||||||
|
if (!type && typeof value === 'number') return Number.isFinite(value) ? value : null;
|
||||||
|
if (!type && typeof value === 'boolean') return value;
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function columnName(count: number): string {
|
||||||
|
let name = '';
|
||||||
|
while (count > 0) {
|
||||||
|
count--;
|
||||||
|
name = String.fromCharCode(65 + (count % 26)) + name;
|
||||||
|
count = Math.floor(count / 26);
|
||||||
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
function width(value: Cell): number {
|
||||||
|
if (value == null) return 0;
|
||||||
|
if (typeof value === 'object' && 'value' in value)
|
||||||
|
return value.value instanceof Date ? 10 : String(value.value).length;
|
||||||
|
return String(value).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadXlsx(
|
||||||
|
name: string,
|
||||||
|
sheets: Sheet[],
|
||||||
|
parameters: Record<string, string>,
|
||||||
|
): Promise<void> {
|
||||||
|
const filename = `${validateName(name)}.xlsx`;
|
||||||
|
const { default: writeExcelFile } = await import('write-excel-file/browser');
|
||||||
|
const parameterSheet: Sheet = {
|
||||||
|
name: 'Parámetros',
|
||||||
|
columns: [
|
||||||
|
{ header: 'Parámetro', key: 'parameter' },
|
||||||
|
{ header: 'Valor', key: 'value' },
|
||||||
|
],
|
||||||
|
rows: Object.entries(parameters).map(([parameter, value]) => ({ parameter, value })),
|
||||||
|
};
|
||||||
|
const filterRanges: (string | undefined)[] = [];
|
||||||
|
const workbook = [...sheets, parameterSheet].map(({ name, columns, rows }, index) => {
|
||||||
|
const data: Row[] = [columns.map(({ header }) => ({ value: header, fontWeight: 'bold' }))];
|
||||||
|
for (const row of rows.slice(0, MAX_ROWS)) {
|
||||||
|
data.push(columns.map(({ key, type }) => cell(row[key], type)));
|
||||||
|
}
|
||||||
|
if (index < sheets.length && columns.length) {
|
||||||
|
filterRanges[index] = `A1:${columnName(columns.length)}${data.length}`;
|
||||||
|
}
|
||||||
|
if (rows.length >= MAX_ROWS) {
|
||||||
|
data.push([`Límite de exportación: ${MAX_ROWS} filas.`]);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
sheet: name,
|
||||||
|
data,
|
||||||
|
stickyRowsCount: 1,
|
||||||
|
columns: columns.map((_, column) => ({
|
||||||
|
width: Math.min(80, Math.max(10, ...data.map((row) => width(row[column]))) + 2),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
await writeExcelFile(workbook, {
|
||||||
|
features: [
|
||||||
|
{
|
||||||
|
files: {
|
||||||
|
transform: {
|
||||||
|
'xl/worksheets/sheet{id}.xml': {
|
||||||
|
transform: (xml, _, { sheetIndex }) => {
|
||||||
|
const ref = filterRanges[sheetIndex];
|
||||||
|
return ref
|
||||||
|
? xml.replace('</sheetData>', `</sheetData><autoFilter ref="${ref}"/>`)
|
||||||
|
: xml;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).toFile(filename);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { exportErrorText, verifiedImport } from './bundles';
|
||||||
|
|
||||||
|
const hash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
|
||||||
|
|
||||||
|
describe('bundle import', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
const bytes = Uint8Array.from(hash.match(/../g)!, (hex) => parseInt(hex, 16));
|
||||||
|
vi.stubGlobal('crypto', { subtle: { digest: vi.fn().mockResolvedValue(bytes.buffer) } });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => vi.unstubAllGlobals());
|
||||||
|
|
||||||
|
it('refuses to upload a file with a different SHA-256', async () => {
|
||||||
|
const file = new Blob([new Uint8Array([97, 98, 99])]);
|
||||||
|
const upload = vi.fn();
|
||||||
|
await expect(verifiedImport(file, '0'.repeat(64), upload)).rejects.toThrow('no coincide');
|
||||||
|
expect(upload).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('submits the verified digest', async () => {
|
||||||
|
const file = new Blob([new Uint8Array([97, 98, 99])]);
|
||||||
|
const upload = vi.fn().mockResolvedValue({ run_id: 'run-1' });
|
||||||
|
await expect(verifiedImport(file, hash.toUpperCase(), upload)).resolves.toEqual({
|
||||||
|
run_id: 'run-1',
|
||||||
|
});
|
||||||
|
expect(upload).toHaveBeenCalledExactlyOnceWith(hash);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bundle export', () => {
|
||||||
|
const failed = (body: string) =>
|
||||||
|
new HttpErrorResponse({ status: 409, error: new Blob([body], { type: 'application/json' }) });
|
||||||
|
|
||||||
|
it("shows the API's detail from a blob error body", async () => {
|
||||||
|
await expect(
|
||||||
|
exportErrorText(failed('{"detail":"nothing to export: no version selected"}')),
|
||||||
|
).resolves.toBe('nothing to export: no version selected');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a body that is not JSON as it came', async () => {
|
||||||
|
await expect(exportErrorText(failed('Bad gateway'))).resolves.toBe('Bad gateway');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { Component, inject, input, model, output, signal } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { Api } from '../api/api';
|
||||||
|
import { exportModels, type ExportModels$Params } from '../api/fn/models/export-models';
|
||||||
|
import { importModels } from '../api/fn/models/import-models';
|
||||||
|
import type { Domain } from '../api/models/domain';
|
||||||
|
import { errorText } from './run-monitor';
|
||||||
|
|
||||||
|
export async function verifiedImport<T>(
|
||||||
|
file: Blob,
|
||||||
|
expected: string,
|
||||||
|
upload: (sha256: string) => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());
|
||||||
|
const sha256 = Array.from(new Uint8Array(digest), (byte) =>
|
||||||
|
byte.toString(16).padStart(2, '0'),
|
||||||
|
).join('');
|
||||||
|
if (expected.trim().toLowerCase() !== sha256) {
|
||||||
|
throw new Error('El SHA-256 del archivo no coincide con el esperado.');
|
||||||
|
}
|
||||||
|
return upload(sha256);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exportErrorText(error: unknown): Promise<string> {
|
||||||
|
if (!(error instanceof HttpErrorResponse && error.error instanceof Blob)) return errorText(error);
|
||||||
|
const text = await error.error.text();
|
||||||
|
try {
|
||||||
|
const detail = JSON.parse(text).detail;
|
||||||
|
return typeof detail === 'string' ? detail : text;
|
||||||
|
} catch {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function download(blob: Blob, filename: string): void {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = filename;
|
||||||
|
link.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-governance-bundles',
|
||||||
|
imports: [FormsModule, MatButtonModule],
|
||||||
|
template: `
|
||||||
|
<section class="card">
|
||||||
|
<h3>Bundles</h3>
|
||||||
|
<form (ngSubmit)="export()">
|
||||||
|
<label
|
||||||
|
>Versiones
|
||||||
|
<select name="versions" [(ngModel)]="selection">
|
||||||
|
<option value="champion">En producción</option>
|
||||||
|
<option value="latest">Últimas</option>
|
||||||
|
<option value="all">Todas</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<button mat-stroked-button type="submit" [disabled]="exporting()">Exportar bundle</button>
|
||||||
|
</form>
|
||||||
|
@if (exportedHash()) {
|
||||||
|
<p>
|
||||||
|
SHA-256 <code>{{ exportedHash() }}</code>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
<form (ngSubmit)="import(file)">
|
||||||
|
<label>Archivo ZIP <input #file type="file" accept=".zip" required /></label>
|
||||||
|
<label>SHA-256 esperado <input name="hash" [(ngModel)]="hash" required /></label>
|
||||||
|
<button mat-stroked-button type="submit" [disabled]="importing() || disabled()">
|
||||||
|
Importar bundle
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
@if (message()) {
|
||||||
|
<p role="alert">{{ message() }}</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class Bundles {
|
||||||
|
private readonly api = inject(Api);
|
||||||
|
readonly domain = input.required<Domain>();
|
||||||
|
readonly disabled = input(false);
|
||||||
|
readonly started = output<string>();
|
||||||
|
protected readonly selection = signal<NonNullable<ExportModels$Params['versions']>>('champion');
|
||||||
|
protected readonly exportedHash = signal('');
|
||||||
|
protected readonly hash = signal('');
|
||||||
|
protected readonly message = signal('');
|
||||||
|
protected readonly exporting = signal(false);
|
||||||
|
readonly importing = model(false);
|
||||||
|
|
||||||
|
protected async export(): Promise<void> {
|
||||||
|
this.exporting.set(true);
|
||||||
|
this.message.set('');
|
||||||
|
this.exportedHash.set('');
|
||||||
|
const domain = this.domain();
|
||||||
|
try {
|
||||||
|
const response = await this.api.invoke$Response(exportModels, {
|
||||||
|
domain,
|
||||||
|
versions: this.selection(),
|
||||||
|
});
|
||||||
|
const sha256 = response.headers.get('X-Bundle-Sha256') ?? '';
|
||||||
|
this.exportedHash.set(sha256);
|
||||||
|
download(response.body, `${domain}-models-${sha256.slice(0, 12)}.zip`);
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(await exportErrorText(error));
|
||||||
|
} finally {
|
||||||
|
this.exporting.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async import(input: HTMLInputElement): Promise<void> {
|
||||||
|
const file = input.files?.[0];
|
||||||
|
if (!file || this.importing() || this.disabled()) return;
|
||||||
|
this.importing.set(true);
|
||||||
|
this.message.set('');
|
||||||
|
const domain = this.domain();
|
||||||
|
try {
|
||||||
|
const { run_id } = await verifiedImport(file, this.hash(), (sha256) =>
|
||||||
|
this.api.invoke(importModels, {
|
||||||
|
domain,
|
||||||
|
sha256,
|
||||||
|
body: { file: file as unknown as string },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
input.value = '';
|
||||||
|
if (domain === this.domain()) this.started.emit(run_id);
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.importing.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Api } from '../api/api';
|
||||||
|
import { executionHealth } from '../api/fn/execution/execution-health';
|
||||||
|
import { executionOptions } from '../api/fn/execution/execution-options';
|
||||||
|
import { Execution } from './execution';
|
||||||
|
|
||||||
|
describe('execution', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('publishes the deployment default and the selected scheduler, and refreshes only when visible', async () => {
|
||||||
|
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
|
||||||
|
const doc = document;
|
||||||
|
const hidden = vi.spyOn(doc, 'hidden', 'get').mockReturnValue(false);
|
||||||
|
const invoke = vi.fn(async (operation: unknown) =>
|
||||||
|
operation === executionOptions
|
||||||
|
? { default_mode: 'local', schedulers: ['tcp://scheduler:8786'] }
|
||||||
|
: { mode: 'remote', reachable: true, workers: 2 },
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
TestBed.overrideProvider(Api, { useValue: { invoke } });
|
||||||
|
const fixture = TestBed.createComponent(Execution);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.execution()).toEqual({ mode: 'local', scheduler: null });
|
||||||
|
expect(invoke).toHaveBeenCalledWith(executionHealth, { mode: 'local', scheduler: null });
|
||||||
|
|
||||||
|
const mode: HTMLSelectElement = fixture.nativeElement.querySelector('select');
|
||||||
|
mode.value = 'remote';
|
||||||
|
mode.dispatchEvent(new Event('change'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(fixture.componentInstance.execution()).toEqual({
|
||||||
|
mode: 'remote',
|
||||||
|
scheduler: 'tcp://scheduler:8786',
|
||||||
|
});
|
||||||
|
|
||||||
|
const scheduler: HTMLInputElement = fixture.nativeElement.querySelector('input');
|
||||||
|
scheduler.value = 'other:8786';
|
||||||
|
scheduler.dispatchEvent(new Event('change'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
expect(fixture.componentInstance.execution()).toEqual({
|
||||||
|
mode: 'remote',
|
||||||
|
scheduler: 'other:8786',
|
||||||
|
});
|
||||||
|
|
||||||
|
invoke.mockClear();
|
||||||
|
await vi.advanceTimersByTimeAsync(30_000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
expect(invoke).toHaveBeenCalledExactlyOnceWith(executionHealth, {
|
||||||
|
mode: 'remote',
|
||||||
|
scheduler: 'other:8786',
|
||||||
|
});
|
||||||
|
|
||||||
|
invoke.mockClear();
|
||||||
|
hidden.mockReturnValue(true);
|
||||||
|
await vi.advanceTimersByTimeAsync(30_000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(invoke).not.toHaveBeenCalled();
|
||||||
|
} finally {
|
||||||
|
hidden.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { DOCUMENT } from '@angular/common';
|
||||||
|
import { Component, computed, effect, inject, model, resource, signal } from '@angular/core';
|
||||||
|
import { Api } from '../api/api';
|
||||||
|
import { executionHealth } from '../api/fn/execution/execution-health';
|
||||||
|
import { executionOptions } from '../api/fn/execution/execution-options';
|
||||||
|
import type { Execution as Choice } from '../api/models/execution';
|
||||||
|
import type { Health } from '../api/models/health';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-execution',
|
||||||
|
template: `
|
||||||
|
<section class="card">
|
||||||
|
<h2>Ejecución</h2>
|
||||||
|
@if (options.hasValue()) {
|
||||||
|
<label
|
||||||
|
>Modo
|
||||||
|
<select #mode [value]="choice().mode ?? ''" (change)="select($any(mode.value))">
|
||||||
|
<option value="sync">Sync</option>
|
||||||
|
<option value="local">Local</option>
|
||||||
|
<option value="remote">Remoto</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
@if (choice().mode === 'remote') {
|
||||||
|
<label
|
||||||
|
>Scheduler
|
||||||
|
<input
|
||||||
|
#scheduler
|
||||||
|
list="execution-schedulers"
|
||||||
|
[value]="choice().scheduler ?? ''"
|
||||||
|
(change)="address.set(scheduler.value)"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<datalist id="execution-schedulers">
|
||||||
|
@for (host of options.value().schedulers; track host) {
|
||||||
|
<option [value]="host"></option>
|
||||||
|
}
|
||||||
|
</datalist>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (health.hasValue()) {
|
||||||
|
@let h = health.value();
|
||||||
|
<p role="status">
|
||||||
|
{{ h.reachable ? 'Disponible' : 'No disponible' }}
|
||||||
|
@if (h.workers != null) {
|
||||||
|
· Trabajadores: {{ h.workers }}
|
||||||
|
}
|
||||||
|
@if (h.memory_per_worker != null) {
|
||||||
|
· Memoria por trabajador: {{ h.memory_per_worker }}
|
||||||
|
}
|
||||||
|
@if (h.error) {
|
||||||
|
· {{ h.error }}
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
@if (h.dashboard_url && h.dashboard_ok !== false) {
|
||||||
|
<a [href]="h.dashboard_url" target="_blank" rel="noopener">Panel de Dask</a>
|
||||||
|
}
|
||||||
|
} @else if (health.error() || options.error()) {
|
||||||
|
<p role="alert">No se pudo consultar la ejecución.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class Execution {
|
||||||
|
private readonly api = inject(Api);
|
||||||
|
private readonly document = inject(DOCUMENT);
|
||||||
|
private readonly visible = signal(!this.document.hidden);
|
||||||
|
readonly execution = model<Choice | undefined>(undefined);
|
||||||
|
protected readonly options = resource({ loader: () => this.api.invoke(executionOptions) });
|
||||||
|
protected readonly mode = signal<Choice['mode']>(undefined);
|
||||||
|
protected readonly address = signal<string | undefined>(undefined);
|
||||||
|
protected readonly choice = computed<Choice>(() => {
|
||||||
|
const options = this.options.hasValue() ? this.options.value() : undefined;
|
||||||
|
const mode = this.mode() ?? options?.default_mode;
|
||||||
|
return {
|
||||||
|
mode,
|
||||||
|
scheduler:
|
||||||
|
mode === 'remote' ? (this.address() ?? options?.schedulers[0] ?? '').trim() || null : null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
protected readonly health = resource({
|
||||||
|
params: () => (this.visible() && this.choice().mode ? this.choice() : undefined),
|
||||||
|
loader: async ({ params }) => {
|
||||||
|
const health: Health & { memory_per_worker?: string | number } = await this.api.invoke(
|
||||||
|
executionHealth,
|
||||||
|
params,
|
||||||
|
);
|
||||||
|
return health;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const choice = this.choice();
|
||||||
|
this.execution.set(choice.mode ? choice : undefined);
|
||||||
|
});
|
||||||
|
effect((cleanup) => {
|
||||||
|
const refresh = () => {
|
||||||
|
if (!this.document.hidden) this.health.reload();
|
||||||
|
};
|
||||||
|
const visibilityChanged = () => this.visible.set(!this.document.hidden);
|
||||||
|
const timer = setInterval(refresh, 30_000);
|
||||||
|
this.document.addEventListener('visibilitychange', visibilityChanged);
|
||||||
|
cleanup(() => {
|
||||||
|
clearInterval(timer);
|
||||||
|
this.document.removeEventListener('visibilitychange', visibilityChanged);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected select(mode: NonNullable<Choice['mode']>): void {
|
||||||
|
this.mode.set(mode);
|
||||||
|
if (mode === 'remote' && this.address() === undefined && this.options.hasValue()) {
|
||||||
|
this.address.set(this.options.value().schedulers[0] ?? '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { interpretabilityFigures, scenarioFigure } from './figures';
|
import { interpretabilityFigures, scenarioFigure, studyPoints } from './figures';
|
||||||
|
|
||||||
describe('governance figures', () => {
|
describe('governance figures', () => {
|
||||||
it('draws a survival report as curves with bands and the model points', () => {
|
it('draws a survival report as curves with bands and the model points', () => {
|
||||||
@@ -9,7 +9,7 @@ describe('governance figures', () => {
|
|||||||
],
|
],
|
||||||
predicted: { name: 'Modelo', months: [6], survival: [0.92], low: [0.85], high: [0.97] },
|
predicted: { name: 'Modelo', months: [6], survival: [0.92], low: [0.85], high: [0.97] },
|
||||||
});
|
});
|
||||||
expect(found.figure.data.length).toBe(3); // band, curve, model points
|
expect(found.figure.data.length).toBe(3);
|
||||||
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
|
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -30,9 +30,9 @@ describe('governance figures', () => {
|
|||||||
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
|
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
|
||||||
escenarios: [scenario],
|
escenarios: [scenario],
|
||||||
});
|
});
|
||||||
expect(found.length).toBe(1); // the cohort's curves only
|
expect(found.length).toBe(1);
|
||||||
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
|
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.length).toBe(5);
|
||||||
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
|
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -71,6 +71,84 @@ describe('governance figures', () => {
|
|||||||
expect(found.figure.data.length).toBe(2);
|
expect(found.figure.data.length).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('overlays the matching analysed metric at each study age on the API centiles', () => {
|
||||||
|
const points = studyPoints(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
id: 'one',
|
||||||
|
valid: true,
|
||||||
|
level: null,
|
||||||
|
age_months: 21,
|
||||||
|
checks: [],
|
||||||
|
regions: [],
|
||||||
|
metrics: [{ code: 'posterior_rhythm', value: 7, z: null, outside: null, model: null }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'two',
|
||||||
|
valid: true,
|
||||||
|
level: null,
|
||||||
|
age_months: null,
|
||||||
|
checks: [],
|
||||||
|
regions: [],
|
||||||
|
metrics: [{ code: 'posterior_rhythm', value: 9, z: null, outside: null, model: null }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'eeg-posterior-rhythm',
|
||||||
|
'value',
|
||||||
|
);
|
||||||
|
const [found] = interpretabilityFigures(
|
||||||
|
{
|
||||||
|
kind: 'age_curves',
|
||||||
|
curves: { value: { kind: 'curves' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
points,
|
||||||
|
centiles: [
|
||||||
|
{ age_months: 16, p5: 4, median: 6, p95: 8 },
|
||||||
|
{ age_months: 36, p5: 5, median: 7, p95: 9 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(found.figure.data[1]).toMatchObject({ x: [16, 36], y: [6, 7] });
|
||||||
|
expect(found.figure.data[2]).toMatchObject({ mode: 'markers', x: [21], y: [7] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('plots one row per association pair on the log odds-ratio axis', () => {
|
||||||
|
const [found] = interpretabilityFigures({
|
||||||
|
kind: 'forest',
|
||||||
|
rows: [
|
||||||
|
{
|
||||||
|
biomarker: 'Spindles',
|
||||||
|
zone: 'F',
|
||||||
|
outcome_code: 'A1',
|
||||||
|
odds_ratio: 2,
|
||||||
|
ci_low: 1.5,
|
||||||
|
ci_high: 3,
|
||||||
|
q: 0.04,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
biomarker: 'Spindles',
|
||||||
|
zone: 'O',
|
||||||
|
outcome_code: 'A1',
|
||||||
|
odds_ratio: 0.5,
|
||||||
|
ci_low: 0.25,
|
||||||
|
ci_high: 1,
|
||||||
|
q: 0.1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(found.figure.layout?.xaxis?.type).toBe('log');
|
||||||
|
expect(found.figure.data).toHaveLength(2);
|
||||||
|
expect(found.figure.data[0]).toMatchObject({
|
||||||
|
x: [2],
|
||||||
|
y: ['Spindles · F · A1'],
|
||||||
|
error_x: { array: [1], arrayminus: [0.5] },
|
||||||
|
hovertemplate: expect.stringContaining('q: 0.04'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('draws nothing for a report it does not know', () => {
|
it('draws nothing for a report it does not know', () => {
|
||||||
expect(interpretabilityFigures({ kind: 'other' })).toEqual([]);
|
expect(interpretabilityFigures({ kind: 'other' })).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|||||||
+130
-20
@@ -1,16 +1,16 @@
|
|||||||
|
import type { Analysis } from '../api/models/analysis';
|
||||||
import type { Figure } from '../plot';
|
import type { Figure } from '../plot';
|
||||||
import { PALETTE } from '../plot';
|
import { PALETTE } from '../plot';
|
||||||
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
|
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
|
||||||
|
|
||||||
/** A curve with its band, as the reports give them. */
|
|
||||||
interface Band {
|
interface Band {
|
||||||
x: number[];
|
x: number[];
|
||||||
y: number[];
|
y: (number | null)[];
|
||||||
low?: (number | null)[];
|
low?: (number | null)[];
|
||||||
high?: (number | null)[];
|
high?: (number | null)[];
|
||||||
}
|
}
|
||||||
|
|
||||||
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
||||||
const lines: Partial<Plotly.Data>[] = [];
|
const lines: Partial<Plotly.Data>[] = [];
|
||||||
if (b.low && b.high) {
|
if (b.low && b.high) {
|
||||||
lines.push({
|
lines.push({
|
||||||
@@ -35,10 +35,64 @@ function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Pl
|
|||||||
return lines;
|
return lines;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's
|
export interface Centile {
|
||||||
* observed and predicted risk per subgroup, or the logistic regression's calibration. */
|
age_months: number;
|
||||||
|
p5: number | null;
|
||||||
|
median: number | null;
|
||||||
|
p95: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StudyPoint {
|
||||||
|
age: number;
|
||||||
|
value: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AgeCurveOptions {
|
||||||
|
feature?: string;
|
||||||
|
centiles?: Centile[];
|
||||||
|
points?: StudyPoint[];
|
||||||
|
waitForCentiles?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const EEG_METRICS: Record<string, string> = {
|
||||||
|
'eeg-posterior-rhythm': 'posterior_rhythm',
|
||||||
|
'eeg-spindles-n2': 'spindles_n2',
|
||||||
|
'eeg-spindle-topography-n2': 'spindles_n2',
|
||||||
|
'eeg-spindles-n3': 'spindles_n3',
|
||||||
|
'eeg-spindle-topography-n3': 'spindles_n3',
|
||||||
|
'eeg-spikes': 'paroxysmal_spikes',
|
||||||
|
'eeg-gradient': 'anteroposterior_gradient',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function studyPoints(analyses: Analysis[], model: string, feature: string): StudyPoint[] {
|
||||||
|
const code = EEG_METRICS[model];
|
||||||
|
return analyses.flatMap((analysis) => {
|
||||||
|
const age = analysis.age_months;
|
||||||
|
if (age == null || !Number.isFinite(age) || age <= 0) return [];
|
||||||
|
const value =
|
||||||
|
feature === 'value'
|
||||||
|
? analysis.metrics.find((metric) => metric.code === code)?.value
|
||||||
|
: analysis.regions.find(
|
||||||
|
(region) =>
|
||||||
|
region['code'] === code && feature === region['kind'] + '_' + region['site'],
|
||||||
|
)?.['value'];
|
||||||
|
return typeof value === 'number' && Number.isFinite(value) ? [{ age, value }] : [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AssociationRow {
|
||||||
|
biomarker: string;
|
||||||
|
zone: string;
|
||||||
|
outcome_code: string;
|
||||||
|
odds_ratio: number | null;
|
||||||
|
ci_low: number | null;
|
||||||
|
ci_high: number | null;
|
||||||
|
q: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
export function interpretabilityFigures(
|
export function interpretabilityFigures(
|
||||||
report: Record<string, any>,
|
report: Record<string, any>,
|
||||||
|
ageCurve: AgeCurveOptions = {},
|
||||||
): { title: string; figure: Figure }[] {
|
): { title: string; figure: Figure }[] {
|
||||||
switch (report['kind']) {
|
switch (report['kind']) {
|
||||||
case 'curves': {
|
case 'curves': {
|
||||||
@@ -71,7 +125,6 @@ export function interpretabilityFigures(
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
case 'subgroups':
|
case 'subgroups':
|
||||||
@@ -140,26 +193,75 @@ export function interpretabilityFigures(
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
|
case 'scenarios':
|
||||||
return [];
|
return [];
|
||||||
case 'age_curves': {
|
case 'forest':
|
||||||
// The metric's own curve; a topography has only electrodes: its first one.
|
|
||||||
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
|
|
||||||
if (!value) return [];
|
|
||||||
const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`;
|
|
||||||
if (value.kind === 'count_rate') {
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
title: `Tasa de referencia: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`,
|
title: 'Asociaciones ADOS-2',
|
||||||
|
figure: {
|
||||||
|
data: (report['rows'] as AssociationRow[]).map((row) => {
|
||||||
|
const label = [row.biomarker, row.zone, row.outcome_code].filter(Boolean).join(' · ');
|
||||||
|
const odds = row.odds_ratio;
|
||||||
|
return {
|
||||||
|
x: [odds],
|
||||||
|
y: [label],
|
||||||
|
name: label,
|
||||||
|
showlegend: false,
|
||||||
|
type: 'scatter',
|
||||||
|
mode: 'markers',
|
||||||
|
marker: { color: PALETTE[4] },
|
||||||
|
error_x:
|
||||||
|
odds == null || row.ci_low == null || row.ci_high == null
|
||||||
|
? undefined
|
||||||
|
: {
|
||||||
|
type: 'data',
|
||||||
|
symmetric: false,
|
||||||
|
array: [row.ci_high - odds],
|
||||||
|
arrayminus: [odds - row.ci_low],
|
||||||
|
},
|
||||||
|
hovertemplate: '%{y}<br>OR: %{x}<br>q: ' + (row.q ?? '—') + '<extra></extra>',
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
layout: {
|
||||||
|
xaxis: { type: 'log', title: { text: 'OR (IC 95 %)' } },
|
||||||
|
yaxis: { type: 'category', automargin: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
case 'age_curves': {
|
||||||
|
const curves = report['curves'];
|
||||||
|
const feature = ageCurve.feature ?? (curves.value ? 'value' : Object.keys(curves)[0]);
|
||||||
|
const value = curves[feature];
|
||||||
|
if (!value) return [];
|
||||||
|
const label = feature === 'value' ? '' : ` · ${feature}`;
|
||||||
|
const overlay: Partial<Plotly.Data>[] = ageCurve.points?.length
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
x: ageCurve.points.map((point) => point.age),
|
||||||
|
y: ageCurve.points.map((point) => point.value),
|
||||||
|
name: 'Estudios analizados',
|
||||||
|
type: 'scatter',
|
||||||
|
mode: 'markers',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
if (value.kind === 'count_rate') {
|
||||||
|
const rate = Number.isFinite(value.rate) ? value.rate : null;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
title: `Tasa de referencia: ${rate?.toFixed(3) ?? '—'} por minuto (${value.reference} estudios)${label}`,
|
||||||
figure: {
|
figure: {
|
||||||
data: [
|
data: [
|
||||||
{
|
{
|
||||||
x: value.ages,
|
x: value.ages,
|
||||||
y: [value.rate, value.rate],
|
y: [rate, rate],
|
||||||
name: 'Tasa',
|
name: 'Tasa',
|
||||||
type: 'scatter',
|
type: 'scatter',
|
||||||
mode: 'lines',
|
mode: 'lines',
|
||||||
},
|
},
|
||||||
|
...overlay,
|
||||||
],
|
],
|
||||||
layout: {
|
layout: {
|
||||||
xaxis: { title: { text: 'Edad (meses)' } },
|
xaxis: { title: { text: 'Edad (meses)' } },
|
||||||
@@ -169,18 +271,28 @@ export function interpretabilityFigures(
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
const c = value.curve;
|
const centiles = ageCurve.centiles;
|
||||||
|
if (!centiles && ageCurve.waitForCentiles) return [];
|
||||||
|
const c = centiles
|
||||||
|
? {
|
||||||
|
age_months: centiles.map((point) => point.age_months),
|
||||||
|
median: centiles.map((point) => point.median),
|
||||||
|
p5: centiles.map((point) => point.p5),
|
||||||
|
p95: centiles.map((point) => point.p95),
|
||||||
|
}
|
||||||
|
: value.curve;
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
|
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
|
||||||
figure: {
|
figure: {
|
||||||
data: [
|
data: [
|
||||||
...banded(
|
...banded(
|
||||||
'p5–p95',
|
'Mediana',
|
||||||
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
|
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
|
||||||
PALETTE[4],
|
PALETTE[4],
|
||||||
),
|
),
|
||||||
].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)),
|
...overlay,
|
||||||
|
],
|
||||||
layout: {
|
layout: {
|
||||||
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
|
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
|
||||||
yaxis: { title: { text: 'Valor' } },
|
yaxis: { title: { text: 'Valor' } },
|
||||||
@@ -250,8 +362,6 @@ export function interpretabilityFigures(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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(
|
export function scenarioFigure(
|
||||||
title: string,
|
title: string,
|
||||||
e: any,
|
e: any,
|
||||||
|
|||||||
+230
-138
@@ -1,213 +1,305 @@
|
|||||||
<section class="page">
|
<section class="page">
|
||||||
<h1>{{ labels[domain()] ?? domain() }}</h1>
|
<h1>Gobernanza de modelos</h1>
|
||||||
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
|
<nav class="domains" aria-label="Dominios">
|
||||||
|
@for (d of domains.hasValue() ? domains.value() : []; track d) {
|
||||||
|
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
|
||||||
<form class="card actions" (submit)="$event.preventDefault()">
|
<app-execution [(execution)]="execution" />
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
|
||||||
<mat-label>Datos hasta</mat-label>
|
<section>
|
||||||
<input
|
<h2>Modelos</h2>
|
||||||
matInput
|
<div class="card actions">
|
||||||
type="date"
|
<button mat-flat-button type="button" (click)="training.set('all')">Entrenar modelos</button>
|
||||||
[ngModel]="asOf()"
|
|
||||||
(ngModelChange)="asOf.set($event)"
|
|
||||||
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
|
<button
|
||||||
mat-stroked-button
|
mat-stroked-button
|
||||||
type="button"
|
type="button"
|
||||||
[disabled]="running()"
|
[disabled]="starting() || running()"
|
||||||
(click)="confirming.set('score')"
|
(click)="start('score')"
|
||||||
>
|
>
|
||||||
Calcular riesgos
|
Calcular riesgos
|
||||||
</button>
|
</button>
|
||||||
@if (domain() === 'tea') {
|
@if (domain() === 'tea') {
|
||||||
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
|
<button
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
[disabled]="starting() || running() || !execution()"
|
||||||
|
(click)="start('analyze')"
|
||||||
|
>
|
||||||
Analizar EEG
|
Analizar EEG
|
||||||
</button>
|
</button>
|
||||||
}
|
}
|
||||||
|
<button
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
[disabled]="editing() || !models.hasValue()"
|
||||||
|
(click)="prepareCandidates(bulkDialog)"
|
||||||
|
>
|
||||||
|
Promover candidatas
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
@if (training(); as name) {
|
||||||
|
<app-governance-training
|
||||||
|
[domain]="domainKey()"
|
||||||
|
[name]="name"
|
||||||
|
[execution]="execution()"
|
||||||
|
[(busy)]="starting"
|
||||||
|
[disabled]="running() || !execution()"
|
||||||
|
(started)="follow($event.id, 'Entrenamiento', $event.autoPromote)"
|
||||||
|
/>
|
||||||
}
|
}
|
||||||
@if (run(); as r) {
|
<app-governance-bundles
|
||||||
<span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
|
[domain]="domainKey()"
|
||||||
@if (running()) {
|
[(importing)]="starting"
|
||||||
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
|
[disabled]="running()"
|
||||||
|
(started)="follow($event, 'Importación')"
|
||||||
|
/>
|
||||||
|
@if (run(); as current) {
|
||||||
|
<section class="card">
|
||||||
|
<h3>{{ current.label }}</h3>
|
||||||
|
<app-run-monitor [runId]="current.id" (finished)="finish($event)" />
|
||||||
|
</section>
|
||||||
}
|
}
|
||||||
}
|
|
||||||
</form>
|
|
||||||
@if (message()) {
|
@if (message()) {
|
||||||
<p class="muted" role="status">{{ message() }}</p>
|
<p class="message" role="status">{{ message() }}</p>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (models.isLoading()) {
|
@if (models.isLoading()) {
|
||||||
<app-loading what="los modelos" />
|
<p class="muted">Cargando modelos…</p>
|
||||||
} @else if (!models.value()?.length) {
|
} @else if (models.error(); as error) {
|
||||||
<p class="muted empty">Sin modelos entrenados en este dominio.</p>
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
} @else if (!models.hasValue() || !models.value().length) {
|
||||||
|
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
|
||||||
}
|
}
|
||||||
@for (m of models.value() ?? []; track m.name) {
|
@for (m of models.hasValue() ? models.value() : []; track m.name) {
|
||||||
<div class="card model">
|
<section class="card model">
|
||||||
<h2>
|
<h3>{{ m.title }}</h3>
|
||||||
{{ m.title }} <code class="muted code">{{ m.name }}</code>
|
<button mat-stroked-button type="button" (click)="training.set(m.name)">Reentrenar</button>
|
||||||
</h2>
|
|
||||||
<table class="plain">
|
<table class="plain">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Versión</th>
|
<th>Versión</th>
|
||||||
<th>Creada</th>
|
<th>Creada</th>
|
||||||
<th>Datos</th>
|
<th>Entrenamiento / prueba</th>
|
||||||
<th>Informes</th>
|
<th>Informes</th>
|
||||||
<th>Validación clínica</th>
|
<th>Validación clínica</th>
|
||||||
<th></th>
|
<th>Comprobaciones y linaje</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@for (v of m.versions; track v.version) {
|
@for (v of m.versions; track v.version) {
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
v{{ v.version }}
|
v{{ v.version }} <span class="badge">{{ v.status }}</span>
|
||||||
@if (champion(v)) {
|
|
||||||
<span class="badge">en producción</span>
|
|
||||||
}
|
|
||||||
</td>
|
</td>
|
||||||
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</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>
|
<td>
|
||||||
<div class="reports">
|
@for (report of v.reports; track report) {
|
||||||
@for (r of v.reports; track r) {
|
<button
|
||||||
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
|
mat-button
|
||||||
reportNames[r] ?? r
|
type="button"
|
||||||
}}</a>
|
(click)="reportDownload(m.name, v.version, report)"
|
||||||
|
>
|
||||||
|
{{ reportNames[report] ?? report }}
|
||||||
|
</button>
|
||||||
}
|
}
|
||||||
@if (v.reports.includes('interpretability')) {
|
@if (v.reports.includes('interpretability')) {
|
||||||
<button
|
<button
|
||||||
mat-button
|
mat-button
|
||||||
type="button"
|
type="button"
|
||||||
(click)="chosen.set({ name: m.name, version: v.version })"
|
(click)="chooseReport({ name: m.name, version: v.version })"
|
||||||
>
|
>
|
||||||
Ver gráficas
|
Ver gráficas
|
||||||
</button>
|
</button>
|
||||||
}
|
}
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
@if (!v.reports.includes('clinical_validation')) {
|
@if (!v.reports.includes('clinical_validation')) {
|
||||||
<input
|
<input
|
||||||
#file
|
|
||||||
type="file"
|
type="file"
|
||||||
hidden
|
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
|
||||||
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
|
|
||||||
(change)="upload(m.name, v.version, $event)"
|
(change)="upload(m.name, v.version, $event)"
|
||||||
/>
|
/>
|
||||||
<button mat-stroked-button type="button" (click)="file.click()">
|
|
||||||
Subir validación clínica
|
|
||||||
</button>
|
|
||||||
} @else {
|
} @else {
|
||||||
Agregada
|
Agregada
|
||||||
}
|
}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
@if (!champion(v)) {
|
<button
|
||||||
<button mat-stroked-button type="button" (click)="promote(m.name, v.version)">
|
mat-stroked-button
|
||||||
Promover
|
type="button"
|
||||||
|
(click)="
|
||||||
|
showVersion('checks', { name: m.name, version: v.version }, checksDialog)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
Comprobaciones
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
(click)="
|
||||||
|
showVersion('lineage', { name: m.name, version: v.version }, lineageDialog)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
Linaje
|
||||||
</button>
|
</button>
|
||||||
}
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</section>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (chosen(); as c) {
|
@if (chosen(); as version) {
|
||||||
<div class="card">
|
<section class="card">
|
||||||
<h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
|
<h3>Interpretabilidad · {{ version.name }} v{{ version.version }}</h3>
|
||||||
|
@if (feature(); as current) {
|
||||||
|
@if (ageFeatures().length > 1) {
|
||||||
|
<label
|
||||||
|
>Característica
|
||||||
|
<select [ngModel]="current" (ngModelChange)="selectedFeature.set($event)">
|
||||||
|
@for (feature of ageFeatures(); track feature) {
|
||||||
|
<option [value]="feature">{{ feature }}</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
<label><input type="checkbox" [(ngModel)]="overlay" /> Superponer estudios</label>
|
||||||
|
}
|
||||||
|
@if (report.error() || band.error() || analysed.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
@for (f of figures(); track f.title) {
|
@for (f of figures(); track f.title) {
|
||||||
<h3>{{ f.title }}</h3>
|
<h4>{{ f.title }}</h4>
|
||||||
<app-plot [figure]="f.figure" [height]="360" />
|
<app-plot
|
||||||
|
[figure]="f.figure"
|
||||||
|
[height]="
|
||||||
|
report.hasValue() && report.value()['kind'] === 'forest'
|
||||||
|
? forestHeight(f.figure.data.length)
|
||||||
|
: 360
|
||||||
|
"
|
||||||
|
/>
|
||||||
} @empty {
|
} @empty {
|
||||||
<p class="muted">
|
@if (report.isLoading() || band.isLoading()) {
|
||||||
{{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }}
|
<p class="muted">Cargando…</p>
|
||||||
</p>
|
} @else if (!report.error() && !band.error()) {
|
||||||
|
<p class="muted">Este informe no tiene gráficas.</p>
|
||||||
}
|
}
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
@if (domain() === 'tea') {
|
@if (domain() === 'tea') {
|
||||||
<div class="card model">
|
<app-eeg-studies [execution]="execution()" [refresh]="refreshed()" (changed)="refresh()" />
|
||||||
<h2>Electroencefalogramas</h2>
|
|
||||||
<table class="plain eegs">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Fecha</th>
|
|
||||||
<th>Registro</th>
|
|
||||||
<th>Análisis</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
@for (e of eegs.value() ?? []; track e.id) {
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
<button mat-button type="button" (click)="eeg.set(e.id)">{{ e.study_date }}</button>
|
|
||||||
</td>
|
|
||||||
<td>{{ e.lab_record_id ?? '—' }}</td>
|
|
||||||
<td>
|
|
||||||
{{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }}
|
|
||||||
{{ e.level ? '(' + e.level + ')' : '' }}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
} @empty {
|
|
||||||
<tr>
|
|
||||||
<td colspan="3" class="muted">Sin EEG cargados.</td>
|
|
||||||
</tr>
|
|
||||||
}
|
}
|
||||||
</tbody>
|
|
||||||
</table>
|
<dialog #checksDialog aria-label="Comprobaciones" (close)="checksFor.set(undefined)">
|
||||||
@if (eegMetrics.value(); as m) {
|
@if (checksFor(); as key) {
|
||||||
<h3>EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses</h3>
|
<h3>Comprobaciones · {{ key.name }} v{{ key.version }}</h3>
|
||||||
<table class="plain">
|
@if (checks.hasValue()) {
|
||||||
<thead>
|
@let details = checks.value();
|
||||||
<tr>
|
@let actions = checkActions(details);
|
||||||
<th>Métrica</th>
|
<ul>
|
||||||
<th>Valor</th>
|
@for (check of details.checks; track check.report) {
|
||||||
<th>z</th>
|
<li>
|
||||||
<th>Curva</th>
|
{{ reportNames[check.report] ?? check.report }} ·
|
||||||
</tr>
|
{{ check.present ? 'Presente' : 'Falta' }}
|
||||||
</thead>
|
</li>
|
||||||
<tbody>
|
|
||||||
@for (x of m.metrics; track x.code) {
|
|
||||||
<tr>
|
|
||||||
<td>{{ metricNames[x.code] ?? x.code }}</td>
|
|
||||||
<td class="num">{{ x.value | number: '1.2-2' }}</td>
|
|
||||||
<td class="num">{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}</td>
|
|
||||||
<td>{{ x.model ?? 'sin curva en producción' }}</td>
|
|
||||||
</tr>
|
|
||||||
} @empty {
|
|
||||||
<tr>
|
|
||||||
<td colspan="4" class="muted">Sin métricas (EEG no válido).</td>
|
|
||||||
</tr>
|
|
||||||
}
|
}
|
||||||
</tbody>
|
</ul>
|
||||||
</table>
|
<button
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
[disabled]="editing() || !actions.promote"
|
||||||
|
(click)="changeVersion(key, 'promote')"
|
||||||
|
>
|
||||||
|
Promover
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
[disabled]="editing() || !actions.retire"
|
||||||
|
(click)="changeVersion(key, 'retire')"
|
||||||
|
>
|
||||||
|
Retirar
|
||||||
|
</button>
|
||||||
|
} @else if (checks.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
} @else {
|
||||||
|
<p>Cargando…</p>
|
||||||
}
|
}
|
||||||
</div>
|
@if (message()) {
|
||||||
|
<p role="status">{{ message() }}</p>
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog #lineageDialog aria-label="Linaje" (close)="lineageFor.set(undefined)">
|
||||||
|
@if (lineageFor(); as key) {
|
||||||
|
<h3>Linaje · {{ key.name }} v{{ key.version }}</h3>
|
||||||
|
@if (lineage.hasValue()) {
|
||||||
|
@let details = lineage.value();
|
||||||
|
<h4>Parámetros</h4>
|
||||||
|
<dl>
|
||||||
|
@for (entry of details.params | keyvalue; track entry.key) {
|
||||||
|
<dt>{{ entry.key }}</dt>
|
||||||
|
<dd>{{ entry.value }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
<h4>Métricas</h4>
|
||||||
|
<dl>
|
||||||
|
@for (entry of details.metrics | keyvalue; track entry.key) {
|
||||||
|
<dt>{{ entry.key }}</dt>
|
||||||
|
<dd>{{ entry.value }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
<h4>Etiquetas</h4>
|
||||||
|
<dl>
|
||||||
|
@for (entry of details.tags | keyvalue; track entry.key) {
|
||||||
|
<dt>{{ entry.key }}</dt>
|
||||||
|
<dd>{{ entry.value }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
@if (details.imported; as imported) {
|
||||||
|
<h4>Importado de</h4>
|
||||||
|
<dl>
|
||||||
|
@for (entry of imported | keyvalue; track entry.key) {
|
||||||
|
<dt>{{ entry.key }}</dt>
|
||||||
|
<dd>{{ entry.value }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
} @else if (lineage.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
} @else {
|
||||||
|
<p>Cargando…</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog #bulkDialog aria-label="Promover candidatas">
|
||||||
|
<h3>Promover candidatas</h3>
|
||||||
|
<ul>
|
||||||
|
@for (candidate of candidates(); track candidate.name) {
|
||||||
|
<li>{{ candidate.name }} v{{ candidate.version }}</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<button
|
||||||
|
mat-flat-button
|
||||||
|
type="button"
|
||||||
|
[disabled]="editing()"
|
||||||
|
(click)="promoteCandidates(bulkDialog)"
|
||||||
|
>
|
||||||
|
Promover
|
||||||
|
</button>
|
||||||
|
<form method="dialog"><button mat-stroked-button>Cancelar</button></form>
|
||||||
|
</dialog>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,8 +1,18 @@
|
|||||||
:host {
|
:host {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
.subtitle {
|
h1 {
|
||||||
margin: 4px 0 var(--space-4);
|
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 {
|
.actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -20,7 +30,6 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
.badge {
|
.badge {
|
||||||
white-space: nowrap;
|
|
||||||
margin-left: var(--space-2);
|
margin-left: var(--space-2);
|
||||||
padding: 2px 8px;
|
padding: 2px 8px;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
@@ -36,32 +45,12 @@ td a {
|
|||||||
padding: 48px 0;
|
padding: 48px 0;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
.message {
|
||||||
.reports {
|
white-space: pre-line;
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
align-items: center;
|
|
||||||
column-gap: var(--space-3);
|
|
||||||
row-gap: 2px;
|
|
||||||
}
|
}
|
||||||
.reports a {
|
dialog {
|
||||||
margin-right: 0;
|
max-width: min(90vw, 64rem);
|
||||||
}
|
}
|
||||||
h2 .code {
|
dialog form {
|
||||||
font-size: 12px;
|
margin-top: var(--space-3);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { checkActions } from './gobernanza';
|
||||||
|
|
||||||
|
describe('version checks', () => {
|
||||||
|
it('enables promotion only when the API says the version is promotable', () => {
|
||||||
|
expect(checkActions({ status: 'candidate', promotable: false, checks: [] }).promote).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).promote).toBe(true);
|
||||||
|
expect(checkActions({ status: 'retired', promotable: false, checks: [] }).promote).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables retirement for the champion', () => {
|
||||||
|
expect(checkActions({ status: 'champion', promotable: true, checks: [] }).retire).toBe(false);
|
||||||
|
expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).retire).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
+320
-124
@@ -1,31 +1,35 @@
|
|||||||
import { METRIC_NAMES } from '../eeg-labels';
|
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
|
||||||
import { DatePipe, DecimalPipe } from '@angular/common';
|
|
||||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { RouterLink } from '@angular/router';
|
||||||
import { MatInputModule } from '@angular/material/input';
|
|
||||||
import { Api } from '../api/api';
|
import { Api } from '../api/api';
|
||||||
import { ApiConfiguration } from '../api/api-configuration';
|
|
||||||
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
|
||||||
import { analyze } from '../api/fn/models/analyze';
|
|
||||||
import { models } from '../api/fn/models/models';
|
|
||||||
import { promote } from '../api/fn/models/promote';
|
|
||||||
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 { studies } from '../api/fn/eeg/studies';
|
import { studies } from '../api/fn/eeg/studies';
|
||||||
import { study } from '../api/fn/eeg/study';
|
import { study } from '../api/fn/eeg/study';
|
||||||
import { terminateRun } from '../api/fn/runs/terminate-run';
|
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
||||||
import { runStatus } from '../api/fn/runs/run-status';
|
import { analyze } from '../api/fn/models/analyze';
|
||||||
|
import { curve } from '../api/fn/models/curve';
|
||||||
|
import { lineage } from '../api/fn/models/lineage';
|
||||||
|
import { models } from '../api/fn/models/models';
|
||||||
|
import { promote } from '../api/fn/models/promote';
|
||||||
|
import { readReport$Any } from '../api/fn/models/read-report-any';
|
||||||
|
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||||
|
import { retire } from '../api/fn/models/retire';
|
||||||
|
import { score } from '../api/fn/models/score';
|
||||||
|
import { versionChecks } from '../api/fn/models/version-checks';
|
||||||
|
import { versions } from '../api/fn/models/versions';
|
||||||
|
import { domains } from '../api/fn/operations/domains';
|
||||||
import type { Domain } from '../api/models/domain';
|
import type { Domain } from '../api/models/domain';
|
||||||
import type { Version } from '../api/models/version';
|
import type { Execution as Choice } from '../api/models/execution';
|
||||||
|
import type { Run } from '../api/models/run';
|
||||||
import { DOMAINS } from '../app';
|
import { DOMAINS } from '../app';
|
||||||
import { Plot } from '../plot';
|
import { Plot } from '../plot';
|
||||||
import { interpretabilityFigures } from './figures';
|
import { Bundles, download } from './bundles';
|
||||||
import { Loading } from '../loading';
|
import { Execution } from './execution';
|
||||||
|
import { interpretabilityFigures, studyPoints, type Centile } from './figures';
|
||||||
|
import { errorText, RunMonitor } from './run-monitor';
|
||||||
|
import { EegStudies } from './tea/studies';
|
||||||
|
import { Training } from './training';
|
||||||
|
|
||||||
const REPORTS: Record<string, string> = {
|
const REPORTS: Record<string, string> = {
|
||||||
technical_validation: 'Validación técnica',
|
technical_validation: 'Validación técnica',
|
||||||
@@ -33,34 +37,63 @@ const REPORTS: Record<string, string> = {
|
|||||||
clinical_validation: 'Validación clínica',
|
clinical_validation: 'Validación clínica',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Model governance for a domain: every model's versions with their metrics and reports,
|
interface VersionKey {
|
||||||
* the clinical validation the clinical team uploads, promotion (refused without the three
|
name: string;
|
||||||
* reports), and the training and scoring runs. */
|
version: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Checks {
|
||||||
|
status: 'candidate' | 'champion' | 'retired';
|
||||||
|
promotable: boolean;
|
||||||
|
checks: { report: string; present: boolean }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Lineage {
|
||||||
|
params: Record<string, string>;
|
||||||
|
metrics: Record<string, number>;
|
||||||
|
tags: Record<string, string>;
|
||||||
|
imported: Record<string, string> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkActions(checks: Checks) {
|
||||||
|
return { promote: checks.promotable, retire: checks.status !== 'champion' };
|
||||||
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-gobernanza',
|
selector: 'app-gobernanza',
|
||||||
imports: [
|
imports: [
|
||||||
Loading,
|
|
||||||
DatePipe,
|
DatePipe,
|
||||||
DecimalPipe,
|
DecimalPipe,
|
||||||
|
KeyValuePipe,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
MatFormFieldModule,
|
RouterLink,
|
||||||
MatInputModule,
|
|
||||||
Plot,
|
Plot,
|
||||||
|
Bundles,
|
||||||
|
Execution,
|
||||||
|
RunMonitor,
|
||||||
|
EegStudies,
|
||||||
|
Training,
|
||||||
],
|
],
|
||||||
templateUrl: './gobernanza.html',
|
templateUrl: './gobernanza.html',
|
||||||
styleUrl: './gobernanza.scss',
|
styleUrl: './gobernanza.scss',
|
||||||
})
|
})
|
||||||
export class Gobernanza {
|
export class Gobernanza {
|
||||||
private readonly api = inject(Api);
|
private readonly api = inject(Api);
|
||||||
private readonly root = inject(ApiConfiguration).rootUrl;
|
|
||||||
readonly domain = input.required<string>();
|
readonly domain = input.required<string>();
|
||||||
|
protected readonly domainKey = computed(() => this.domain() as Domain);
|
||||||
|
protected readonly execution = signal<Choice | undefined>(undefined);
|
||||||
protected readonly labels = DOMAINS as Record<string, string>;
|
protected readonly labels = DOMAINS as Record<string, string>;
|
||||||
protected readonly reportNames = REPORTS;
|
protected readonly reportNames = REPORTS;
|
||||||
private readonly refreshed = signal(0);
|
protected readonly errorText = errorText;
|
||||||
|
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||||
|
protected readonly refreshed = signal(0);
|
||||||
|
|
||||||
|
protected refresh(): void {
|
||||||
|
this.refreshed.update((value) => value + 1);
|
||||||
|
}
|
||||||
protected readonly models = resource({
|
protected readonly models = resource({
|
||||||
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
|
params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
|
||||||
loader: async ({ params: { domain } }) => {
|
loader: async ({ params: { domain } }) => {
|
||||||
const found = await this.api.invoke(models, { domain });
|
const found = await this.api.invoke(models, { domain });
|
||||||
return Promise.all(
|
return Promise.all(
|
||||||
@@ -72,136 +105,299 @@ export class Gobernanza {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
protected readonly chosen = signal<{ name: string; version: number } | undefined>(undefined);
|
protected readonly training = signal('');
|
||||||
|
protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>(
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
protected readonly starting = signal(false);
|
||||||
|
protected readonly running = signal(false);
|
||||||
|
protected readonly editing = signal(false);
|
||||||
|
protected readonly message = signal('');
|
||||||
|
protected readonly chosen = signal<VersionKey | undefined>(undefined);
|
||||||
|
protected readonly checksFor = signal<VersionKey | undefined>(undefined);
|
||||||
|
protected readonly lineageFor = signal<VersionKey | undefined>(undefined);
|
||||||
|
protected readonly checks = resource({
|
||||||
|
params: () => {
|
||||||
|
const key = this.checksFor();
|
||||||
|
return key ? { ...key, domain: this.domainKey(), at: this.refreshed() } : undefined;
|
||||||
|
},
|
||||||
|
loader: async ({ params: { at, ...params } }) => this.getChecks(params.domain, params),
|
||||||
|
});
|
||||||
|
protected readonly checkActions = checkActions;
|
||||||
|
protected readonly lineage = resource({
|
||||||
|
params: () => {
|
||||||
|
const key = this.lineageFor();
|
||||||
|
return key ? { ...key, domain: this.domainKey() } : undefined;
|
||||||
|
},
|
||||||
|
loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage,
|
||||||
|
});
|
||||||
|
protected readonly candidates = signal<VersionKey[]>([]);
|
||||||
protected readonly report = resource({
|
protected readonly report = resource({
|
||||||
params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain },
|
params: () => {
|
||||||
|
const key = this.chosen();
|
||||||
|
return key ? { ...key, domain: this.domainKey() } : undefined;
|
||||||
|
},
|
||||||
loader: ({ params }) =>
|
loader: ({ params }) =>
|
||||||
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
|
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
|
||||||
});
|
});
|
||||||
protected readonly figures = computed(() => {
|
protected readonly ageFeatures = computed<string[]>(() => {
|
||||||
const found = this.report.value();
|
const report = this.report.hasValue() ? this.report.value() : undefined;
|
||||||
return found ? interpretabilityFigures(found as Record<string, unknown>) : [];
|
return report?.kind === 'age_curves' ? Object.keys(report['curves']) : [];
|
||||||
});
|
});
|
||||||
/** TEA: its EEGs and their analysis. */
|
protected readonly selectedFeature = signal('');
|
||||||
protected readonly eegs = resource({
|
protected readonly feature = computed(() => {
|
||||||
params: () => (this.domain() === 'tea' ? this.refreshed() + 1 : undefined),
|
const keys = this.ageFeatures();
|
||||||
loader: () => this.api.invoke(studies),
|
return keys.includes(this.selectedFeature())
|
||||||
|
? this.selectedFeature()
|
||||||
|
: keys.includes('value')
|
||||||
|
? 'value'
|
||||||
|
: keys[0];
|
||||||
});
|
});
|
||||||
protected readonly eeg = signal<string | undefined>(undefined);
|
protected readonly band = resource({
|
||||||
protected readonly eegMetrics = resource({
|
params: () => {
|
||||||
params: () => this.eeg(),
|
const key = this.chosen();
|
||||||
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
|
const feature = this.feature();
|
||||||
|
if (!key || !feature || !this.report.hasValue()) return undefined;
|
||||||
|
if (this.report.value()['curves'][feature].kind === 'count_rate') return undefined;
|
||||||
|
return { ...key, domain: this.domainKey(), feature };
|
||||||
|
},
|
||||||
|
loader: async ({ params }) => (await this.api.invoke(curve, params)) as Centile[],
|
||||||
});
|
});
|
||||||
protected readonly metricNames = METRIC_NAMES;
|
protected readonly overlay = signal(false);
|
||||||
protected readonly asOf = signal('');
|
protected readonly analysed = resource({
|
||||||
protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
|
params: () =>
|
||||||
undefined,
|
this.overlay() && this.domainKey() === 'tea' && this.feature()
|
||||||
|
? this.refreshed() + 1
|
||||||
|
: undefined,
|
||||||
|
loader: async () => {
|
||||||
|
const found = await this.api.invoke(studies);
|
||||||
|
return Promise.all(
|
||||||
|
found
|
||||||
|
.filter((entry) => entry.analysed)
|
||||||
|
.map(({ id }) => this.api.invoke(study, { eeg_id: id })),
|
||||||
);
|
);
|
||||||
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
|
},
|
||||||
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
|
});
|
||||||
protected readonly running = computed(() => {
|
protected readonly figures = computed(() => {
|
||||||
const r = this.run();
|
if (!this.report.hasValue()) return [];
|
||||||
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
|
const report = this.report.value();
|
||||||
|
const feature = this.feature();
|
||||||
|
const points =
|
||||||
|
this.analysed.hasValue() && feature
|
||||||
|
? studyPoints(this.analysed.value(), report['model'], feature)
|
||||||
|
: [];
|
||||||
|
return interpretabilityFigures(report, {
|
||||||
|
feature,
|
||||||
|
centiles: this.band.hasValue() ? this.band.value() : undefined,
|
||||||
|
points,
|
||||||
|
waitForCentiles: report['kind'] === 'age_curves',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
protected readonly STATUS: Record<string, string> = {
|
|
||||||
QUEUED: 'en cola',
|
|
||||||
NOT_STARTED: 'por iniciar',
|
|
||||||
STARTING: 'iniciando',
|
|
||||||
STARTED: 'en curso',
|
|
||||||
SUCCESS: 'terminado',
|
|
||||||
FAILURE: 'con error',
|
|
||||||
CANCELING: 'deteniéndose',
|
|
||||||
CANCELED: 'detenido',
|
|
||||||
};
|
|
||||||
/** A model's title by its name, for messages. */
|
|
||||||
protected titleOf(name: string): string {
|
|
||||||
return this.models.value()?.find((m) => m.name === name)?.title ?? name;
|
|
||||||
}
|
|
||||||
/** What a version learned from, as its metrics say it (each kind of model its own). */
|
|
||||||
protected sizes(v: Version): string {
|
|
||||||
const m = v.metrics;
|
|
||||||
const n = (x: number) => x.toLocaleString('es-MX');
|
|
||||||
if (m['n_train'] !== undefined)
|
|
||||||
return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`;
|
|
||||||
if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`;
|
|
||||||
if (m['children'] !== undefined) return `${n(m['children'])} niños`;
|
|
||||||
const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox'));
|
|
||||||
if (c) return `C-index ${c[1].toFixed(3)}`;
|
|
||||||
return '—';
|
|
||||||
}
|
|
||||||
protected readonly message = signal('');
|
|
||||||
|
|
||||||
protected champion(v: Version): boolean {
|
constructor() {
|
||||||
return v.aliases.includes('champion');
|
effect(() => {
|
||||||
|
this.domain();
|
||||||
|
this.training.set('');
|
||||||
|
this.run.set(undefined);
|
||||||
|
this.running.set(false);
|
||||||
|
this.starting.set(false);
|
||||||
|
this.editing.set(false);
|
||||||
|
this.message.set('');
|
||||||
|
this.chosen.set(undefined);
|
||||||
|
this.checksFor.set(undefined);
|
||||||
|
this.lineageFor.set(undefined);
|
||||||
|
this.overlay.set(false);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected reportUrl(name: string, version: number, report: string): string {
|
protected async reportDownload(name: string, version: number, report: string): Promise<void> {
|
||||||
return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`;
|
try {
|
||||||
|
const response = await this.api.invoke$Response(readReport$Any, {
|
||||||
|
domain: this.domainKey(),
|
||||||
|
name,
|
||||||
|
version,
|
||||||
|
report,
|
||||||
|
});
|
||||||
|
const filename = /filename="([^"]+)"/.exec(
|
||||||
|
response.headers.get('Content-Disposition') ?? '',
|
||||||
|
)?.[1];
|
||||||
|
download(response.body, filename ?? report);
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async upload(name: string, version: number, event: Event): Promise<void> {
|
protected async upload(name: string, version: number, event: Event): Promise<void> {
|
||||||
const file = (event.target as HTMLInputElement).files?.[0];
|
const input = event.target as HTMLInputElement;
|
||||||
|
const file = input.files?.[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
|
const domain = this.domainKey();
|
||||||
|
try {
|
||||||
await this.api.invoke(addClinicalValidation, {
|
await this.api.invoke(addClinicalValidation, {
|
||||||
domain: this.domain() as Domain,
|
domain,
|
||||||
name,
|
name,
|
||||||
version,
|
version,
|
||||||
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
|
|
||||||
body: { file: file as unknown as string },
|
body: { file: file as unknown as string },
|
||||||
});
|
});
|
||||||
this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
|
input.value = '';
|
||||||
this.refreshed.update((n) => n + 1);
|
if (domain !== this.domainKey()) return;
|
||||||
|
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
|
||||||
|
this.refresh();
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async promote(name: string, version: number): Promise<void> {
|
protected showVersion(
|
||||||
|
kind: 'checks' | 'lineage',
|
||||||
|
key: VersionKey,
|
||||||
|
dialog: HTMLDialogElement,
|
||||||
|
): void {
|
||||||
|
(kind === 'checks' ? this.checksFor : this.lineageFor).set(key);
|
||||||
|
dialog.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise<void> {
|
||||||
|
const domain = this.domainKey();
|
||||||
|
this.editing.set(true);
|
||||||
|
this.message.set('');
|
||||||
try {
|
try {
|
||||||
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
|
if (action === 'promote') await this.api.invoke(promote, { domain, ...key });
|
||||||
this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
|
else await this.api.invoke(retire, { domain, ...key });
|
||||||
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(
|
this.message.set(
|
||||||
missing
|
`${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`,
|
||||||
? `No se promovió: faltan informes (${missing
|
|
||||||
.split(', ')
|
|
||||||
.map((r) => this.reportNames[r] ?? r)
|
|
||||||
.join(', ')}).`
|
|
||||||
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
|
|
||||||
);
|
);
|
||||||
|
this.refresh();
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.editing.set(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async analyzeEegs(): Promise<void> {
|
protected async prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
|
||||||
const { run_id } = await this.api.invoke(analyze, { domain: this.domain() as Domain });
|
if (!this.models.hasValue()) return;
|
||||||
await this.follow(run_id, 'Análisis de EEG');
|
const domain = this.domainKey();
|
||||||
|
this.editing.set(true);
|
||||||
|
this.message.set('');
|
||||||
|
try {
|
||||||
|
const latest = this.models.value().flatMap(({ name, versions }) => {
|
||||||
|
const newest = versions.reduce<(typeof versions)[number] | undefined>(
|
||||||
|
(current, version) => (!current || version.version > current.version ? version : current),
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
return newest?.status === 'candidate' ? [{ name, version: newest.version }] : [];
|
||||||
|
});
|
||||||
|
const allowed = await Promise.all(
|
||||||
|
latest.map(async (key) => (await this.getChecks(domain, key)).promotable),
|
||||||
|
);
|
||||||
|
if (domain !== this.domainKey()) return;
|
||||||
|
const found = latest.filter((_, index) => allowed[index]);
|
||||||
|
this.candidates.set(found);
|
||||||
|
if (found.length) dialog.showModal();
|
||||||
|
else this.message.set('No hay candidatas que se puedan promover.');
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.editing.set(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async follow(run_id: string, label: string): Promise<void> {
|
protected async promoteCandidates(dialog: HTMLDialogElement): Promise<void> {
|
||||||
for (;;) {
|
this.editing.set(true);
|
||||||
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
|
this.message.set('');
|
||||||
this.run.set({ id: run_id, kind: label, status });
|
try {
|
||||||
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
|
await this.promoteVersions(this.domainKey(), this.candidates());
|
||||||
await new Promise((r) => setTimeout(r, 2000));
|
dialog.close();
|
||||||
|
} finally {
|
||||||
|
this.editing.set(false);
|
||||||
}
|
}
|
||||||
this.refreshed.update((n) => n + 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async stop(): Promise<void> {
|
protected forestHeight(rows: number): number {
|
||||||
const r = this.run();
|
return Math.max(360, rows * 24 + 72);
|
||||||
if (!r) return;
|
|
||||||
const found = await this.api.invoke(terminateRun, { run_id: r.id });
|
|
||||||
this.run.set({ ...r, status: found['status'] });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async start(kind: 'train' | 'score'): Promise<void> {
|
protected chooseReport(key: VersionKey): void {
|
||||||
this.confirming.set(undefined);
|
this.overlay.set(false);
|
||||||
const domain = this.domain() as Domain;
|
this.selectedFeature.set('');
|
||||||
|
this.chosen.set(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected follow(id: string, label: string, autoPromote = false): void {
|
||||||
|
this.message.set('');
|
||||||
|
this.run.set({ id, label, autoPromote });
|
||||||
|
this.running.set(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async start(kind: 'score' | 'analyze'): Promise<void> {
|
||||||
|
const domain = this.domainKey();
|
||||||
|
this.starting.set(true);
|
||||||
|
this.message.set('');
|
||||||
|
try {
|
||||||
const { run_id } =
|
const { run_id } =
|
||||||
kind === 'train'
|
kind === 'score'
|
||||||
? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} })
|
? await this.api.invoke(score, { domain })
|
||||||
: await this.api.invoke(score, { domain });
|
: await this.api.invoke(analyze, { domain, body: { execution: this.execution() } });
|
||||||
await this.follow(run_id, kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos');
|
if (domain === this.domainKey())
|
||||||
|
this.follow(run_id, kind === 'score' ? 'Cálculo de riesgos' : 'Análisis de EEG');
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.starting.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async finish(run: Run): Promise<void> {
|
||||||
|
const domain = this.domainKey();
|
||||||
|
const active = this.run();
|
||||||
|
if (active?.id !== run.id) return;
|
||||||
|
try {
|
||||||
|
if (!active.autoPromote) return;
|
||||||
|
if (run.state !== 'succeeded') {
|
||||||
|
this.message.set('No se promovió: el entrenamiento no terminó correctamente.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const newVersions = run.info.flatMap((line) => {
|
||||||
|
const match = /^train_models: tea\.(.+): version (\d+)$/.exec(line);
|
||||||
|
return match ? [{ name: match[1], version: Number(match[2]) }] : [];
|
||||||
|
});
|
||||||
|
if (newVersions.length) await this.promoteVersions(domain, newVersions);
|
||||||
|
else this.message.set('No se promovió: el entrenamiento no registró versiones nuevas.');
|
||||||
|
} finally {
|
||||||
|
if (domain === this.domainKey() && this.run()?.id === run.id) {
|
||||||
|
this.refresh();
|
||||||
|
this.running.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getChecks(domain: Domain, key: VersionKey): Promise<Checks> {
|
||||||
|
return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise<void> {
|
||||||
|
const messages = await Promise.all(
|
||||||
|
keys.map(async (key) => {
|
||||||
|
const label = `${key.name} v${key.version}`;
|
||||||
|
try {
|
||||||
|
const checks = await this.getChecks(domain, key);
|
||||||
|
if (!checks.promotable) {
|
||||||
|
const missing = checks.checks
|
||||||
|
.filter((check) => !check.present)
|
||||||
|
.map((check) => REPORTS[check.report] ?? check.report);
|
||||||
|
const reason = missing.length ? `faltan ${missing.join(', ')}` : checks.status;
|
||||||
|
return `No se promovió ${label}: ${reason}.`;
|
||||||
|
}
|
||||||
|
await this.api.invoke(promote, { domain, ...key });
|
||||||
|
return `${label}: en producción.`;
|
||||||
|
} catch (error) {
|
||||||
|
return `No se promovió ${label}: ${errorText(error)}`;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
if (domain !== this.domainKey()) return;
|
||||||
|
this.message.set(messages.join('\n'));
|
||||||
|
this.refresh();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
|
import { Api } from '../api/api';
|
||||||
|
import { cancelRun } from '../api/fn/runs/cancel-run';
|
||||||
|
import { runStatus } from '../api/fn/runs/run-status';
|
||||||
|
import type { Progress } from '../api/models/progress';
|
||||||
|
import type { Run } from '../api/models/run';
|
||||||
|
import { eta, RunMonitor } from './run-monitor';
|
||||||
|
|
||||||
|
const progress: Progress = {
|
||||||
|
done: 4,
|
||||||
|
total: 10,
|
||||||
|
mode: 'local',
|
||||||
|
phase: 'training',
|
||||||
|
elapsed_s: 20,
|
||||||
|
eta_s: null,
|
||||||
|
scheduler: null,
|
||||||
|
updated_at: '2026-11-30T12:00:00Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
function run(state: Run['state']): Run {
|
||||||
|
return {
|
||||||
|
id: 'run-1',
|
||||||
|
domain: 'tea',
|
||||||
|
job: 'train',
|
||||||
|
status: state,
|
||||||
|
state,
|
||||||
|
info: [],
|
||||||
|
warnings: [],
|
||||||
|
steps: [],
|
||||||
|
error: null,
|
||||||
|
progress,
|
||||||
|
started: null,
|
||||||
|
ended: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function render(fixture: ComponentFixture<RunMonitor>): Promise<void> {
|
||||||
|
fixture.detectChanges();
|
||||||
|
await Promise.resolve();
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('run monitor', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const state of ['succeeded', 'failed', 'cancelled'] as const) {
|
||||||
|
it('stops polling after ' + state, async () => {
|
||||||
|
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||||
|
const invoke = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(run('running'))
|
||||||
|
.mockResolvedValueOnce(run(state));
|
||||||
|
TestBed.configureTestingModule({ providers: [{ provide: Api, useValue: { invoke } }] });
|
||||||
|
const fixture = TestBed.createComponent(RunMonitor);
|
||||||
|
fixture.componentRef.setInput('runId', 'run-1');
|
||||||
|
const finished = vi.fn();
|
||||||
|
fixture.componentInstance.finished.subscribe(finished);
|
||||||
|
|
||||||
|
await render(fixture);
|
||||||
|
expect(invoke).toHaveBeenCalledExactlyOnceWith(runStatus, { run_id: 'run-1' });
|
||||||
|
await vi.advanceTimersByTimeAsync(1999);
|
||||||
|
expect(invoke).toHaveBeenCalledTimes(1);
|
||||||
|
await vi.advanceTimersByTimeAsync(1);
|
||||||
|
expect(finished).toHaveBeenCalledExactlyOnceWith(run(state));
|
||||||
|
await vi.advanceTimersByTimeAsync(6000);
|
||||||
|
expect(invoke).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it('estimates seconds remaining from observed throughput', () => {
|
||||||
|
expect(eta(progress)).toBe(30);
|
||||||
|
expect(eta({ ...progress, done: 0 })).toBeNull();
|
||||||
|
expect(eta({ ...progress, done: 10 })).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requests cancellation and displays the conflict detail', async () => {
|
||||||
|
const invoke = vi.fn(async (endpoint: unknown) => {
|
||||||
|
if (endpoint === cancelRun) {
|
||||||
|
throw new HttpErrorResponse({
|
||||||
|
status: 409,
|
||||||
|
error: { detail: 'the run is still starting; try again' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return run('running');
|
||||||
|
});
|
||||||
|
TestBed.configureTestingModule({ providers: [{ provide: Api, useValue: { invoke } }] });
|
||||||
|
const fixture = TestBed.createComponent(RunMonitor);
|
||||||
|
fixture.componentRef.setInput('runId', 'run-1');
|
||||||
|
await render(fixture);
|
||||||
|
|
||||||
|
const cancel: HTMLButtonElement = fixture.nativeElement.querySelector('button');
|
||||||
|
cancel.click();
|
||||||
|
await render(fixture);
|
||||||
|
expect(invoke).toHaveBeenCalledWith(cancelRun, { run_id: 'run-1' });
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('the run is still starting; try again');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { DecimalPipe, KeyValuePipe } from '@angular/common';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { Component, effect, inject, input, output, signal } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { Api } from '../api/api';
|
||||||
|
import { cancelRun } from '../api/fn/runs/cancel-run';
|
||||||
|
import { runStatus } from '../api/fn/runs/run-status';
|
||||||
|
import type { Progress } from '../api/models/progress';
|
||||||
|
import type { Run } from '../api/models/run';
|
||||||
|
|
||||||
|
export function errorText(error: unknown): string {
|
||||||
|
if (error instanceof HttpErrorResponse) {
|
||||||
|
const detail = error.error?.detail ?? error.error;
|
||||||
|
return typeof detail === 'string' ? detail : detail ? JSON.stringify(detail) : error.message;
|
||||||
|
}
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function eta(progress: Progress): number | null {
|
||||||
|
return progress.done > 0 && progress.total > 0
|
||||||
|
? (Math.max(0, progress.total - progress.done) * progress.elapsed_s) / progress.done
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-run-monitor',
|
||||||
|
imports: [DecimalPipe, KeyValuePipe, MatButtonModule],
|
||||||
|
template: `
|
||||||
|
<section aria-label="Monitor de ejecución">
|
||||||
|
@if (run(); as r) {
|
||||||
|
<p role="status">{{ r.status }}</p>
|
||||||
|
@for (step of r.steps; track step.key) {
|
||||||
|
<div>{{ step.key }} · {{ step.status }}</div>
|
||||||
|
}
|
||||||
|
@if (r.progress; as p) {
|
||||||
|
<div>
|
||||||
|
{{ p.phase }} · {{ p.done }} / {{ p.total }}
|
||||||
|
@if (p.total > 0) {
|
||||||
|
({{ (100 * p.done) / p.total | number: '1.0-0' }} %)
|
||||||
|
<progress [value]="p.done" [max]="p.total"></progress>
|
||||||
|
}
|
||||||
|
@if (eta(p) !== null) {
|
||||||
|
· ETA {{ eta(p) | number: '1.0-0' }} s
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@for (worker of p.workers ?? []; track worker.name) {
|
||||||
|
<div>
|
||||||
|
{{ worker.name }} · CPU {{ worker.cpu_pct | number: '1.0-1' }} % · RAM
|
||||||
|
{{ worker.memory_bytes / 1048576 | number: '1.0-1' }} MiB
|
||||||
|
@if (worker.memory_limit != null) {
|
||||||
|
/ {{ worker.memory_limit / 1048576 | number: '1.0-1' }} MiB
|
||||||
|
}
|
||||||
|
· Tareas activas: {{ worker.executing }}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@for (task of p.tasks | keyvalue; track task.key) {
|
||||||
|
<div>{{ task.key }}: {{ task.value }}</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (r.info.length) {
|
||||||
|
<h4>Información</h4>
|
||||||
|
<ul>
|
||||||
|
@for (line of r.info; track $index) {
|
||||||
|
<li>{{ line }}</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (r.warnings.length) {
|
||||||
|
<h4>Advertencias</h4>
|
||||||
|
<ul>
|
||||||
|
@for (line of r.warnings; track $index) {
|
||||||
|
<li>{{ line }}</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (r.error) {
|
||||||
|
<p role="alert">{{ r.error }}</p>
|
||||||
|
}
|
||||||
|
@if (!terminal.has(r.state)) {
|
||||||
|
<button
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
[disabled]="cancelling() || r.state === 'cancelling'"
|
||||||
|
(click)="cancel()"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<p role="status">Consultando ejecución…</p>
|
||||||
|
}
|
||||||
|
@if (pollError()) {
|
||||||
|
<p role="alert">{{ pollError() }}</p>
|
||||||
|
}
|
||||||
|
@if (cancelError()) {
|
||||||
|
<p role="alert">{{ cancelError() }}</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class RunMonitor {
|
||||||
|
private readonly api = inject(Api);
|
||||||
|
readonly runId = input.required<string>();
|
||||||
|
readonly finished = output<Run>();
|
||||||
|
protected readonly run = signal<Run | undefined>(undefined);
|
||||||
|
protected readonly pollError = signal('');
|
||||||
|
protected readonly cancelError = signal('');
|
||||||
|
protected readonly cancelling = signal(false);
|
||||||
|
protected readonly terminal = new Set<Run['state']>(['succeeded', 'failed', 'cancelled']);
|
||||||
|
protected readonly eta = eta;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect((cleanup) => {
|
||||||
|
const run_id = this.runId();
|
||||||
|
this.run.set(undefined);
|
||||||
|
this.pollError.set('');
|
||||||
|
this.cancelError.set('');
|
||||||
|
this.cancelling.set(false);
|
||||||
|
let active = true;
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const run = await this.api.invoke(runStatus, { run_id });
|
||||||
|
if (!active) return;
|
||||||
|
this.run.set(run);
|
||||||
|
this.pollError.set('');
|
||||||
|
if (this.terminal.has(run.state)) {
|
||||||
|
this.finished.emit(run);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (!active) return;
|
||||||
|
this.pollError.set(errorText(error));
|
||||||
|
}
|
||||||
|
timer = setTimeout(poll, 2000);
|
||||||
|
};
|
||||||
|
void poll();
|
||||||
|
cleanup(() => {
|
||||||
|
active = false;
|
||||||
|
clearTimeout(timer);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async cancel(): Promise<void> {
|
||||||
|
const run_id = this.runId();
|
||||||
|
this.cancelling.set(true);
|
||||||
|
this.cancelError.set('');
|
||||||
|
try {
|
||||||
|
const { state, status } = await this.api.invoke(cancelRun, { run_id });
|
||||||
|
if (this.runId() === run_id) {
|
||||||
|
this.run.update((run) =>
|
||||||
|
run && !this.terminal.has(run.state) && !this.terminal.has(state)
|
||||||
|
? { ...run, state, status }
|
||||||
|
: run,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (this.runId() === run_id) this.cancelError.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
if (this.runId() === run_id) this.cancelling.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { PreviewResult } from '../../api/models/preview-result';
|
||||||
|
import { previewPdfContent, previewPdfName } from './preview-pdf';
|
||||||
|
|
||||||
|
const score = { z: 2.1, p5: 1, median: 2, p95: 3, outside: 1 };
|
||||||
|
|
||||||
|
const result: PreviewResult = {
|
||||||
|
eeg: {
|
||||||
|
valid: true,
|
||||||
|
level: 'complete',
|
||||||
|
recorded_on: '2026-01-10',
|
||||||
|
age_months: 24,
|
||||||
|
clean_fraction: 0.9,
|
||||||
|
bad_channels: 0,
|
||||||
|
channels: 19,
|
||||||
|
duration_min: 20,
|
||||||
|
line_noise_db: 3,
|
||||||
|
sleep: true,
|
||||||
|
error: null,
|
||||||
|
checks: [
|
||||||
|
{ code: 'duration', value: 20, unit: 'min', low: 10, high: null, abnormal: false },
|
||||||
|
{ code: 'flat', electrode: 'O1', text: 'plano', abnormal: true },
|
||||||
|
],
|
||||||
|
metrics: [
|
||||||
|
{
|
||||||
|
code: 'posterior_rhythm',
|
||||||
|
value: 6.5,
|
||||||
|
model: 'tea.eeg-posterior-rhythm/1',
|
||||||
|
score,
|
||||||
|
electrodes: { O1: { value: 6.4, score: null } },
|
||||||
|
zones: { occipital: { value: 6.6, score } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
ados2: {
|
||||||
|
module: 'module_1',
|
||||||
|
evaluation_date: '2026-01-12',
|
||||||
|
items: { pointing: 2, gestures: null, intonation: null, ignoring: 1 },
|
||||||
|
titles: { pointing: 'A-7 Señalar', gestures: 'A-8 Gestos' },
|
||||||
|
css: 7,
|
||||||
|
classification: 'autism',
|
||||||
|
read: ['module', 'pointing'],
|
||||||
|
},
|
||||||
|
warnings: ['sin curva en producción para spindles_n2'],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('previewPdfContent', () => {
|
||||||
|
it('prints the verdict, checks, scored metrics, ADOS-2 items by title and warnings', () => {
|
||||||
|
expect(previewPdfContent(result)).toEqual([
|
||||||
|
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
|
||||||
|
'complete · Válido',
|
||||||
|
{ text: 'Comprobaciones', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
|
||||||
|
{
|
||||||
|
layout: 'lightHorizontalLines',
|
||||||
|
table: {
|
||||||
|
headerRows: 1,
|
||||||
|
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
|
||||||
|
body: [
|
||||||
|
['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'],
|
||||||
|
['duration', '—', '20 min', '10 / —', 'No'],
|
||||||
|
['flat', 'O1', 'plano', '— / —', 'Sí'],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ text: 'Métricas', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
|
||||||
|
{
|
||||||
|
layout: 'lightHorizontalLines',
|
||||||
|
table: {
|
||||||
|
headerRows: 1,
|
||||||
|
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
|
||||||
|
body: [
|
||||||
|
['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'],
|
||||||
|
['posterior_rhythm', '6.5', '2.1', '1 / 2 / 3', '1'],
|
||||||
|
['posterior_rhythm · O1', '6.4', '—', '— / — / —', '—'],
|
||||||
|
['posterior_rhythm · occipital', '6.6', '2.1', '1 / 2 / 3', '1'],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ text: 'ADOS-2', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
|
||||||
|
'autism · CSS 7',
|
||||||
|
{
|
||||||
|
layout: 'lightHorizontalLines',
|
||||||
|
table: {
|
||||||
|
headerRows: 1,
|
||||||
|
widths: ['*', 'auto'],
|
||||||
|
body: [
|
||||||
|
['Ítem', 'Puntuación'],
|
||||||
|
['A-7 Señalar', '2'],
|
||||||
|
['A-8 Gestos', '—'],
|
||||||
|
['ignoring', '1'],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ text: 'Advertencias', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
|
||||||
|
{ ul: ['sin curva en producción para spindles_n2'] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks an invalid study with its error and no ADOS-2 or warnings', () => {
|
||||||
|
const content = previewPdfContent({
|
||||||
|
eeg: { ...result.eeg, valid: false, error: 'sin canales', checks: [], metrics: [] },
|
||||||
|
ados2: null,
|
||||||
|
warnings: [],
|
||||||
|
});
|
||||||
|
expect(content).toEqual([
|
||||||
|
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
|
||||||
|
'complete · No válido',
|
||||||
|
'sin canales',
|
||||||
|
{ text: 'Comprobaciones', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
|
||||||
|
'—',
|
||||||
|
{ text: 'Métricas', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
|
||||||
|
'—',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names the file by domain, page and day only', () => {
|
||||||
|
expect(previewPdfName(new Date('2026-11-30T12:00:00Z'))).toBe('tea-gobernanza-2026-11-30');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { downloadPdf, type PdfContent } from '../../export/pdf';
|
||||||
|
import { safeName } from '../../export/safe-name';
|
||||||
|
import type { PreviewResult } from '../../api/models/preview-result';
|
||||||
|
import type { Score } from '../../api/models/score';
|
||||||
|
|
||||||
|
function shown(value: unknown): string {
|
||||||
|
return value == null || value === '' ? '—' : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function yesNo(value: unknown): string {
|
||||||
|
return value === true ? 'Sí' : value === false ? 'No' : '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function verdict(valid: boolean | null): string {
|
||||||
|
return valid === true ? 'Válido' : valid === false ? 'No válido' : '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function scoreCells(score: Score | null): string[] {
|
||||||
|
return [
|
||||||
|
shown(score?.z),
|
||||||
|
`${shown(score?.p5)} / ${shown(score?.median)} / ${shown(score?.p95)}`,
|
||||||
|
shown(score?.outside),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function table(headers: string[], rows: string[][]): PdfContent {
|
||||||
|
if (!rows.length) return '—';
|
||||||
|
return {
|
||||||
|
layout: 'lightHorizontalLines',
|
||||||
|
table: {
|
||||||
|
headerRows: 1,
|
||||||
|
widths: ['*', ...headers.slice(1).map(() => 'auto' as const)],
|
||||||
|
body: [headers, ...rows],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function heading(text: string): PdfContent {
|
||||||
|
return { text, bold: true, fontSize: 14, margin: [0, 12, 0, 5] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function previewPdfName(day = new Date()): string {
|
||||||
|
return safeName(['tea', 'gobernanza', day.toISOString().slice(0, 10)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function previewPdfContent(result: PreviewResult): PdfContent[] {
|
||||||
|
const { eeg, ados2, warnings } = result;
|
||||||
|
const content: PdfContent[] = [
|
||||||
|
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
|
||||||
|
`${eeg.level} · ${verdict(eeg.valid)}`,
|
||||||
|
];
|
||||||
|
if (eeg.error) content.push(eeg.error);
|
||||||
|
|
||||||
|
content.push(
|
||||||
|
heading('Comprobaciones'),
|
||||||
|
table(
|
||||||
|
['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'],
|
||||||
|
eeg.checks.map((check) => [
|
||||||
|
shown(check['code']),
|
||||||
|
shown(check['electrode']),
|
||||||
|
`${shown(check['value'] ?? check['text'])}${check['unit'] ? ' ' + check['unit'] : ''}`,
|
||||||
|
`${shown(check['low'])} / ${shown(check['high'])}`,
|
||||||
|
yesNo(check['abnormal']),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
content.push(
|
||||||
|
heading('Métricas'),
|
||||||
|
table(
|
||||||
|
['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'],
|
||||||
|
eeg.metrics.flatMap((metric) => [
|
||||||
|
[metric.code, shown(metric.value), ...scoreCells(metric.score)],
|
||||||
|
...[...Object.entries(metric.electrodes), ...Object.entries(metric.zones)].map(
|
||||||
|
([site, value]) => [
|
||||||
|
`${metric.code} · ${site}`,
|
||||||
|
shown(value.value),
|
||||||
|
...scoreCells(value.score),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ados2) {
|
||||||
|
content.push(
|
||||||
|
heading('ADOS-2'),
|
||||||
|
`${shown(ados2.classification)} · CSS ${shown(ados2.css)}`,
|
||||||
|
table(
|
||||||
|
['Ítem', 'Puntuación'],
|
||||||
|
Object.entries(ados2.items)
|
||||||
|
.filter(([field, value]) => field in ados2.titles || value != null)
|
||||||
|
.map(([field, value]) => [ados2.titles[field] ?? field, shown(value)]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (warnings.length) content.push(heading('Advertencias'), { ul: [...warnings] });
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function downloadPreviewPdf(result: PreviewResult): Promise<void> {
|
||||||
|
return downloadPdf(previewPdfName(), previewPdfContent(result));
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import { KeyValuePipe } from '@angular/common';
|
||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { Api } from '../../api/api';
|
||||||
|
import { previewStatus } from '../../api/fn/preview/preview-status';
|
||||||
|
import { startPreview } from '../../api/fn/preview/start-preview';
|
||||||
|
import type { PreviewResult } from '../../api/models/preview-result';
|
||||||
|
import type { Run } from '../../api/models/run';
|
||||||
|
import { RunMonitor, errorText } from '../run-monitor';
|
||||||
|
import { downloadPreviewPdf } from './preview-pdf';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-eeg-preview',
|
||||||
|
imports: [FormsModule, KeyValuePipe, MatButtonModule, RunMonitor],
|
||||||
|
template: `
|
||||||
|
<section>
|
||||||
|
<h3>Vista previa</h3>
|
||||||
|
<form (ngSubmit)="start(edf.files?.[0], ados.files?.[0], birth.value)">
|
||||||
|
<label>EDF <input #edf type="file" accept=".edf" required /></label>
|
||||||
|
<label>ADOS-2 (PDF) <input #ados type="file" accept=".pdf" /></label>
|
||||||
|
<label>Fecha de nacimiento <input #birth type="date" /></label>
|
||||||
|
<button mat-stroked-button type="submit" [disabled]="busy()">Vista previa</button>
|
||||||
|
</form>
|
||||||
|
@if (error()) {
|
||||||
|
<p role="alert">{{ error() }}</p>
|
||||||
|
}
|
||||||
|
@if (runId(); as id) {
|
||||||
|
<app-run-monitor [runId]="id" (finished)="finish($event, dialog)" />
|
||||||
|
}
|
||||||
|
<dialog #dialog aria-label="Vista previa del estudio">
|
||||||
|
@if (result(); as r) {
|
||||||
|
<h3>Resultado de la vista previa</h3>
|
||||||
|
<p>
|
||||||
|
{{ r.eeg.level }} ·
|
||||||
|
{{ r.eeg.valid === true ? 'Válido' : r.eeg.valid === false ? 'No válido' : '—' }}
|
||||||
|
</p>
|
||||||
|
@if (r.eeg.error) {
|
||||||
|
<p role="alert">{{ r.eeg.error }}</p>
|
||||||
|
}
|
||||||
|
<h4>Comprobaciones</h4>
|
||||||
|
<table class="plain">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Comprobación</th>
|
||||||
|
<th>Electrodo</th>
|
||||||
|
<th>Resultado</th>
|
||||||
|
<th>Rango</th>
|
||||||
|
<th>Anormal</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (check of r.eeg.checks; track $index) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ check['code'] }}</td>
|
||||||
|
<td>{{ check['electrode'] ?? '—' }}</td>
|
||||||
|
<td>{{ check['value'] ?? check['text'] ?? '—' }} {{ check['unit'] }}</td>
|
||||||
|
<td>{{ check['low'] ?? '—' }} / {{ check['high'] ?? '—' }}</td>
|
||||||
|
<td>
|
||||||
|
{{
|
||||||
|
check['abnormal'] === true ? 'Sí' : check['abnormal'] === false ? 'No' : '—'
|
||||||
|
}}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<h4>Métricas</h4>
|
||||||
|
<table class="plain">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Métrica</th>
|
||||||
|
<th>Valor</th>
|
||||||
|
<th>z</th>
|
||||||
|
<th>p5 / mediana / p95</th>
|
||||||
|
<th>Fuera de rango</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (metric of r.eeg.metrics; track metric.code) {
|
||||||
|
<tr>
|
||||||
|
<th>{{ metric.code }}</th>
|
||||||
|
<td>{{ metric.value ?? '—' }}</td>
|
||||||
|
<td>{{ metric.score?.z ?? '—' }}</td>
|
||||||
|
<td>
|
||||||
|
{{ metric.score?.p5 ?? '—' }} / {{ metric.score?.median ?? '—' }} /
|
||||||
|
{{ metric.score?.p95 ?? '—' }}
|
||||||
|
</td>
|
||||||
|
<td>{{ metric.score?.outside ?? '—' }}</td>
|
||||||
|
</tr>
|
||||||
|
@for (site of metric.electrodes | keyvalue; track site.key) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ site.key }}</td>
|
||||||
|
<td>{{ site.value.value ?? '—' }}</td>
|
||||||
|
<td>{{ site.value.score?.z ?? '—' }}</td>
|
||||||
|
<td>
|
||||||
|
{{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} /
|
||||||
|
{{ site.value.score?.p95 ?? '—' }}
|
||||||
|
</td>
|
||||||
|
<td>{{ site.value.score?.outside ?? '—' }}</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
@for (site of metric.zones | keyvalue; track site.key) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ site.key }}</td>
|
||||||
|
<td>{{ site.value.value ?? '—' }}</td>
|
||||||
|
<td>{{ site.value.score?.z ?? '—' }}</td>
|
||||||
|
<td>
|
||||||
|
{{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} /
|
||||||
|
{{ site.value.score?.p95 ?? '—' }}
|
||||||
|
</td>
|
||||||
|
<td>{{ site.value.score?.outside ?? '—' }}</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
@if (r.ados2; as ados2) {
|
||||||
|
<h4>ADOS-2</h4>
|
||||||
|
<p>{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}</p>
|
||||||
|
<dl>
|
||||||
|
@for (item of ados2.items | keyvalue: unsorted; track item.key) {
|
||||||
|
<dt>{{ ados2.titles[item.key] ?? item.key }}</dt>
|
||||||
|
<dd>{{ item.value ?? '—' }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
@if (r.warnings.length) {
|
||||||
|
<h4>Advertencias</h4>
|
||||||
|
<ul>
|
||||||
|
@for (warning of r.warnings; track $index) {
|
||||||
|
<li>{{ warning }}</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (pdfError()) {
|
||||||
|
<p role="alert">{{ pdfError() }}</p>
|
||||||
|
}
|
||||||
|
<form method="dialog">
|
||||||
|
@if (result(); as r) {
|
||||||
|
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="pdf(r)">
|
||||||
|
Guardar como PDF
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
<button mat-stroked-button>Cerrar</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
</section>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class EegPreview {
|
||||||
|
private readonly api = inject(Api);
|
||||||
|
protected readonly busy = signal(false);
|
||||||
|
protected readonly error = signal('');
|
||||||
|
protected readonly runId = signal('');
|
||||||
|
protected readonly result = signal<PreviewResult | null>(null);
|
||||||
|
protected readonly unsorted = () => 0;
|
||||||
|
protected readonly exporting = signal(false);
|
||||||
|
protected readonly pdfError = signal('');
|
||||||
|
|
||||||
|
protected async pdf(result: PreviewResult): Promise<void> {
|
||||||
|
this.exporting.set(true);
|
||||||
|
this.pdfError.set('');
|
||||||
|
try {
|
||||||
|
await downloadPreviewPdf(result);
|
||||||
|
} catch (error) {
|
||||||
|
this.pdfError.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.exporting.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async start(edf?: File, ados2?: File, birth_date?: string): Promise<void> {
|
||||||
|
if (!edf) return;
|
||||||
|
this.busy.set(true);
|
||||||
|
this.error.set('');
|
||||||
|
this.result.set(null);
|
||||||
|
try {
|
||||||
|
const { run_id } = await this.api.invoke(startPreview, {
|
||||||
|
body: { edf, ados2, birth_date: birth_date || undefined },
|
||||||
|
});
|
||||||
|
this.runId.set(run_id);
|
||||||
|
} catch (error) {
|
||||||
|
this.error.set(errorText(error));
|
||||||
|
this.busy.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async finish(run: Run, dialog: HTMLDialogElement): Promise<void> {
|
||||||
|
try {
|
||||||
|
if (run.state !== 'succeeded') return;
|
||||||
|
const { result } = await this.api.invoke(previewStatus, { run_id: run.id });
|
||||||
|
this.result.set(result);
|
||||||
|
if (result) dialog.showModal();
|
||||||
|
else this.error.set('La vista previa no devolvió un resultado.');
|
||||||
|
} catch (error) {
|
||||||
|
this.error.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.busy.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<section class="card model">
|
||||||
|
<h2>Estudios EEG</h2>
|
||||||
|
<form (ngSubmit)="analyze()">
|
||||||
|
<label
|
||||||
|
>Alcance
|
||||||
|
<select name="scope" [(ngModel)]="mode">
|
||||||
|
<option value="pending">Pendientes</option>
|
||||||
|
<option value="first_n">Primeros N</option>
|
||||||
|
<option value="ids">Por ID</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
@if (mode() === 'first_n') {
|
||||||
|
<label
|
||||||
|
>Número de estudios <input type="number" name="count" min="1" required [(ngModel)]="count"
|
||||||
|
/></label>
|
||||||
|
}
|
||||||
|
@if (mode() === 'ids') {
|
||||||
|
<label
|
||||||
|
>ID de estudios (uno por línea) <textarea name="ids" required [(ngModel)]="ids"></textarea>
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
<button mat-flat-button type="submit" [disabled]="busy() || !execution()">Analizar</button>
|
||||||
|
</form>
|
||||||
|
<form (ngSubmit)="upload(files)">
|
||||||
|
<label>Archivos EDF <input #files type="file" accept=".edf" multiple required /></label>
|
||||||
|
<button mat-stroked-button type="submit" [disabled]="busy()">Subir EDF</button>
|
||||||
|
</form>
|
||||||
|
@if (error()) {
|
||||||
|
<p role="alert">{{ error() }}</p>
|
||||||
|
}
|
||||||
|
@if (runId(); as id) {
|
||||||
|
<app-run-monitor [runId]="id" (finished)="finish()" />
|
||||||
|
}
|
||||||
|
<app-eeg-preview />
|
||||||
|
<h3>Resumen</h3>
|
||||||
|
@if (summary.hasValue()) {
|
||||||
|
<dl>
|
||||||
|
@for (count of summary.value() | keyvalue; track count.key) {
|
||||||
|
<dt>{{ labels[count.key] ?? count.key }}</dt>
|
||||||
|
<dd>{{ count.value }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
} @else if (summary.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
|
@if (history.hasValue()) {
|
||||||
|
@if (history.value().last; as last) {
|
||||||
|
<p>
|
||||||
|
Última ejecución TEA: {{ last.status }}
|
||||||
|
@if (last.ended != null) {
|
||||||
|
· {{ last.ended * 1000 | date: 'short' }}
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
<p>
|
||||||
|
{{
|
||||||
|
history.value().current
|
||||||
|
? 'Indicadores al día'
|
||||||
|
: 'Indicadores pendientes: corre el análisis TEA'
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
} @else if (history.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
|
@if (eegs.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
|
@if (eegMetrics.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
|
<div class="model">
|
||||||
|
<table class="plain eegs">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Fecha</th>
|
||||||
|
<th>Registro</th>
|
||||||
|
<th>Análisis</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (e of eegs.hasValue() ? eegs.value() : []; track e.id) {
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<button mat-button type="button" [disabled]="!e.analysed" (click)="eeg.set(e.id)">
|
||||||
|
{{ e.study_date }}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
<td>{{ e.lab_record_id ?? '—' }}</td>
|
||||||
|
<td>
|
||||||
|
{{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }}
|
||||||
|
{{ e.level ? '(' + e.level + ')' : '' }}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
} @empty {
|
||||||
|
<tr>
|
||||||
|
<td colspan="3" class="muted">Sin EEG cargados.</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
@if (eegMetrics.hasValue() && eegMetrics.value(); as m) {
|
||||||
|
<h3>EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses</h3>
|
||||||
|
<table class="plain">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Métrica</th>
|
||||||
|
<th>Valor</th>
|
||||||
|
<th>z</th>
|
||||||
|
<th>Curva</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (x of m.metrics; track x.code) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ metricNames[x.code] ?? x.code }}</td>
|
||||||
|
<td class="num">{{ x.value | number: '1.2-2' }}</td>
|
||||||
|
<td class="num">{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}</td>
|
||||||
|
<td>{{ x.model ?? 'sin curva en producción' }}</td>
|
||||||
|
</tr>
|
||||||
|
} @empty {
|
||||||
|
<tr>
|
||||||
|
<td colspan="4" class="muted">Sin métricas (EEG no válido).</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { Component, inject, input, output, resource, signal } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { Api } from '../../api/api';
|
||||||
|
import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs';
|
||||||
|
import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary';
|
||||||
|
import { studies } from '../../api/fn/eeg/studies';
|
||||||
|
import { study } from '../../api/fn/eeg/study';
|
||||||
|
import { pipeline } from '../../api/fn/ingest/pipeline';
|
||||||
|
import { startRun } from '../../api/fn/ingest/start-run';
|
||||||
|
import { upload } from '../../api/fn/ingest/upload';
|
||||||
|
import { runHistory } from '../../api/fn/runs/run-history';
|
||||||
|
import type { Execution } from '../../api/models/execution';
|
||||||
|
import type { Scope } from '../../api/models/scope';
|
||||||
|
import { errorText, RunMonitor } from '../run-monitor';
|
||||||
|
import { EegPreview } from './preview';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-eeg-studies',
|
||||||
|
imports: [
|
||||||
|
DatePipe,
|
||||||
|
DecimalPipe,
|
||||||
|
KeyValuePipe,
|
||||||
|
FormsModule,
|
||||||
|
MatButtonModule,
|
||||||
|
RunMonitor,
|
||||||
|
EegPreview,
|
||||||
|
],
|
||||||
|
templateUrl: './studies.html',
|
||||||
|
})
|
||||||
|
export class EegStudies {
|
||||||
|
private readonly api = inject(Api);
|
||||||
|
readonly execution = input<Execution>();
|
||||||
|
readonly refresh = input(0);
|
||||||
|
readonly changed = output<void>();
|
||||||
|
protected readonly eegs = resource({
|
||||||
|
params: () => this.refresh(),
|
||||||
|
loader: () => this.api.invoke(studies),
|
||||||
|
});
|
||||||
|
protected readonly eeg = signal<string | undefined>(undefined);
|
||||||
|
protected readonly eegMetrics = resource({
|
||||||
|
params: () => {
|
||||||
|
const eeg_id = this.eeg();
|
||||||
|
return eeg_id ? { eeg_id, refresh: this.refresh() } : undefined;
|
||||||
|
},
|
||||||
|
loader: ({ params: { eeg_id } }) => this.api.invoke(study, { eeg_id }),
|
||||||
|
});
|
||||||
|
protected readonly summary = resource({
|
||||||
|
params: () => this.refresh(),
|
||||||
|
loader: () => this.api.invoke(eegStudiesSummary),
|
||||||
|
});
|
||||||
|
protected readonly history = resource({
|
||||||
|
params: () => this.refresh(),
|
||||||
|
loader: async () => {
|
||||||
|
const [last] = await this.api.invoke(runHistory, { job: 'tea_eeg', domain: 'tea', limit: 1 });
|
||||||
|
if (last?.state !== 'succeeded' || last.ended == null) return { last, current: false };
|
||||||
|
const ended = last.ended;
|
||||||
|
const limit = 200;
|
||||||
|
let before: string | undefined;
|
||||||
|
for (;;) {
|
||||||
|
const runs = await this.api.invoke(runHistory, {
|
||||||
|
job: 'analyze',
|
||||||
|
domain: 'tea',
|
||||||
|
limit,
|
||||||
|
before,
|
||||||
|
});
|
||||||
|
if (runs.some((run) => run.ended != null && run.ended > ended))
|
||||||
|
return { last, current: false };
|
||||||
|
if (runs.length < limit) return { last, current: true };
|
||||||
|
before = runs[runs.length - 1].id;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
protected readonly labels: Record<string, string> = {
|
||||||
|
eegs: 'Estudios',
|
||||||
|
analysed: 'Analizados',
|
||||||
|
valid: 'Válidos',
|
||||||
|
not_valid: 'No válidos',
|
||||||
|
failed: 'Fallidos',
|
||||||
|
metrics: 'Métricas',
|
||||||
|
metrics_with_z: 'Métricas con z',
|
||||||
|
high: 'Altas',
|
||||||
|
low: 'Bajas',
|
||||||
|
};
|
||||||
|
protected readonly metricNames: Record<string, string> = {
|
||||||
|
posterior_rhythm: 'Ritmo posterior (Hz)',
|
||||||
|
spindles_n2: 'Husos de sueño N2 (por min)',
|
||||||
|
spindles_n3: 'Husos de sueño N3 (por min)',
|
||||||
|
paroxysmal_spikes: 'Picos paroxísticos (por min)',
|
||||||
|
anteroposterior_gradient: 'Gradiente anteroposterior',
|
||||||
|
};
|
||||||
|
protected readonly mode = signal<NonNullable<Scope['mode']>>('pending');
|
||||||
|
protected readonly count = signal<number | null>(null);
|
||||||
|
protected readonly ids = signal('');
|
||||||
|
protected readonly busy = signal(false);
|
||||||
|
protected readonly error = signal('');
|
||||||
|
protected readonly runId = signal('');
|
||||||
|
protected readonly errorText = errorText;
|
||||||
|
|
||||||
|
protected async analyze(): Promise<void> {
|
||||||
|
const execution = this.execution();
|
||||||
|
if (!execution) return;
|
||||||
|
const mode = this.mode();
|
||||||
|
const scope: Scope = { mode };
|
||||||
|
if (mode === 'first_n') {
|
||||||
|
const count = this.count();
|
||||||
|
if (count == null || !Number.isInteger(count) || count < 1) return;
|
||||||
|
scope.n = count;
|
||||||
|
}
|
||||||
|
if (mode === 'ids') {
|
||||||
|
scope.ids = this.ids().split(/\s+/).filter(Boolean);
|
||||||
|
if (!scope.ids.length) return;
|
||||||
|
}
|
||||||
|
await this.start(() => this.api.invoke(analyzeEegs, { body: { scope, execution } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async upload(input: HTMLInputElement): Promise<void> {
|
||||||
|
const files = Array.from(input.files ?? []);
|
||||||
|
if (!files.length) return;
|
||||||
|
if (files.some((file) => !file.name.toLowerCase().endsWith('.edf'))) {
|
||||||
|
this.error.set('Selecciona archivos EDF.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await this.start(async () => {
|
||||||
|
try {
|
||||||
|
await this.api.invoke(pipeline, { pipeline_id: 'tea' });
|
||||||
|
await this.api.invoke(upload, { body: { files: files as unknown as string[] } });
|
||||||
|
const run = await this.api.invoke(startRun, { pipeline_id: 'tea', body: {} });
|
||||||
|
input.value = '';
|
||||||
|
return run;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof HttpErrorResponse && error.status === 404) {
|
||||||
|
throw new Error('No hay un pipeline TEA configurado');
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected finish(): void {
|
||||||
|
this.busy.set(false);
|
||||||
|
this.changed.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async start(submit: () => Promise<{ [key: string]: string }>): Promise<void> {
|
||||||
|
this.busy.set(true);
|
||||||
|
this.error.set('');
|
||||||
|
try {
|
||||||
|
const { run_id } = await submit();
|
||||||
|
this.runId.set(run_id);
|
||||||
|
} catch (error) {
|
||||||
|
this.error.set(errorText(error));
|
||||||
|
this.busy.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { trainingForm } from './training';
|
||||||
|
|
||||||
|
describe('training form', () => {
|
||||||
|
it('removes execution and resolves the TEA training source with its defaults', () => {
|
||||||
|
const { schema, model } = trainingForm({
|
||||||
|
name: 'all',
|
||||||
|
domain: 'tea',
|
||||||
|
defaults: {
|
||||||
|
execution: { mode: 'local', scheduler: null },
|
||||||
|
source: { kind: 'site', line_hz: 50 },
|
||||||
|
},
|
||||||
|
json_schema: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
execution: { type: 'object' },
|
||||||
|
as_of: { anyOf: [{ type: 'string', format: 'date' }, { type: 'null' }] },
|
||||||
|
source: { anyOf: [{ $ref: '#/$defs/TrainingSource' }, { type: 'null' }] },
|
||||||
|
},
|
||||||
|
$defs: {
|
||||||
|
TrainingSource: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
kind: { type: 'string', enum: ['site', 'folder'], default: 'site' },
|
||||||
|
folder: { anyOf: [{ type: 'string' }, { type: 'null' }] },
|
||||||
|
line_hz: { type: 'integer', enum: [50, 60], default: 50 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(schema.properties).not.toHaveProperty('execution');
|
||||||
|
expect(schema.properties?.['as_of']).toMatchObject({
|
||||||
|
type: ['string', 'null'],
|
||||||
|
format: 'date',
|
||||||
|
});
|
||||||
|
expect(schema.properties?.['source']).toMatchObject({
|
||||||
|
type: ['object', 'null'],
|
||||||
|
properties: {
|
||||||
|
kind: { enum: ['site', 'folder'] },
|
||||||
|
folder: { type: ['string', 'null'] },
|
||||||
|
line_hz: { enum: [50, 60] },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(model).toEqual({ source: { kind: 'site', line_hz: 50 } });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { Component, inject, input, model, output, resource, signal } from '@angular/core';
|
||||||
|
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { FormlyForm, provideFormlyCore } from '@ngx-formly/core';
|
||||||
|
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
|
||||||
|
import { withFormlyMaterial } from '@ngx-formly/material';
|
||||||
|
import type { JSONSchema7, JSONSchema7TypeName } from 'json-schema';
|
||||||
|
import { Api } from '../api/api';
|
||||||
|
import { train } from '../api/fn/models/train';
|
||||||
|
import { trainingConfig } from '../api/fn/models/training-config';
|
||||||
|
import { trainingInputs } from '../api/fn/models/training-inputs';
|
||||||
|
import { uploadTrainingInputs } from '../api/fn/models/upload-training-inputs';
|
||||||
|
import type { Domain } from '../api/models/domain';
|
||||||
|
import type { Execution } from '../api/models/execution';
|
||||||
|
import type { TrainingConfig } from '../api/models/training-config';
|
||||||
|
import { FORMLY_TYPES } from '../conectar/schema-form';
|
||||||
|
import { errorText } from './run-monitor';
|
||||||
|
|
||||||
|
type Schema = JSONSchema7 & { $defs?: Record<string, Schema> };
|
||||||
|
|
||||||
|
interface InputSets {
|
||||||
|
allowed: string[];
|
||||||
|
description: string;
|
||||||
|
sets: { name: string; edf_files: number; has_ages: boolean }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trainingForm(config: TrainingConfig) {
|
||||||
|
const raw = structuredClone(config.json_schema) as Schema;
|
||||||
|
const model = structuredClone(config.defaults);
|
||||||
|
delete model['execution'];
|
||||||
|
delete raw.properties?.['execution'];
|
||||||
|
raw.required = raw.required?.filter((key) => key !== 'execution');
|
||||||
|
const normalize = (schema: Schema): Schema => {
|
||||||
|
if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]);
|
||||||
|
if (schema.anyOf) {
|
||||||
|
const { anyOf, ...rest } = schema;
|
||||||
|
const selected = normalize(
|
||||||
|
anyOf.find((entry) => typeof entry === 'object' && entry.type !== 'null') as Schema,
|
||||||
|
);
|
||||||
|
return { ...selected, ...rest, type: [selected.type as JSONSchema7TypeName, 'null'] };
|
||||||
|
}
|
||||||
|
if (schema.properties) {
|
||||||
|
return {
|
||||||
|
...schema,
|
||||||
|
properties: Object.fromEntries(
|
||||||
|
Object.entries(schema.properties).map(([key, value]) => [
|
||||||
|
key,
|
||||||
|
normalize(value as Schema),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return schema;
|
||||||
|
};
|
||||||
|
return { schema: normalize(raw), model };
|
||||||
|
}
|
||||||
|
|
||||||
|
function allowedFile(file: File, allowed: string[]): boolean {
|
||||||
|
return allowed.some((pattern) => {
|
||||||
|
if (pattern === '*.edf') return file.name.toLowerCase().endsWith('.edf');
|
||||||
|
return file.name === pattern;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-governance-training',
|
||||||
|
imports: [FormsModule, ReactiveFormsModule, FormlyForm, MatButtonModule],
|
||||||
|
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
|
||||||
|
template: `
|
||||||
|
<section class="card">
|
||||||
|
<h3>{{ name() === 'all' ? 'Entrenar modelos' : 'Reentrenar ' + name() }}</h3>
|
||||||
|
@if (config.hasValue()) {
|
||||||
|
@let form = config.value();
|
||||||
|
<form (ngSubmit)="start(form.model)">
|
||||||
|
<formly-form [form]="form.form" [fields]="form.fields" [model]="form.model" />
|
||||||
|
@if (domain() === 'tea') {
|
||||||
|
<label
|
||||||
|
><input type="checkbox" name="promote" [(ngModel)]="autoPromote" /> Promover al
|
||||||
|
terminar</label
|
||||||
|
>
|
||||||
|
}
|
||||||
|
<button
|
||||||
|
mat-flat-button
|
||||||
|
type="submit"
|
||||||
|
[disabled]="busy() || disabled() || form.form.invalid"
|
||||||
|
>
|
||||||
|
Entrenar
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
} @else if (config.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
|
@if (inputs.hasValue() && inputs.value(); as sets) {
|
||||||
|
<h4>Archivos de entrenamiento</h4>
|
||||||
|
<p>{{ sets.description }}</p>
|
||||||
|
<ul>
|
||||||
|
@for (set of sets.sets; track set.name) {
|
||||||
|
<li>
|
||||||
|
{{ set.name }} · {{ set.edf_files }} EDF ·
|
||||||
|
{{ set.has_ages ? 'Con edades' : 'Sin edades' }}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<form (ngSubmit)="upload(setName.value, files)">
|
||||||
|
<label
|
||||||
|
>Conjunto
|
||||||
|
<input #setName list="training-input-sets" required />
|
||||||
|
</label>
|
||||||
|
<datalist id="training-input-sets">
|
||||||
|
@for (set of sets.sets; track set.name) {
|
||||||
|
<option [value]="set.name"></option>
|
||||||
|
}
|
||||||
|
</datalist>
|
||||||
|
<label
|
||||||
|
>Archivos
|
||||||
|
<input #files type="file" multiple required [accept]="accept(sets.allowed)" />
|
||||||
|
</label>
|
||||||
|
<button mat-stroked-button type="submit" [disabled]="uploading()">Subir archivos</button>
|
||||||
|
</form>
|
||||||
|
} @else if (inputs.error(); as error) {
|
||||||
|
<p role="alert">{{ errorText(error) }}</p>
|
||||||
|
}
|
||||||
|
@if (message()) {
|
||||||
|
<p role="status">{{ message() }}</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class Training {
|
||||||
|
private readonly api = inject(Api);
|
||||||
|
private readonly jsonschema = inject(FormlyJsonschema);
|
||||||
|
readonly domain = input.required<Domain>();
|
||||||
|
readonly name = input.required<string>();
|
||||||
|
readonly execution = input<Execution>();
|
||||||
|
readonly disabled = input(false);
|
||||||
|
readonly started = output<{ id: string; autoPromote: boolean }>();
|
||||||
|
protected readonly config = resource({
|
||||||
|
params: () => ({ domain: this.domain(), name: this.name() }),
|
||||||
|
loader: async ({ params }) => {
|
||||||
|
const { schema, model } = trainingForm(await this.api.invoke(trainingConfig, params));
|
||||||
|
const fields = [
|
||||||
|
this.jsonschema.toFieldConfig(schema, {
|
||||||
|
map: (field, source) => {
|
||||||
|
if (source.format === 'date') {
|
||||||
|
field.props = { ...field.props, type: 'date' };
|
||||||
|
}
|
||||||
|
if (field.key === 'kind') {
|
||||||
|
field.type = 'select';
|
||||||
|
field.props = {
|
||||||
|
...field.props,
|
||||||
|
options: [
|
||||||
|
{ value: 'site', label: 'Niños del sitio sin el diagnóstico' },
|
||||||
|
{ value: 'folder', label: 'Carpeta de EDF con edades' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (field.key === 'line_hz') {
|
||||||
|
field.type = 'select';
|
||||||
|
field.props = {
|
||||||
|
...field.props,
|
||||||
|
options: [
|
||||||
|
{ value: 50, label: '50 Hz' },
|
||||||
|
{ value: 60, label: '60 Hz' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return field;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
return { fields, model, form: new UntypedFormGroup({}) };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
protected readonly inputs = resource({
|
||||||
|
params: () => ({ domain: this.domain(), name: this.name() }),
|
||||||
|
loader: async ({ params }) => {
|
||||||
|
try {
|
||||||
|
return (await this.api.invoke(trainingInputs, params)) as InputSets;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof HttpErrorResponse && error.status === 404) return undefined;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
readonly busy = model(false);
|
||||||
|
protected readonly uploading = signal(false);
|
||||||
|
protected readonly message = signal('');
|
||||||
|
protected readonly autoPromote = signal(false);
|
||||||
|
protected readonly errorText = errorText;
|
||||||
|
|
||||||
|
protected async start(model: TrainingConfig['defaults']): Promise<void> {
|
||||||
|
if (this.busy() || this.disabled()) return;
|
||||||
|
this.busy.set(true);
|
||||||
|
this.message.set('');
|
||||||
|
const domain = this.domain();
|
||||||
|
const name = this.name();
|
||||||
|
const autoPromote = domain === 'tea' && this.autoPromote();
|
||||||
|
try {
|
||||||
|
const { run_id } = await this.api.invoke(train, {
|
||||||
|
domain,
|
||||||
|
body: {
|
||||||
|
as_of: model['as_of'] || undefined,
|
||||||
|
source: model['source'] ?? undefined,
|
||||||
|
execution: this.execution(),
|
||||||
|
...(name === 'all' ? {} : { models: [name] }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.started.emit({ id: run_id, autoPromote });
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.busy.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected accept(allowed: string[]): string {
|
||||||
|
return allowed
|
||||||
|
.map((pattern) =>
|
||||||
|
pattern.startsWith('*.') ? pattern.slice(1) : '.' + pattern.split('.').pop(),
|
||||||
|
)
|
||||||
|
.join(',');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async upload(set: string, input: HTMLInputElement): Promise<void> {
|
||||||
|
const files = Array.from(input.files ?? []);
|
||||||
|
const allowed = this.inputs.hasValue() ? (this.inputs.value()?.allowed ?? []) : [];
|
||||||
|
if (!files.length || files.some((file) => !allowedFile(file, allowed))) {
|
||||||
|
this.message.set('Archivos permitidos: ' + allowed.join(', '));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.uploading.set(true);
|
||||||
|
this.message.set('');
|
||||||
|
try {
|
||||||
|
await this.api.invoke(uploadTrainingInputs, {
|
||||||
|
domain: this.domain(),
|
||||||
|
name: this.name(),
|
||||||
|
set: set.trim(),
|
||||||
|
body: { files },
|
||||||
|
});
|
||||||
|
input.value = '';
|
||||||
|
this.inputs.reload();
|
||||||
|
} catch (error) {
|
||||||
|
this.message.set(errorText(error));
|
||||||
|
} finally {
|
||||||
|
this.uploading.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user