Compare commits

..

35 Commits

Author SHA1 Message Date
edgar 5f92c49ed4 Mostrar escalas de supervivencia publicadas 2026-12-02 23:00:06 -06:00
edgar a22ce12067 Mostrar solo curvas de probabilidad disponibles 2026-12-02 22:53:44 -06:00
edgar a19874438b Ajustar resumen y ocultar series no disponibles 2026-12-02 22:50:30 -06:00
edgar c08a0b8874 Ajustar pestañas y etiquetas de días 2026-12-02 21:54:54 -06:00
edgar 5201340a13 Aclarar etiquetas de días en indicadores CaCu 2026-12-02 21:50:01 -06:00
edgar cca9517b7c Conservar la exclusión por histerectomía cuando la API no la reporta 2026-12-02 20:26:14 -06:00
edgar 3693991772 Renombrar tasas de confirmación histopatológica 2026-12-02 20:23:32 -06:00
edgar e49dde10e7 Distinguir diagnósticos en la ruta de tamizaje 2026-12-02 20:19:36 -06:00
edgar 2dec5af826 Distinguir tiempos de diagnóstico en indicadores 2026-12-02 20:19:36 -06:00
edgar 0316966374 Ajustar la prueba de las escalas al título sin versión 2026-12-02 19:43:55 -06:00
edgar 3d72c153c5 Ficha: quitar la nota de las etapas de la citología 2026-12-02 19:42:55 -06:00
edgar 422b408e37 Ficha: quitar la procedencia del formulario de citología 2026-12-02 19:42:53 -06:00
edgar 211f02edad Ficha: mostrar el VPH como estudio aparte 2026-12-02 19:42:51 -06:00
edgar 32b879edd2 Ficha: mostrar la tabla de modelos como desplegable 2026-12-02 19:42:48 -06:00
edgar 9726d6faa3 Ficha: quitar el texto de las curvas de probabilidad 2026-12-02 19:42:46 -06:00
edgar bafd6760d4 Ficha: llevar la comparación y sus filtros a las curvas de probabilidad 2026-12-02 19:42:43 -06:00
edgar 0666ce3077 Ficha: no mostrar la comparación de riesgos de referencia 2026-12-02 19:42:41 -06:00
edgar d2eada9385 Ficha: titular cada riesgo por su desenlace y llevar el escenario al pie 2026-12-02 19:42:38 -06:00
edgar 0d458818b5 Ficha: dibujar el intervalo sobre la escala y llevar la fecha índice al pie 2026-12-02 19:42:36 -06:00
edgar 2970ce16b0 Ficha: quitar el título Riesgos y recomendaciones 2026-12-02 19:42:33 -06:00
Angel Capetillo Zavala a43cf4b51b Distinguir ausencias e insuficiencia en supervivencia CaCu 2026-12-02 19:26:50 -06:00
edgar a4cc80fbe2 Mostrar la elegibilidad CaCu solo cuando la paciente no es elegible 2026-12-02 19:04:00 -06:00
Angel Capetillo Zavala 370da43695 Agregar elegibilidad CaCu por escenario clínico 2026-12-02 18:47:09 -06:00
edgar f7fdab950a Comparar series de riesgo seleccionables en la ficha CaCu 2026-12-02 18:24:33 -06:00
edgar 1260e0ff2a Mostrar métodos y escenarios sin curva en la supervivencia de la ficha 2026-12-02 18:14:19 -06:00
Angel Capetillo Zavala 09e5f4dd34 CaCu record: grouped NCI comparison, Spanish outcome names, survival texts and risk-only scales
The NCI comparison shows the reference once per horizon and one block per model, saying the
reasons that every incompatible comparison shares only once. Outcome names are translated for
display only (the API identifiers stay), and the reference outcome is read from the answer.
The CaCu survival card is titled as survival and states that its curves estimate the clinical
scenario's group, not an individual. Survival and recurrence estimates no longer feed the risk
scales, curves, probability table or PDF.
2026-12-02 17:48:03 -06:00
Angel Capetillo Zavala f119ba048a Simplify CaCu distribution descriptions 2026-12-02 14:09:02 -06:00
edgar 9ae8254dee Mostrar el motivo de exclusión en la ficha CaCu 2026-12-02 09:35:25 -06:00
Angel Capetillo Zavala b9e210d825 Merge the CaMa diagnostic pathway and biopsy results into the CaCu rounds, record and risk work 2026-12-01 19:02:02 -06:00
Angel Capetillo Zavala 652fd45c29 CaCu record: the NCI reference comparison section and probability curves at the published horizons 2026-12-01 18:32:11 -06:00
Angel Capetillo Zavala 8fc06038fb CaCu record: stages with states and sources, segmented risk scales, antecedents and collapsible findings 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala e1e8da6093 CaCu indicators: one selector for the cytology and HPV genotype views, grouped bars and genotype labels 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala 81894a3777 CaCu: show screening rounds and restore category palettes 2026-12-01 14:22:23 -06:00
Angel Capetillo Zavala 749afe765d CaMa: present diagnostic pathway and biopsy results 2026-12-01 12:27:16 -06:00
Roberto Treviño fe4dd55452 CaCu's page by readings, screening stages, ages and exports 2026-11-30 23:31:58 -06:00
176 changed files with 11388 additions and 12258 deletions
-3
View File
@@ -39,9 +39,6 @@
"material-symbols/outlined.css",
"src/styles.scss"
],
"define": {
"global": "globalThis"
},
"allowedCommonJsDependencies": [
"plotly.js-cartesian-dist-min"
]
+343
View File
@@ -0,0 +1,343 @@
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
const ROUND = { name: 'Por detección inicial y subsecuente' };
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
const VIEWS = ['General', 'Por grupo de edad', 'Por estatus de seguimiento', ROUND.name];
const TITLES = {
cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
};
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page,
}) => {
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Días de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Tasa de confirmación histopatológica de referencia a colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
// one selector for the cytology distribution and the HPV by genotype; the biopsy card is apart
await expect(
tab.locator('app-readings', {
has: page.getByRole('heading', { name: 'Pacientes evaluadas por resultado de VPH' }),
}),
).toHaveCount(0);
const views = tab.getByRole('radiogroup', { name: VIEWS_LABEL });
await expect(views.getByRole('radio')).toHaveText(VIEWS);
await expect(views.getByRole('radio', { name: 'General' })).toBeChecked();
await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
for (const view of VIEWS.slice(1)) {
await views.getByRole('radio', { name: view }).click();
for (const card of [TITLES.cytology, TITLES.genotype]) {
const readings = tab.locator('app-readings', {
has: page.getByRole('heading', { name: card }),
});
// each card has no toggle of its own: the selector drives both
await expect(readings.getByRole('radio')).toHaveCount(0);
// no long description beside the bars: the cards read from their title, note and legend
await expect(readings).not.toContainText(
/Cada barra|Cada paciente cuenta una vez|«Detección inicial»|una barra vacía|«Positivo»/,
);
await expect(
readings
.locator('.group')
.first()
.or(readings.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
}
}
const biopsyCard = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.biopsy }),
});
await expect(biopsyCard.getByRole('radio')).toHaveCount(0);
await views.getByRole('radio', { name: 'General' }).click();
await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: TITLES.cytology }) })
.getByRole('table'),
).toBeVisible();
// the PPV cards keep their round tab, in the same words and order
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.colposcopy }),
});
await colposcopy.getByRole('radio', ROUND).click();
await expect(
colposcopy
.getByRole('table', ROUND)
.or(colposcopy.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.ppvBiopsy }),
})
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Seguimiento' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried on top of the API's own answers. They show how the page draws them, not the
// backend. The shared selector drives the cytology and the HPV-by-genotype cards; the PPV cards keep a tab.
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
const GENOTYPE_COLOURS = {
Negativo: '#42A77E',
'VPH 16': '#DF8640',
'VPH 18': '#C29C42',
'VPH 16 y 18': '#C24269',
Positivo: '#A8C243',
};
const CYTOLOGY_COLOURS = {
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const view = async (name: string) => {
await tab.getByRole('radiogroup', { name: VIEWS_LABEL }).getByRole('radio', { name }).click();
};
/** A PPV card on its round tab. */
const ppv = async (key: 'colposcopy' | 'ppvBiopsy') => {
await tab
.getByRole('radio', { name: key === 'colposcopy' ? 'Colposcopía' : 'Biopsia', exact: true })
.click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, card, view, ppv };
}
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first();
/** The groups of a card as the page draws them: "label<br>n = N", the width of the first bar and the colour of
* each category (the first group's rows), in hex. */
const traces = (readings: Locator) =>
readings.evaluate((el) => {
const hex = (rgb: string) =>
'#' +
(rgb.match(/\d+/g) ?? [])
.slice(0, 3)
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const groups = [...el.querySelectorAll('.group')];
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>n = ${g.querySelector('.n')!.textContent!.replace('n = ', '').trim()}`,
),
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries(
[...groups[0].querySelectorAll('.row')].map((r) => [
r.querySelector('.name')!.textContent!.trim(),
hex(getComputedStyle(r.querySelector('.fill')!).backgroundColor),
]),
),
};
});
for (const key of ['colposcopy', 'ppvBiopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'as-is');
const readings = await ppv(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'no-initial');
const readings = await ppv(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'unpublished');
const readings = await ppv(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
for (const card of ['cytology', 'genotype'] as const) {
test(`rondas (simulado) ${card}: the selector draws the rounds in order, with the category colours`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'as-is');
await view(ROUND.name);
const readings = of(TITLES[card]);
await expect(plotOf(readings)).toBeVisible();
const found = await traces(readings);
expect(found.y.map((l) => l.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(found.colours).toMatchObject(card === 'cytology' ? CYTOLOGY_COLOURS : GENOTYPE_COLOURS);
});
test(`rondas (simulado) ${card}: an empty initial group is an empty bar with its zero`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name);
const found = await traces(of(TITLES[card]));
expect(found.y[0]).toBe('Detección inicial<br>n = 0');
expect(found.x[0]).toBe(0);
});
test(`rondas (simulado) ${card}: without the stratum the selector says it is not available`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'unpublished');
await view(ROUND.name);
await expect(of(TITLES[card])).toContainText('No disponible');
});
}
test('rondas (simulado): the genotype card never shows the incomplete positives, and carries no long description', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).not.toContainText('«Positivo»');
await expect(readings).not.toContainText('Cada barra');
await expect(readings.getByRole('rowheader')).not.toContainText([
'Otro de alto riesgo',
'incompleto',
]);
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim())).toEqual([
'Negativo',
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
const found = await traces(readings);
expect(Object.keys(found.colours)).toEqual(Object.keys(GENOTYPE_COLOURS));
}
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the shared selector on each view lays out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { view, ppv } = await withRounds(page, 'as-is');
for (const name of VIEWS) {
await view(name);
await page.waitForTimeout(1200);
// every option of the selector is inside the window (it wraps on a narrow screen)
for (const box of await page
.getByRole('radiogroup', { name: VIEWS_LABEL })
.getByRole('radio')
.evaluateAll((els) =>
els.map((e) => e.closest('mat-button-toggle')!.getBoundingClientRect().right),
))
expect(box).toBeLessThanOrEqual(width);
expect(await layoutProblems(page), name).toEqual([]);
}
await ppv('colposcopy');
await ppv('ppvBiopsy');
await page.waitForTimeout(1200);
expect(await layoutProblems(page)).toEqual([]);
});
}
File diff suppressed because it is too large Load Diff
+122
View File
@@ -0,0 +1,122 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+339 -99
View File
@@ -1,6 +1,8 @@
import { statSync } from 'node:fs';
import { expect, Locator, Page, test } from '@playwright/test';
import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] {
const problems: string[] = [];
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
@@ -9,6 +11,7 @@ function watch(page: Page): string[] {
return problems;
}
// The pages show only to someone signed in (the API itself answers everyone).
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
@@ -16,123 +19,360 @@ test.beforeEach(async ({ page }) => {
expect(signed.status()).toBe(204);
});
async function downloaded(page: Page, button: Locator, kind: 'pdf' | 'xlsx'): Promise<string> {
const [file] = await Promise.all([page.waitForEvent('download'), button.click()]);
const name = file.suggestedFilename();
expect(name).toMatch(new RegExp(`^tea-[a-z]+-\\d{4}-\\d{2}-\\d{2}\\.${kind}$`));
expect(name).not.toMatch(/N-?\d{4}/);
expect(statSync(await file.path()).size).toBeGreaterThan(0);
return name;
}
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
await page.goto('/conectar');
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page).toHaveURL(/\/conectar$/);
await page.getByRole('button', { name: 'Cuenta' }).click();
await page.getByRole('menuitem', { name: 'Salir' }).click();
await expect(page).toHaveURL(/\/login/);
await page.close();
});
test('tea indicators: every tab loads, and the follow-up list exports to Excel', async ({
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page,
}) => {
const problems = watch(page);
const listed = page.waitForResponse(
(r) => r.url().includes('/tea/fhir/Measure') && !r.url().includes('MeasureReport'),
const report = page.waitForResponse(
(r) =>
r.url().includes('MeasureReport') &&
r.url().includes('measure=cacu-eu7') &&
!r.url().includes('%2C'),
);
await page.goto('/indicadores/tea');
const measures = (await (await listed).json()).entry.length;
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await expect(page.locator('app-tab-indicadores [data-measure]').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
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',
await page.goto('/indicadores/cacu');
const eu7 = await (await report).json();
const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population',
).count;
// the card says it as the old one did: "<n> pacientes"
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
`${count.toLocaleString('es-MX')} pacientes`,
);
expect(name).toMatch(/^tea-seguimiento-/);
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
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: 'Histórico' }).click();
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(measures);
expect(problems).toEqual([]);
});
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
test('tea patient: the record and the risk page load and export to PDF', async ({ page }) => {
const problems = watch(page);
await page.goto('/indicadores/tea');
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
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();
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')).toBeVisible();
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('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.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-/,
);
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
expect(problems).toEqual([]);
});
test('tea gobernanza: every section in sync mode, and the preview saved as PDF', async ({
test('conectar: open the hospital pipeline, preview a source, run it to success', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/gobernanza/tea');
await page.getByLabel('Modo').selectOption('sync');
await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).toBeVisible();
await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible();
// a node's caption: its kind, then its name
await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await 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([]);
});
await page.getByRole('button', { name: 'Entrenar modelos' }).click();
await expect(page.getByRole('heading', { name: 'Entrenar modelos', level: 3 })).toBeVisible();
await expect(page.locator('app-governance-training formly-form')).toBeVisible();
test('revision: what the hospital source holds, and a decision through the page', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click();
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([]);
});
const monitor = page.locator('app-gobernanza > section > section app-run-monitor');
await page.getByRole('button', { name: 'Analizar EEG' }).click();
await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible();
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
await page.getByRole('button', { name: 'Calcular riesgos' }).click();
await expect(page.getByRole('heading', { name: 'Cálculo de riesgos' })).toBeVisible();
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
await page.getByRole('button', { name: 'Promover candidatas' }).click();
await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible();
const studies = page.locator('app-eeg-studies');
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');
test('gobernanza: a version with its reports, its curves, and promotion refused without validation', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
});
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
page,
}) => {
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
const problems = watch(page);
await page.goto('/conectar');
await page.getByLabel('Nueva canalización').fill('asistente');
await page.getByLabel('Nueva canalización').press('Enter');
await page.getByRole('button', { name: 'Fuente de datos' }).click();
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
await page.locator('[data-type="sqlserver"]').click();
await page.locator('[data-field="host"]').fill(site.hostname);
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
await page.locator('mat-select[data-field="table"]').click();
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it');
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
await page.getByRole('button', { name: 'Cancelar' }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
expect(problems).toEqual([]);
});
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
* opportunity section on, in order, and the kind of each plot (its traces' types). */
function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Seguimiento', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Histórico', exact: true })).toHaveCount(1);
const labels = await page.getByRole('tab').allTextContents();
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
});
}
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Histórico' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from '@playwright/test';
/** SIMULATED answers. The pages read the API's aggregated MeasureReports; these helpers pass them
* through the browser and rewrite the screening-round strata, so the cards can be tried with the
* groups the contract of `rebuild` allows (stratum `round`, crossed `round-category`) without
* loading data. They prove how the page draws such answers, not what the backend computes.
*
* - `as-is`: the answers untouched, with a stratum named `screening_round` renamed `round`.
* - `no-initial`: nobody is in the initial group (the group is absent and the totals drop).
* - `unclassified`: the initial group folds into "Sin dato" (what 5740's answers look like).
* - `unpublished`: the round strata are not in the answers. */
export type Simulation = 'as-is' | 'no-initial' | 'unclassified' | 'unpublished';
type Stratum = {
value?: { text?: string };
component?: { value?: { text?: string } }[];
population?: { code?: { coding?: { code?: string }[] }; count: number }[];
};
type Stratifier = { code?: { coding?: { code?: string }[] }[]; stratum?: Stratum[] };
const named = (s: Stratifier) => (s.code ?? []).map((c) => c.coding?.[0]?.code).join('-');
const label = (x: Stratum) => x.component?.[0]?.value?.text ?? x.value?.text;
const pop = (o: { population?: Stratum['population'] }, code: string) =>
o.population?.find((p) => p.code?.coding?.[0]?.code === code);
function fold(into: Stratum, from: Stratum) {
for (const p of from.population ?? []) {
const q = pop(into, p.code!.coding![0].code!);
if (q) q.count += p.count;
else (into.population ??= []).push(structuredClone(p));
}
}
export function simulate(report: any, how: Simulation) {
const group = report?.group?.[0];
if (!group) return report;
for (const s of group.stratifier ?? ([] as Stratifier[]))
for (const c of s.code ?? []) {
const k = c.coding?.[0];
if (k?.code === 'screening_round') k.code = 'round';
}
const rounds: Stratifier[] = (group.stratifier ?? []).filter((s: Stratifier) =>
['round', 'round-category'].includes(named(s)),
);
if (how === 'unpublished')
group.stratifier = (group.stratifier ?? []).filter((s: Stratifier) => !rounds.includes(s));
if (how === 'no-initial' || how === 'unclassified')
for (const s of rounds) {
const initial = (s.stratum ?? []).filter((x) => label(x) === 'initial');
const rest = (s.stratum ?? []).filter((x) => label(x) !== 'initial');
for (const x of initial) {
if (how === 'unclassified') {
const other = x.component?.[1]?.value?.text;
const target = rest.find(
(y) => label(y) === 'no_data' && (!other || y.component?.[1]?.value?.text === other),
);
if (target) fold(target, x);
else {
(x.component ? x.component[0].value! : x.value!).text = 'no_data';
rest.push(x);
}
} else if (named(s) === 'round') {
// the group vanishes and the period's total drops by its patients: a real zero
for (const p of x.population ?? []) {
const total = pop(group, p.code!.coding![0].code!);
if (total && p.code!.coding![0].code !== 'numerator')
total.count = Math.max(0, total.count - p.count);
}
}
}
s.stratum = rest;
}
return report;
}
/** Answers every CaCu MeasureReport search through `simulate`. */
export async function simulateRounds(page: Page, how: Simulation) {
await page.route('**/api/cacu/fhir/MeasureReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const entry of body.entry ?? []) simulate(entry.resource, how);
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
+498 -2506
View File
File diff suppressed because it is too large Load Diff
+262 -2115
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -29,8 +29,8 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.15",
"plotly.js": "4.1.2",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
@@ -44,7 +44,7 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.3",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
+5 -1
View File
@@ -1,5 +1,8 @@
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({
testDir: 'e2e',
timeout: 15 * 60_000,
@@ -9,9 +12,10 @@ export default defineConfig({
use: {
baseURL: 'http://127.0.0.1:4310',
viewport: { width: 1440, height: 1000 },
actionTimeout: 60_000,
actionTimeout: 60_000, // a stuck step fails, not the whole run
},
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',
env: { NG_CLI_ANALYTICS: 'false' },
url: 'http://127.0.0.1:4310',
+1
View File
@@ -1 +1,2 @@
// `/api` to the API the e2e run started (API_URL).
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
-100
View File
@@ -1,100 +0,0 @@
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();
});
});
-82
View File
@@ -1,82 +0,0 @@
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}`);
}
-36
View File
@@ -1,36 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { AnalyzeRequest } from '../../models/analyze-request';
export interface AnalyzeEegs$Params {
body: AnalyzeRequest
}
export function analyzeEegs(http: HttpClient, rootUrl: string, params: AnalyzeEegs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, analyzeEegs.PATH, 'post');
if (params) {
rb.body(params.body, 'application/json');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
analyzeEegs.PATH = '/tea/eegs/analyze';
-33
View File
@@ -1,33 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
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';
@@ -1,36 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
@@ -1,30 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Options } from '../../models/options';
export interface ExecutionOptions$Params {
}
export function executionOptions(http: HttpClient, rootUrl: string, params?: ExecutionOptions$Params, context?: HttpContext): Observable<StrictHttpResponse<Options>> {
const rb = new RequestBuilder(rootUrl, executionOptions.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<Options>;
})
);
}
executionOptions.PATH = '/execution/options';
@@ -9,32 +9,40 @@ import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Retire$Params {
export interface CacuEligibility$Params {
domain: Domain;
name: string;
version: number;
id: string;
/**
* Limit the report to one CaCu scenario
*/
scenario?: (string | null);
/**
* Only index dates up to this day
*/
cutoff?: (string | null);
}
export function retire(http: HttpClient, rootUrl: string, params: Retire$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, retire.PATH, 'post');
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('version', params.version, {});
rb.path('id', params.id, {});
rb.query('scenario', params.scenario, {});
rb.query('cutoff', params.cutoff, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
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<{
[key: string]: string;
}>;
})
);
}
retire.PATH = '/models/{domain}/{name}/versions/{version}/retire';
cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
@@ -9,30 +9,40 @@ import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface TrainingInputs$Params {
export interface CacuRiskSeries$Params {
domain: Domain;
name: string;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function trainingInputs(http: HttpClient, rootUrl: string, params: TrainingInputs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, trainingInputs.PATH, 'get');
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
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<{
[key: string]: any;
}>;
})
);
}
trainingInputs.PATH = '/models/{domain}/{name}/inputs';
cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
-54
View File
@@ -1,54 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
@@ -9,32 +9,40 @@ import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface VersionChecks$Params {
export interface ReferenceRisk$Params {
domain: Domain;
name: string;
version: number;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function versionChecks(http: HttpClient, rootUrl: string, params: VersionChecks$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, versionChecks.PATH, 'get');
const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('version', params.version, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
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<{
[key: string]: any;
}>;
})
);
}
versionChecks.PATH = '/models/{domain}/{name}/versions/{version}/checks';
referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
+6 -6
View File
@@ -18,11 +18,6 @@ export interface SearchPatient$Params {
*/
'follow-up-window'?: (number | null);
/**
* explicit window start that overrides follow-up-window
*/
'follow-up-start'?: (string | null);
/**
* default: the last day with data
*/
@@ -39,6 +34,11 @@ export interface SearchPatient$Params {
*/
identifier?: (string | null);
/**
* gt, ge, lt or le and a day (2000-12-31)
*/
birthdate?: Array<string>;
/**
* -recent or -risk-<outcome>
*/
@@ -69,11 +69,11 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.path('domain', params.domain, {});
rb.query('_id', params['_id'], {});
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'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('birthdate', params.birthdate, {});
rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {});
-3
View File
@@ -7,12 +7,10 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Analyze } from '../../models/analyze';
import { Domain } from '../../models/domain';
export interface Analyze$Params {
domain: Domain;
body?: Analyze
}
export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Params, context?: HttpContext): Observable<StrictHttpResponse<{
@@ -21,7 +19,6 @@ export function analyze(http: HttpClient, rootUrl: string, params: Analyze$Param
const rb = new RequestBuilder(rootUrl, analyze.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.body(params.body, 'application/json');
}
return http.request(
-42
View File
@@ -1,42 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
-36
View File
@@ -1,36 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
-41
View File
@@ -1,41 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
-40
View File
@@ -1,40 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
-35
View File
@@ -1,35 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
@@ -1,43 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
-32
View File
@@ -1,32 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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}';
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
-32
View File
@@ -1,32 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
-39
View File
@@ -1,39 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
+6 -5
View File
@@ -7,18 +7,17 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Run } from '../../models/run';
export interface RunStatus$Params {
run_id: string;
outputs?: boolean;
}
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<Run>> {
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
if (params) {
rb.path('run_id', params.run_id, {});
rb.query('outputs', params.outputs, {});
}
return http.request(
@@ -26,7 +25,9 @@ export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$P
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Run>;
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
@@ -7,18 +7,17 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyStartPreview } from '../../models/body-start-preview';
export interface StartPreview$Params {
body: BodyStartPreview
export interface TerminateRun$Params {
run_id: string;
}
export function startPreview(http: HttpClient, rootUrl: string, params: StartPreview$Params, context?: HttpContext): Observable<StrictHttpResponse<{
export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, startPreview.PATH, 'post');
const rb = new RequestBuilder(rootUrl, terminateRun.PATH, 'post');
if (params) {
rb.body(params.body, 'multipart/form-data');
rb.path('run_id', params.run_id, {});
}
return http.request(
@@ -33,4 +32,4 @@ export function startPreview(http: HttpClient, rootUrl: string, params: StartPre
);
}
startPreview.PATH = '/tea/preview';
terminateRun.PATH = '/runs/{run_id}/terminate';
+8 -36
View File
@@ -9,10 +9,6 @@ export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
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 { conceptMaps as conceptMaps } from './fn/ingest/concept-maps';
export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/get-concept-map';
@@ -49,28 +45,12 @@ export type { Models$Params as Models$Params } from './fn/models/models';
export { models as models } from './fn/models/models';
export type { Analyze$Params as Analyze$Params } 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 { score as score } from './fn/models/score';
export type { Train$Params as Train$Params } 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 { 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 { promote as promote } from './fn/models/promote';
export type { AddClinicalValidation$Params as AddClinicalValidation$Params } from './fn/models/add-clinical-validation';
@@ -79,8 +59,6 @@ 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 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 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 { conflicts as conflicts } from './fn/review/conflicts';
export type { Correct$Params as Correct$Params } from './fn/review/correct';
@@ -95,24 +73,14 @@ export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject';
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { 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 { runStatus as runStatus } from './fn/runs/run-status';
export type { CancelRun$Params as CancelRun$Params } from './fn/runs/cancel-run';
export { cancelRun as cancelRun } from './fn/runs/cancel-run';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies';
export type { 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 { 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 { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user';
export type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
@@ -143,10 +111,14 @@ export type { SearchObservation$Params as SearchObservation$Params } from './fn/
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
export type { SearchPatient$Params as SearchPatient$Params } 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 { readPatient as readPatient } from './fn/fhir/read-patient';
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
export type { ReferenceRisk$Params as ReferenceRisk$Params } from './fn/fhir/reference-risk';
export { referenceRisk as referenceRisk } from './fn/fhir/reference-risk';
export type { CacuRiskSeries$Params as CacuRiskSeries$Params } from './fn/fhir/cacu-risk-series';
export { cacuRiskSeries as cacuRiskSeries } from './fn/fhir/cacu-risk-series';
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
+1 -25
View File
@@ -2,30 +2,21 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
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 { 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 { BodyUploadTrainingInputs } from './models/body-upload-training-inputs';
export type { Browsed } from './models/browsed';
export type { Cancel } from './models/cancel';
export type { Catalog } from './models/catalog';
export type { Condition } from './models/condition';
export type { Correction } from './models/correction';
export type { Domain } from './models/domain';
export type { Edf } from './models/edf';
export type { Entry } from './models/entry';
export type { ErrorModel } from './models/error-model';
export type { Execution } from './models/execution';
export type { Extract } from './models/extract';
export type { Fhir } from './models/fhir';
export type { FieldSpec } from './models/field-spec';
export type { Group } from './models/group';
export type { Guided } from './models/guided';
export type { Health } from './models/health';
export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join';
export type { Link } from './models/link';
@@ -35,43 +26,28 @@ export type { Map } from './models/map';
export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option';
export type { Options } from './models/options';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
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 { Read } from './models/read';
export type { Rejection } from './models/rejection';
export type { Relation } from './models/relation';
export type { Route } from './models/route';
export type { Run } from './models/run';
export type { RunRequest } from './models/run-request';
export type { RunSummary } from './models/run-summary';
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 { Site } from './models/site';
export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type';
export type { Step } from './models/step';
export type { Study } from './models/study';
export type { Target } from './models/target';
export type { Tasks } from './models/tasks';
export type { Tested } from './models/tested';
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 { UserCreate } from './models/user-create';
export type { UserRead } from './models/user-read';
export type { UserUpdate } from './models/user-update';
export type { ValidationError } from './models/validation-error';
export type { Version } from './models/version';
export type { Worker } from './models/worker';
+2 -6
View File
@@ -2,16 +2,12 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Metric } from '../models/metric';
import { Relation } from '../models/relation';
export interface Analysis {
age_months: (number | null);
checks: Array<{
[key: string]: any;
}>;
id: string;
level: (string | null);
metrics: Array<Metric>;
regions: Array<{
[key: string]: any;
}>;
relation?: Array<Relation>;
valid: (boolean | null);
}
-9
View File
@@ -1,9 +0,0 @@
/* 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;
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
export interface Analyze {
execution?: (Execution | null);
}
-6
View File
@@ -1,6 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyImportModels {
file: string;
}
-9
View File
@@ -1,9 +0,0 @@
/* 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;
}
@@ -1,6 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUploadTrainingInputs {
files: Array<Blob>;
}
-8
View File
@@ -1,8 +0,0 @@
/* 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 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
-32
View File
@@ -1,32 +0,0 @@
/* 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);
}
-11
View File
@@ -1,11 +0,0 @@
/* 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);
}
+1 -1
View File
@@ -25,7 +25,7 @@ export interface Extract {
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
+1 -1
View File
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'fhir';
-20
View File
@@ -1,20 +0,0 @@
/* 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);
}
+6
View File
@@ -1,10 +1,16 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric {
code: string;
electrodes?: Array<Site>;
median?: (number | null);
model: (string | null);
outside: (number | null);
p5?: (number | null);
p95?: (number | null);
value: number;
z: (number | null);
zones?: Array<Site>;
}
-7
View File
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Options {
default_mode: 'sync' | 'local' | 'remote';
schedulers: Array<string>;
}
+1 -2
View File
@@ -1,7 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Edf } from '../models/edf';
import { Extract } from '../models/extract';
import { Fhir } from '../models/fhir';
import { Join } from '../models/join';
@@ -12,5 +11,5 @@ import { Route } from '../models/route';
import { Source } from '../models/source';
import { Target } from '../models/target';
export interface Pipeline {
nodes: Array<(Source | Read | Route | Map | Extract | Edf | Fhir | Join | Link | Target)>;
nodes: Array<(Source | Read | Route | Map | Extract | Fhir | Join | Link | Target)>;
}
-16
View File
@@ -1,16 +0,0 @@
/* 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;
};
}
-21
View File
@@ -1,21 +0,0 @@
/* 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);
}
-17
View File
@@ -1,17 +0,0 @@
/* 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;
};
}
-10
View File
@@ -1,10 +0,0 @@
/* 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>;
}
-8
View File
@@ -1,8 +0,0 @@
/* 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';
}
-21
View File
@@ -1,21 +0,0 @@
/* 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 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
+25
View File
@@ -0,0 +1,25 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
-12
View File
@@ -1,12 +0,0 @@
/* 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;
}
-22
View File
@@ -1,22 +0,0 @@
/* 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>;
}
-13
View File
@@ -1,13 +0,0 @@
/* 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);
}
-10
View File
@@ -1,10 +0,0 @@
/* 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);
}
+3 -3
View File
@@ -1,8 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Score } from '../models/score';
export interface Site {
score: (Score | null);
value: (number | null);
site: string;
value: number;
z: (number | null);
}
-9
View File
@@ -1,9 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Step {
ended: (number | null);
key: string;
started: (number | null);
status: string;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export interface Target {
/**
* En qué estudio de la plataforma se guarda.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'target';
-10
View File
@@ -1,10 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Tasks {
erred?: number;
memory?: number;
processing?: number;
queued?: number;
waiting?: number;
}
-13
View File
@@ -1,13 +0,0 @@
/* 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;
}
-16
View File
@@ -1,16 +0,0 @@
/* 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;
}
-8
View File
@@ -1,15 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
import { TrainingSource } from '../models/training-source';
export interface Training {
/**
* Fecha de corte de los datos (por omisión, hoy)
*/
as_of?: (string | null);
execution?: (Execution | null);
models?: Array<string>;
source?: (TrainingSource | null);
}
-1
View File
@@ -11,6 +11,5 @@ export interface Version {
[key: string]: string;
};
reports: Array<string>;
status: 'champion' | 'retired' | 'candidate';
version: number;
}
-11
View File
@@ -1,11 +0,0 @@
/* 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;
}
-6
View File
@@ -13,12 +13,6 @@ export const routes: Routes = [
canActivate: [domainAllowed],
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',
canActivate: [domainAllowed],
+1 -1
View File
@@ -75,7 +75,7 @@ export const signedIn: CanActivateFn = async (_route, state) => {
/** A domain's pages show only to whom may see it. */
export const domainAllowed: CanActivateFn = (route) => {
const auth = inject(Auth);
const domain = route.paramMap.get('domain') ?? route.data['domain'];
const domain = route.paramMap.get('domain');
if (!domain || auth.canSee(domain)) return true;
const first = auth.user()?.domains[0];
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
-53
View File
@@ -1,53 +0,0 @@
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();
});
});
-72
View File
@@ -1,72 +0,0 @@
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);
}
}
+1 -2
View File
@@ -59,6 +59,7 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
export const KINDS: Record<Kind, string> = {
source: 'Fuente de datos',
read: 'Leer documentos',
@@ -66,7 +67,6 @@ export const KINDS: Record<Kind, string> = {
map: 'Traducir códigos',
extract: 'Extraer datos',
fhir: 'Leer FHIR',
edf: 'Leer EDF',
join: 'Unir',
link: 'Identificar a la persona',
target: 'Guardar en la plataforma',
@@ -79,7 +79,6 @@ export const HELP: Record<Kind, string> = {
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
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.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.',
+96
View File
@@ -1,3 +1,14 @@
import type { Figure } from './plot';
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
export const METRIC_NAMES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
@@ -46,3 +57,88 @@ export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
CSS: 'Puntuación de severidad (CSS)',
};
/** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */
const AT: Record<string, [number, number]> = {
Fp1: [-0.31, 0.95], Fp2: [0.31, 0.95],
F7: [-0.81, 0.59], F3: [-0.4, 0.53], Fz: [0, 0.5], F4: [0.4, 0.53], F8: [0.81, 0.59],
T3: [-1, 0], C3: [-0.5, 0], Cz: [0, 0], C4: [0.5, 0], T4: [1, 0],
T5: [-0.81, -0.59], P3: [-0.4, -0.53], Pz: [0, -0.5], P4: [0.4, -0.53], T6: [0.81, -0.59],
O1: [-0.31, -0.95], O2: [0.31, -0.95],
}; // prettier-ignore
export interface Site {
site: string;
value: number;
z?: number | null;
}
/** Her electrodes on the head, coloured by how far each is from its age curve (z, blue
* below and red above), or by her own value where no curve scores electrodes. */
export function headMap(electrodes: Site[]): Figure {
const placed = electrodes.filter((e) => AT[e.site]);
const scored = placed.some((e) => e.z !== null && e.z !== undefined);
const colour = placed.map((e) => (scored ? (e.z ?? 0) : e.value));
const ring = Array.from({ length: 73 }, (_, i) => (i * 2 * Math.PI) / 72);
return {
data: [
{
x: ring.map((t) => 1.12 * Math.sin(t)),
y: ring.map((t) => 1.12 * Math.cos(t)),
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: [-0.12, 0, 0.12],
y: [1.1, 1.24, 1.1],
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: placed.map((e) => AT[e.site][0]),
y: placed.map((e) => AT[e.site][1]),
text: placed.map((e) => e.site),
customdata: colour,
mode: 'markers+text',
textposition: 'top center',
marker: {
size: 22,
color: colour,
colorscale: 'RdBu',
reversescale: true,
...(scored ? { cmin: -3, cmax: 3, cmid: 0 } : {}),
colorbar: { title: { text: scored ? 'z' : 'valor' }, thickness: 10 },
line: { color: '#ffffff', width: 1 },
},
hovertemplate: scored ? '%{text}: z = %{customdata:.2f}<extra></extra>'
: '%{text}: %{customdata:.3f}<extra></extra>', // prettier-ignore
showlegend: false,
},
],
layout: {
xaxis: { visible: false, range: [-1.35, 1.35], scaleanchor: 'y' },
yaxis: { visible: false, range: [-1.25, 1.35] },
margin: { l: 10, r: 10, t: 10, b: 10 },
},
} as Figure;
}
/** The zones, most affected first: by how far from the age curve, else by value. */
export function byDeviation(zones: Site[]): Site[] {
const scored = zones.some((z) => z.z !== null && z.z !== undefined);
return [...zones].sort((a, b) =>
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
);
}
/** An EEG's quality level (models.tea.eeg.checks): how much of it the analysis could use. */
export const LEVEL_NAMES: Record<string, string> = {
complete: 'registro completo',
partial: 'registro parcial: menos de la mitad limpio',
no_ear_reference: 'sin referencia auricular',
not_analyzable: 'no analizable',
};
+69
View File
@@ -0,0 +1,69 @@
import type { Content, TDocumentDefinitions } from 'pdfmake/interfaces';
/** A table to save, as the page shows it: its headers and rows, and what it was asked with. */
export interface Sheet {
title: string;
query?: [string, string][];
head: string[];
rows: string[][];
}
/** Every cell is text: nothing in it runs as a formula. */
export async function saveExcel(sheet: Sheet, file: string): Promise<void> {
const { default: write } = await import('write-excel-file/browser');
const text = (value: string) => ({ value, type: String });
const head = sheet.head.map((value) => ({ ...text(value), fontWeight: 'bold' as const }));
await write([
{ sheet: 'Resultados', data: [head, ...sheet.rows.map((r) => r.map(text))] },
{ sheet: 'Consulta', data: (sheet.query ?? []).map((q) => q.map(text)) },
]).toFile(`${file}.xlsx`);
}
/** The tables on the institutional page: logo, date and page numbers. */
export async function savePdf(sheets: Sheet[], file: string, wide = false): Promise<void> {
const [pdfmake, fonts, logo] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
fetch('assets/branding/isssteleon-logo.png').then((r) => r.blob()),
]);
const image = await new Promise<string>((done, fail) => {
const reader = new FileReader();
reader.onload = () => done(reader.result as string);
reader.onerror = () => fail(reader.error);
reader.readAsDataURL(logo);
});
const made = new Date().toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
const definition: TDocumentDefinitions = {
pageSize: 'LETTER',
pageOrientation: wide ? 'landscape' : 'portrait',
pageMargins: [36, 60, 36, 40],
defaultStyle: { fontSize: 7.5 },
header: { image, width: 110, margin: [36, 18, 0, 0] },
footer: (page, pages) => ({
columns: [
`Generado: ${made}`,
{ text: 'Confidencial, uso interno', alignment: 'center' },
{ text: `Página ${page} de ${pages}`, alignment: 'right' },
],
margin: [36, 12],
fontSize: 7,
}),
content: sheets.flatMap((s): Content[] => [
{ text: s.title, fontSize: 13, bold: true, margin: [0, 10, 0, 4] },
...(s.query ?? []).map(([k, v]) => ({ text: [{ text: `${k}: `, bold: true }, v] })),
s.rows.length
? {
layout: 'lightHorizontalLines',
margin: [0, 6, 0, 0],
table: {
headerRows: 1,
dontBreakRows: true,
body: [s.head.map((text) => ({ text, bold: true })), ...s.rows],
},
}
: 'Sin registros.',
]),
};
pdfmake.default.addVirtualFileSystem(fonts.default);
await pdfmake.default.createPdf(definition).download(`${file}.pdf`);
}
-100
View File
@@ -1,100 +0,0 @@
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`);
});
});
-20
View File
@@ -1,20 +0,0 @@
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;
}
-4
View File
@@ -1,4 +0,0 @@
export { allRows } from './fetch-all';
export { downloadPdf, type PdfContent } from './pdf';
export { safeName } from './safe-name';
export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx';
-31
View File
@@ -1,31 +0,0 @@
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);
}
-34
View File
@@ -1,34 +0,0 @@
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));
}
-99
View File
@@ -1,99 +0,0 @@
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);
}
-44
View File
@@ -1,44 +0,0 @@
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');
});
});
-135
View File
@@ -1,135 +0,0 @@
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);
}
}
}
-71
View File
@@ -1,71 +0,0 @@
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();
}
});
});
-117
View File
@@ -1,117 +0,0 @@
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] ?? '');
}
}
}
+4 -82
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures, scenarioFigure, studyPoints } from './figures';
import { interpretabilityFigures, scenarioFigure } from './figures';
describe('governance figures', () => {
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] },
});
expect(found.figure.data.length).toBe(3);
expect(found.figure.data.length).toBe(3); // band, curve, model points
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] },
escenarios: [scenario],
});
expect(found.length).toBe(1);
expect(found.length).toBe(1); // the cohort's curves only
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(drawn.figure.data.length).toBe(5);
expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
});
@@ -71,84 +71,6 @@ describe('governance figures', () => {
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', () => {
expect(interpretabilityFigures({ kind: 'other' })).toEqual([]);
});
+70 -146
View File
@@ -1,32 +1,53 @@
import type { Analysis } from '../api/models/analysis';
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them. */
interface Band {
x: number[];
y: (number | null)[];
y: number[];
low?: (number | null)[];
high?: (number | null)[];
}
export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The stretches of x where the curve has both limits: a band is drawn only there, never from a
* limit that is absent (an absent limit is not zero). */
function bandRuns(b: Band): number[][] {
const runs: number[][] = [];
let run: number[] = [];
b.x.forEach((x, i) => {
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
else {
if (run.length > 1) runs.push(run);
run = [];
}
});
if (run.length > 1) runs.push(run);
return runs;
}
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
lines.push({
x: [...b.x, ...[...b.x].reverse()],
y: [...b.high, ...[...b.low].reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
for (const run of bandRuns(b)) {
const x = run.map((i) => b.x[i]);
lines.push({
x: [...x, ...[...x].reverse()],
y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
}
}
lines.push({
x: b.x,
y: b.y,
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name,
type: 'scatter',
mode: 'lines',
@@ -35,64 +56,10 @@ export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Par
return lines;
}
export interface Centile {
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;
}
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's
* observed and predicted risk per subgroup, or the logistic regression's calibration. */
export function interpretabilityFigures(
report: Record<string, any>,
ageCurve: AgeCurveOptions = {},
): { title: string; figure: Figure }[] {
switch (report['kind']) {
case 'curves': {
@@ -125,6 +92,7 @@ export function interpretabilityFigures(
},
},
},
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
];
}
case 'subgroups':
@@ -193,75 +161,26 @@ export function interpretabilityFigures(
},
];
}
case 'scenarios':
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return [];
case 'forest':
return [
{
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];
// 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 = 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',
},
]
: [];
const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`;
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}`,
title: `Tasa de referencia: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`,
figure: {
data: [
{
x: value.ages,
y: [rate, rate],
y: [value.rate, value.rate],
name: 'Tasa',
type: 'scatter',
mode: 'lines',
},
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' } },
@@ -271,28 +190,18 @@ export function interpretabilityFigures(
},
];
}
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;
const c = value.curve;
return [
{
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
figure: {
data: [
...banded(
'Mediana',
'p5–p95',
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
PALETTE[4],
),
...overlay,
],
].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)),
layout: {
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
yaxis: { title: { text: 'Valor' } },
@@ -362,6 +271,8 @@ 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(
title: string,
e: any,
@@ -405,20 +316,33 @@ export function scenarioFigure(
};
}
/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
* point without both limits has no bar. */
function points(
name: string,
x: number[],
p: { S: number[]; low: number[]; high: number[] },
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> {
const errors = p.S.map((value, i) => {
const low = p.low?.[i];
const high = p.high?.[i];
return finite(value) && finite(low) && finite(high)
? { up: high - value, down: value - low }
: null;
});
return {
x,
y: p.S,
error_y: {
type: 'data',
symmetric: false,
array: p.high.map((h, i) => h - p.S[i]),
arrayminus: p.S.map((v, i) => v - p.low[i]),
},
y: p.S.map((v) => (finite(v) ? v : null)) as number[],
...(errors.some((error) => error !== null)
? {
error_y: {
type: 'data' as const,
symmetric: false,
array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: errors.map((error) => error?.down ?? null) as number[],
},
}
: {}),
name,
type: 'scatter',
mode: 'markers',
+180 -272
View File
@@ -1,305 +1,213 @@
<section class="page">
<h1>Gobernanza de modelos</h1>
<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>
<h1>{{ labels[domain()] ?? domain() }}</h1>
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
<app-execution [(execution)]="execution" />
<section>
<h2>Modelos</h2>
<div class="card actions">
<button mat-flat-button type="button" (click)="training.set('all')">Entrenar modelos</button>
<form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Datos hasta</mat-label>
<input
matInput
type="date"
[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
mat-stroked-button
type="button"
[disabled]="starting() || running()"
(click)="start('score')"
[disabled]="running()"
(click)="confirming.set('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button
mat-stroked-button
type="button"
[disabled]="starting() || running() || !execution()"
(click)="start('analyze')"
>
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
Analizar EEG
</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)"
/>
}
<app-governance-bundles
[domain]="domainKey()"
[(importing)]="starting"
[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>
}
@if (message()) {
<p class="message" role="status">{{ message() }}</p>
@if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
@if (running()) {
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
}
}
</form>
@if (message()) {
<p class="muted" role="status">{{ message() }}</p>
}
@if (models.isLoading()) {
<p class="muted">Cargando modelos…</p>
} @else if (models.error(); as error) {
<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.hasValue() ? models.value() : []; track m.name) {
<section class="card model">
<h3>{{ m.title }}</h3>
<button mat-stroked-button type="button" (click)="training.set(m.name)">Reentrenar</button>
<table class="plain">
<thead>
@if (models.isLoading()) {
<app-loading what="los modelos" />
} @else if (!models.value()?.length) {
<p class="muted empty">Sin modelos entrenados en este dominio.</p>
}
@for (m of models.value() ?? []; track m.name) {
<div class="card model">
<h2>
{{ m.title }} <code class="muted code">{{ m.name }}</code>
</h2>
<table class="plain">
<thead>
<tr>
<th>Versión</th>
<th>Creada</th>
<th>Datos</th>
<th>Informes</th>
<th>Validación clínica</th>
<th></th>
</tr>
</thead>
<tbody>
@for (v of m.versions; track v.version) {
<tr>
<th>Versión</th>
<th>Creada</th>
<th>Entrenamiento / prueba</th>
<th>Informes</th>
<th>Validación clínica</th>
<th>Comprobaciones y linaje</th>
</tr>
</thead>
<tbody>
@for (v of m.versions; track v.version) {
<tr>
<td>
v{{ v.version }} <span class="badge">{{ v.status }}</span>
</td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num">
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td>
@for (report of v.reports; track report) {
<button
mat-button
type="button"
(click)="reportDownload(m.name, v.version, report)"
>
{{ reportNames[report] ?? report }}
</button>
<td>
v{{ v.version }}
@if (champion(v)) {
<span class="badge">en producción</span>
}
</td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="nowrap">{{ sizes(v) }}</td>
<td>
<div class="reports">
@for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r
}}</a>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chooseReport({ name: m.name, version: v.version })"
(click)="chosen.set({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
} @else {
Agregada
}
</td>
<td>
<button
mat-stroked-button
type="button"
(click)="
showVersion('checks', { name: m.name, version: v.version }, checksDialog)
"
>
Comprobaciones
</div>
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
#file
type="file"
hidden
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
<button mat-stroked-button type="button" (click)="file.click()">
Subir validación clínica
</button>
<button
mat-stroked-button
type="button"
(click)="
showVersion('lineage', { name: m.name, version: v.version }, lineageDialog)
"
>
Linaje
} @else {
Agregada
}
</td>
<td>
@if (!champion(v)) {
<button mat-stroked-button type="button" (click)="promote(m.name, v.version)">
Promover
</button>
</td>
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
@if (chosen(); as c) {
<div class="card">
<h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" />
} @empty {
<p class="muted">
{{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }}
</p>
}
</div>
}
@if (domain() === 'tea') {
<div class="card model">
<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>
@if (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>
</section>
}
@if (chosen(); as version) {
<section class="card">
<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) {
<h4>{{ f.title }}</h4>
<app-plot
[figure]="f.figure"
[height]="
report.hasValue() && report.value()['kind'] === 'forest'
? forestHeight(f.figure.data.length)
: 360
"
/>
} @empty {
@if (report.isLoading() || band.isLoading()) {
<p class="muted">Cargando…</p>
} @else if (!report.error() && !band.error()) {
<p class="muted">Este informe no tiene gráficas.</p>
}
}
</section>
}
</section>
@if (domain() === 'tea') {
<app-eeg-studies [execution]="execution()" [refresh]="refreshed()" (changed)="refresh()" />
}
</div>
}
<dialog #checksDialog aria-label="Comprobaciones" (close)="checksFor.set(undefined)">
@if (checksFor(); as key) {
<h3>Comprobaciones · {{ key.name }} v{{ key.version }}</h3>
@if (checks.hasValue()) {
@let details = checks.value();
@let actions = checkActions(details);
<ul>
@for (check of details.checks; track check.report) {
<li>
{{ reportNames[check.report] ?? check.report }} ·
{{ check.present ? 'Presente' : 'Falta' }}
</li>
}
</ul>
<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>
}
@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>
+29 -18
View File
@@ -1,18 +1,8 @@
:host {
display: block;
}
h1 {
text-align: center;
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
.subtitle {
margin: 4px 0 var(--space-4);
}
.actions {
display: flex;
@@ -30,6 +20,7 @@ h1 {
white-space: nowrap;
}
.badge {
white-space: nowrap;
margin-left: var(--space-2);
padding: 2px 8px;
border-radius: 999px;
@@ -45,12 +36,32 @@ td a {
padding: 48px 0;
text-align: center;
}
.message {
white-space: pre-line;
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
}
dialog {
max-width: min(90vw, 64rem);
.reports a {
margin-right: 0;
}
dialog form {
margin-top: var(--space-3);
h2 .code {
font-size: 12px;
font-weight: 400;
margin-left: var(--space-2);
}
.confirm {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: 4px 4px 4px 12px;
border-radius: 8px;
background: var(--color-surface-warning, #fdf3dc);
}
td button {
white-space: nowrap;
}
-16
View File
@@ -1,16 +0,0 @@
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);
});
});
+130 -326
View File
@@ -1,35 +1,31 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { METRIC_NAMES } from '../eeg-labels';
import { HttpErrorResponse } from '@angular/common/http';
import { DatePipe, DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { RouterLink } from '@angular/router';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { Api } from '../api/api';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
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 { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status';
import type { Domain } from '../api/models/domain';
import type { Execution as Choice } from '../api/models/execution';
import type { Run } from '../api/models/run';
import type { Version } from '../api/models/version';
import { DOMAINS } from '../app';
import { Plot } from '../plot';
import { Bundles, download } from './bundles';
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';
import { interpretabilityFigures } from './figures';
import { Loading } from '../loading';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
@@ -37,63 +33,34 @@ const REPORTS: Record<string, string> = {
clinical_validation: 'Validación clínica',
};
interface VersionKey {
name: string;
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' };
}
/** Model governance for a domain: every model's versions with their metrics and reports,
* the clinical validation the clinical team uploads, promotion (refused without the three
* reports), and the training and scoring runs. */
@Component({
selector: 'app-gobernanza',
imports: [
Loading,
DatePipe,
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
RouterLink,
MatFormFieldModule,
MatInputModule,
Plot,
Bundles,
Execution,
RunMonitor,
EegStudies,
Training,
],
templateUrl: './gobernanza.html',
styleUrl: './gobernanza.scss',
})
export class Gobernanza {
private readonly api = inject(Api);
private readonly root = inject(ApiConfiguration).rootUrl;
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 reportNames = REPORTS;
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);
}
private readonly refreshed = signal(0);
protected readonly models = resource({
params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
loader: async ({ params: { domain } }) => {
const found = await this.api.invoke(models, { domain });
return Promise.all(
@@ -105,299 +72,136 @@ export class Gobernanza {
);
},
});
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 chosen = signal<{ name: string; version: number } | undefined>(undefined);
protected readonly report = resource({
params: () => {
const key = this.chosen();
return key ? { ...key, domain: this.domainKey() } : undefined;
},
params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain },
loader: ({ params }) =>
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
});
protected readonly ageFeatures = computed<string[]>(() => {
const report = this.report.hasValue() ? this.report.value() : undefined;
return report?.kind === 'age_curves' ? Object.keys(report['curves']) : [];
});
protected readonly selectedFeature = signal('');
protected readonly feature = computed(() => {
const keys = this.ageFeatures();
return keys.includes(this.selectedFeature())
? this.selectedFeature()
: keys.includes('value')
? 'value'
: keys[0];
});
protected readonly band = resource({
params: () => {
const key = this.chosen();
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 overlay = signal(false);
protected readonly analysed = resource({
params: () =>
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 })),
);
},
});
protected readonly figures = computed(() => {
if (!this.report.hasValue()) return [];
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',
});
const found = this.report.value();
return found ? interpretabilityFigures(found as Record<string, unknown>) : [];
});
/** TEA: its EEGs and their analysis. */
protected readonly eegs = resource({
params: () => (this.domain() === 'tea' ? this.refreshed() + 1 : undefined),
loader: () => this.api.invoke(studies),
});
protected readonly eeg = signal<string | undefined>(undefined);
protected readonly eegMetrics = resource({
params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
});
protected readonly metricNames = METRIC_NAMES;
protected readonly asOf = signal('');
protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
undefined,
);
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
protected readonly running = computed(() => {
const r = this.run();
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
});
protected readonly STATUS: Record<string, string> = {
QUEUED: 'en cola',
NOT_STARTED: 'por iniciar',
STARTING: 'iniciando',
STARTED: 'en curso',
SUCCESS: 'terminado',
FAILURE: 'con error',
CANCELING: 'deteniéndose',
CANCELED: 'detenido',
};
/** 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('');
constructor() {
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 champion(v: Version): boolean {
return v.aliases.includes('champion');
}
protected async reportDownload(name: string, version: number, report: string): Promise<void> {
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 reportUrl(name: string, version: number, report: string): string {
return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`;
}
protected async upload(name: string, version: number, event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
const domain = this.domainKey();
try {
await this.api.invoke(addClinicalValidation, {
domain,
name,
version,
body: { file: file as unknown as string },
});
input.value = '';
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));
}
await this.api.invoke(addClinicalValidation, {
domain: this.domain() as Domain,
name,
version,
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string },
});
this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
this.refreshed.update((n) => n + 1);
}
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('');
protected async promote(name: string, version: number): Promise<void> {
try {
if (action === 'promote') await this.api.invoke(promote, { domain, ...key });
else await this.api.invoke(retire, { domain, ...key });
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.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(
`${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`,
missing
? `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 prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
if (!this.models.hasValue()) return;
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);
protected async analyzeEegs(): Promise<void> {
const { run_id } = await this.api.invoke(analyze, { domain: this.domain() as Domain });
await this.follow(run_id, 'Análisis de EEG');
}
private async follow(run_id: string, label: string): Promise<void> {
for (;;) {
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
this.run.set({ id: run_id, kind: label, status });
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
await new Promise((r) => setTimeout(r, 2000));
}
this.refreshed.update((n) => n + 1);
}
protected async promoteCandidates(dialog: HTMLDialogElement): Promise<void> {
this.editing.set(true);
this.message.set('');
try {
await this.promoteVersions(this.domainKey(), this.candidates());
dialog.close();
} finally {
this.editing.set(false);
}
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
}
protected forestHeight(rows: number): number {
return Math.max(360, rows * 24 + 72);
}
protected chooseReport(key: VersionKey): void {
this.overlay.set(false);
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 } =
kind === 'score'
? await this.api.invoke(score, { domain })
: await this.api.invoke(analyze, { domain, body: { execution: this.execution() } });
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();
protected async start(kind: 'train' | 'score'): Promise<void> {
this.confirming.set(undefined);
const domain = this.domain() as Domain;
const { run_id } =
kind === 'train'
? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} })
: await this.api.invoke(score, { domain });
await this.follow(run_id, kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos');
}
}
-101
View File
@@ -1,101 +0,0 @@
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');
});
});
-164
View File
@@ -1,164 +0,0 @@
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);
}
}
}

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