Compare commits

..

27 Commits

Author SHA1 Message Date
alberto d8cb6420a4 T2: page specs no longer point at the removed reference captures 2026-12-01 00:46:19 -06:00
alberto d3c04a5fcf The record test's FHIR stub answers searches (the CaCu/CaMa record lists her risks) 2026-12-01 00:23:32 -06:00
alberto 3655b9857c TEA studies upload their EDFs as one upload set (the merged upload takes several files) 2026-12-01 00:09:12 -06:00
alberto 3e213c4fc0 OpenAPI document and client regenerated from the merged API 2026-11-30 23:57:49 -06:00
alberto bd897baa2d Merge origin/rebuild into parity/T1-merge (WebApp)
rebuild's shell, auth and non-TEA pages; tea/parity's TEA pages on tea/parity's API.
- Routes: rebuild's signed-in tree; the TEA risk page joins it (domainAllowed reads the
  route's data domain when the path has no :domain).
- Indicadores: rebuild's header and its generic Resumen/Trazabilidad/Definiciones tabs
  (TEA as the reference page, fed by tea/parity's measures); TEA Seguimiento and Análisis
  de riesgo render tea/parity's tea-list inside rebuild's tab-seguimiento/tab-riesgos,
  which keep rebuild's CaCu/CaMa lists and patient search. rebuild's tab-riesgos-tea read
  rebuild's TEA Patient extensions, which are gone with its backend; tea-list already
  shows that list from tea/parity's FHIR search, so it is deleted rather than ported
  (its look is the base for T8/T9).
- Paciente: rebuild's record for CaCu/CaMa; TEA delegates to tea/parity's TeaRecord.
  rebuild's inline TEA sections read its EEG detail endpoint and are removed.
- Gobernanza: tea/parity's page (execution, models with checks/lineage, bundles, training,
  studies, preview) until T13; model headings use rebuild's model titles. figures.ts:
  rebuild's scenarios (drawn in the record) plus tea/parity's association forest.
- plot.ts: rebuild's layout helpers on tea/parity's partial Plotly bundle.
- Conectar: rebuild's KINDS/HELP with an entry for tea/parity's edf node.
- Dead code removed: measures boxes/sankey (tea/parity's old TEA tab), eeg-labels
  headMap/byDeviation/LEVEL_NAMES/METRIC_NAMES (rebuild's TEA record), e2e/layout.ts.
- e2e: tea/parity's TEA cases, signed in; rebuild's CaCu/CaMa/site cases need their
  hospitals loaded and come back with the page suite (T16).
- openapi.json and src/app/api: regenerated in the next commit.
2026-11-30 23:56:25 -06:00
alberto b291885b97 Gobernanza preview saved as PDF; Playwright TEA page tests
- The EEG preview dialog gets "Guardar como PDF": previewPdfContent is a
  pure function (verdict, checks, metrics with scores per electrode and
  zone, ADOS-2 classification/CSS and items by their Core titles,
  warnings), downloadPreviewPdf a thin wrapper over export/pdf; the file
  is tea-gobernanza-<day>.pdf. Unit-tested without mocks.
- e2e/pages.spec.ts now holds only the TEA page tests (the CaCu/CaMa
  cases needed fixtures P7 removed): every indicator tab, the follow-up
  xlsx export, the patient record and risk page with their PDFs, and
  every Gobernanza section in sync mode including the preview PDF. Each
  download is checked for a file and a name without a record number.
- Fixes the page tests found: the TEA xlsx name ('seguimiento-tea') failed
  validateName, so the export always threw; it is now tea-<page>-<day>.
  ng serve crashed on every Plotly page (has-hover reads 'global'): the
  build defines global as globalThis. Record numbers repeated once per
  source identifier; they are deduplicated. A refused bundle export showed
  '{}': the blob error body is now read for the API's detail.
2026-11-30 19:17:46 -06:00
alberto b847e04697 ADOS-2 items shown by the child's module, grouped by domain and subdomain
The patient record ADOS-2 table and the Seguimiento ADOS-2 card list only
the module's items, in the order of core.tea.ados2_items as the FHIR
aggregate Observation carries them: each module item component has the
module's item code and exact title as a second coding (and code.text), and
ados2-domain / ados2-subdomain extensions. Components without those
(items outside the module) are not listed. Association titles and the
concordance look the item up by catalog field instead of by row index, so
they do not depend on which items the module has. ADOS2_ITEMS moves to a
shared src/app/ados2.ts.
2026-11-30 16:56:26 -06:00
alberto e5556ebf41 Merge P6 cleanup into P5-combined 2026-11-30 16:34:17 -06:00
alberto 08a1bf910e Merge P5.3-tea-patient into P5-combined 2026-11-30 14:20:07 -06:00
alberto 7e21ebbc7b Merge P5.2-tea-indicators into P5-combined 2026-11-30 14:20:07 -06:00
alberto fde3ec08e1 Merge P5.4-gobernanza into P5-combined 2026-11-30 14:20:07 -06:00
alberto 3f6fa28590 TEA patient pages: the record and the risk analysis page
Keep the TEA record branch inside Paciente and lazy-load the risk route.
Separate FHIR adaptation, figures, shared section rendering, and PDF
content under paciente. Use the existing section cards, tables, and
buttons, with flexible summary fields and scrollable detail tables.

Read the Patient by _id with Observation, DiagnosticReport, and
RiskAssessment reverse includes. Group neurology observations by
encounter, use aggregate ADOS-2 evaluations, and use the lab-record
observation for EEG dates without reports. Order the timeline and exams
newest first and use the RiskAssessment headline flag for pair order.
Render absent fields and empty tables with an em dash.

Use a normalized 10–20 layout and a 41-by-41 inverse-distance weighted
contour clipped to the head outline, with symmetric z colors and
electrode labels. Keep the head outline and markers when no site has a
score. Request each aggregate champion's version once per record load,
draw the median and p5–p95 band with banded(), and place the observed
value at the EEG's age. Omit unavailable bands and count-rate bands.

Use the RiskAssessment's EEG for z and pair status, falling back to the
newest EEG with z scores for the bars when needed. Use site outside flags
for the forest filter, aggregate scores for global and posterior-rhythm
pairs, and show the unit-OR line and available CI bounds. Select the
headline pair by default. The current RiskAssessment carries no logistic
coefficients, so the view shows patient and reference points at the
served z and at zero. Keep the optional logistic figure input independent
of the FHIR mapping. Link to Seguimiento with the agreed query parameter.

Share section data with the PDF and include snapshots of the rendered
figures. Use the existing safe seguimiento and riesgos filename tokens
with the UTC date. Format values for es-MX and size categorical charts
to their row count.

Add Vitest coverage for the head map, norm and point, forest filtering,
z band, probability fallback, ADOS-2 rows, PDF content, included data,
and the domain branch. Static TypeScript and Angular template checks
passed with a temporary PDF type shim. The Angular build, Vitest runtime
and Playwright run on the test machines.
2026-11-30 14:19:03 -06:00
alberto adff5bac5c Indicadores TEA: Resumen, Trazabilidad, Seguimiento, Análisis de riesgo, periodicities 2026-11-30 14:19:03 -06:00
alberto e2d1c9f277 Gobernanza: execution, models (training, run monitor, checks, lineage, bundles, interpretability), EEG studies
Share one execution selection across training and analysis. Use the first
configured scheduler for a remote default and let the API validate typed
addresses. Suspend health polling when the document is hidden. Poll each
run serially, retry status reads on transient errors, and compute ETA from
completed items and elapsed seconds.

Reuse the Conectar Formly types with nullable fields and inlined references.
Omit the optional cohort when its name is blank, and offer the declared
input sets in a datalist with filename validation before upload. Identify
the versions created by a training run from its version log lines, then
check each exact version before promotion. Use native dialogs for checks,
lineage, bulk confirmation and preview. Recheck promotion eligibility before
submitting changes, and list results per version.

Verify bundle hashes using SubtleCrypto before upload. Use blob downloads
for bundles and reports. Read age centiles from the curve endpoint and keep
the count-rate reference line from the report. Join study metrics by code
and regional values by feature, skipping absent ages and values. Use one
Plotly trace per association pair and scale the forest plot height by row
count.

Preflight the TEA pipeline before staging EDFs, then start the pipeline once
for the batch. Refresh studies, their overlays and summary on completed
runs. Page through analyze history to compare its end times against the
latest tea_eeg result. The branch base lacks export/pdf.ts, so the preview
uses the specified TODO and omits the PDF action.

Added Vitest coverage for execution and run polling, ETA and cancellation,
training schema, version actions, bundle digest verification, study overlays
and the association forest. Ruff check, Ruff format --check, Prettier,
strict Angular and TypeScript diagnostics for Gobernanza and git diff --check
passed. npm ci, ng build and vitest run are assigned to the test machines.
2026-11-30 14:19:03 -06:00
alberto 0760721144 Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place
1. No prose in code
- Remove the parity-added comment above the canvas palette mapping.

2. No hacks, no glued code
- Keep the existing palette entries and saved-pipeline behavior.

3. Everything in its place
- Keep canvas code in conectar. Generated API bindings and OpenAPI
  are excluded from the cleanup.
2026-11-30 13:41:49 -06:00
alberto 56d1ef2e8a WebApp shared: Plotly partial bundle, card actions, print report, export module
Plotly partial bundle (bar, scatter, box, pie, sankey, contour) replacing the cartesian dist; card-actions (published Measure definitions, settings, Volver); Descargar reporte with a print stylesheet; export module: xlsx with frozen header, autofilter, Parámetros sheet and 5,000-row cap, pdfmake documents with header/footer, allRows following next links, file names without patient identifiers; lazy-loaded export libraries.

Checks on milkpc (node:22): npm ci, ng build (initial 567 kB / 134 kB transfer), ng test 7 files passed.
2026-11-30 13:36:35 -06:00
alberto 5d03f333f7 Client: eeg_studies_summary and the FHIR eeg_summary as distinct operations 2026-11-29 19:47:01 -06:00
alberto f7cc141625 Merge P4.3 into P4.1 for one combined gate 2026-11-29 19:46:01 -06:00
alberto 84dcebda55 Regenerate the governance REST API client 2026-11-29 19:45:50 -06:00
alberto 12b056343b TEA follow-up: Patient search with TEA filters and $eeg-summary
Regenerate the OpenAPI document and Angular client with the existing generator configuration. Repeated generation produced identical files.
2026-11-29 19:42:17 -06:00
alberto 38ece960f9 Merge P3.7 into P3.5 for one combined gate 2026-11-28 16:31:56 -06:00
alberto b3e5a69783 Client: run outputs 2026-11-28 13:37:28 -06:00
alberto 8442ad5fe6 Client for the training config 2026-11-28 13:26:18 -06:00
alberto 6732893bcc Merge tea/parity into P3.6 2026-11-28 10:31:03 -06:00
alberto 5ce225df5a Client for the edf pipeline node; the canvas shows a kind it has no form for by its raw name and leaves it out of the palette 2026-11-28 10:30:49 -06:00
alberto 8b1cbec66a Client for model bundle export and import 2026-11-28 09:24:39 -06:00
alberto 43b5523f99 Client for the runs, execution and TEA EEG analysis routes 2026-11-28 06:54:00 -06:00
163 changed files with 12516 additions and 9089 deletions
+3
View File
@@ -39,6 +39,9 @@
"material-symbols/outlined.css",
"src/styles.scss"
],
"define": {
"global": "globalThis"
},
"allowedCommonJsDependencies": [
"plotly.js-cartesian-dist-min"
]
-338
View File
@@ -1,338 +0,0 @@
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: 'Valor predictivo positivo de la colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la 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',
'Tiempos de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
// 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);
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: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
// ---- 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 says where they went', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).toContainText('«Positivo»');
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([]);
});
}
-974
View File
@@ -1,974 +0,0 @@
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
// The individual record of CaCu: the stages inside "Historial médico" and the risk scales.
// "(simulado)" tests rewrite the API's answers in the browser to cover what the synthetic data
// do not hold (every stage state, every risk value); they show how the page draws them, not the backend.
const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
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);
});
/** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!;
return { url, sample: new URL(url, 'http://x').searchParams.get('citologia')! };
}
const plus = (day: string, days: number) =>
new Date(Date.parse(day) + days * 86_400_000).toISOString().slice(0, 10);
type Route = Partial<
Record<'report' | 'colposcopy' | 'request' | 'biopsy' | 'diagnosis', number>
> & {
link?: 'recorded';
/** more extensions on the report, as the backend would publish them (stage states and sources) */
extra?: object[];
};
/** The shown cytology's report carries these dates (days after its sample). */
async function withRoute(page: Page, sample: string, days: Route) {
await page.route('**/api/cacu/fhir/DiagnosticReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const { resource: r } of body.entry ?? []) {
if (r.code?.coding?.[0]?.code !== 'cervical_cytology' || r.effectiveDateTime !== sample)
continue;
const names = {
report: 'report-date',
colposcopy: 'colposcopy-date',
request: 'biopsy-request-date',
biopsy: 'biopsy-date',
diagnosis: 'diagnosis-date',
} as const;
r.extension = (r.extension ?? []).filter(
(e: any) =>
!Object.values(names).some((n) => e.url === EXT + n) && e.url !== EXT + 'biopsy-link',
);
for (const [key, name] of Object.entries(names)) {
const d = days[key as keyof typeof names];
if (d !== undefined) r.extension.push({ url: EXT + name, valueDate: plus(sample, d) });
}
if (days.link) r.extension.push({ url: EXT + 'biopsy-link', valueCode: days.link });
r.extension.push(...(days.extra ?? []));
}
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
type Prediction = [years: number, p: number, low?: number, high?: number];
const risk = (
id: string,
text: string,
model: string,
index: string,
predictions: Prediction[],
) => ({
resourceType: 'RiskAssessment',
id,
status: 'final',
method: { text, coding: [{ code: model }] },
occurrenceDateTime: index,
prediction: predictions.map(([years, p, low, high]) => ({
whenRange: { high: { value: years, unit: 'a', code: 'a' } },
probabilityDecimal: p,
extension:
low === undefined
? []
: [
{ url: EXT + 'ic-bajo', valueDecimal: low },
{ url: EXT + 'ic-alto', valueDecimal: high },
],
})),
});
/** The patient has these risk assessments. */
async function withRisks(page: Page, assessments: object[]) {
await page.route('**/api/cacu/fhir/RiskAssessment**', (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: assessments.map((resource) => ({ resource })),
}),
}),
);
}
const historial = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Historial médico' }),
});
const scale = (page: Page, label: string, nth = 0) =>
page.locator(`.risk-scale[data-scale="${label}"]`).nth(nth);
const IMMEDIATE = 'Riesgo inmediato (al índice)';
const FIVE = 'Riesgo a 5 años';
async function open(page: Page, url: string) {
await page.goto(url);
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
}
/** Where a scale draws its marker, in % of the bar, and the figure it prints. */
async function drawn(scaleBox: Locator) {
const marker = scaleBox.locator('.risk-marker');
return {
markers: await marker.count(),
left: (await marker.count())
? await marker.evaluate((e) => (e as HTMLElement).style.left)
: undefined,
value: (await scaleBox.locator('.risk-value').count())
? (await scaleBox.locator('.risk-value').innerText()).trim()
: undefined,
grey: await scaleBox.locator('.risk-plot.unavailable').count(),
};
}
test('ficha: the five stages are a line of nodes inside "Historial médico", with the export button', async ({
page,
}) => {
const { url } = await firstRecord(page);
await open(page, url);
await expect(page.locator('mat-card-title', { hasText: 'Etapas del tamizaje' })).toHaveCount(0);
const stages = historial(page).locator('[data-section=etapas] app-stages li');
await expect(stages).toHaveCount(5);
// one row: the five nodes are level
const tops = await stages
.locator('.node')
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
expect(new Set(tops).size).toBe(1);
// each stage says its name, state, day and both intervals, centred
const first = stages.first();
await expect(first).toContainText('Toma de muestra');
await expect(first).toContainText('Registrada');
await expect(first).toContainText('Desde anterior: —');
await expect(first).toContainText('Desde toma: 0 días');
expect(
await first.locator('.info').evaluate((e) => getComputedStyle(e.parentElement!).textAlign),
).toBe('center');
await expect(historial(page)).toContainText('a la fecha de corte');
await expect(historial(page).getByRole('button', { name: 'Exportar PDF' })).toBeVisible();
// history and tests keep their tables
await expect(historial(page).getByRole('table')).toBeVisible();
await expect(page.locator('mat-card-title', { hasText: 'Pruebas y resultados' })).toBeVisible();
});
test('ficha: the export of the record still downloads its PDF', async ({ page }) => {
const { url } = await firstRecord(page);
await open(page, url);
const saved = page.waitForEvent('download');
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
expect((await saved).suggestedFilename()).toBe('expediente-cacu.pdf');
});
test('ficha: with no model both horizons are drawn grey, not available, without a marker', async ({
page,
}) => {
const { url } = await firstRecord(page);
await open(page, url);
for (const label of [IMMEDIATE, FIVE]) {
const box = scale(page, label);
await expect(box).toContainText('No disponible');
expect(await drawn(box)).toMatchObject({ markers: 0, grey: 1 });
await expect(box.locator('.risk-labels span')).toHaveText([
'0 %',
'25 %',
'50 %',
'75 %',
'100 %',
]);
}
await expect(
page.getByText('Divisiones numéricas descriptivas; no representan umbrales clínicos.'),
).toBeVisible();
});
test('ficha (simulado): every state of a stage, its dates and its intervals', async ({ page }) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
link: 'recorded',
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const stages = historial(page).locator('app-stages li');
const text = async (n: number) => (await stages.nth(n).innerText()).replace(/\s+/g, ' ');
expect(await text(0)).toContain(`Registrada ${sample}`);
expect(await text(1)).toContain(
`Registrada ${plus(sample, 14)} Procedencia: Formulario de citología Desde anterior: 14 días Desde toma: 14 días`,
);
// colposcopy and diagnosis are inferred from dates: their intervals say so
expect(await text(2)).toContain(
`Inferida por fechas ${plus(sample, 30)} Desde anterior: 16 días (inferido) Desde toma: 30 días (inferido)`,
);
// a recorded biopsy link is recorded; the interval since an inferred stage is still inferred
expect(await text(3)).toContain(
`Registrada ${plus(sample, 50)} Desde anterior: 20 días (inferido) Desde toma: 50 días`,
);
expect(await text(4)).toContain(
`Inferida por fechas ${plus(sample, 70)} Desde anterior: 20 días (inferido)`,
);
const state = (n: number) =>
stages
.nth(n)
.locator('.node')
.evaluate(
(e) => getComputedStyle(e).backgroundColor + '|' + getComputedStyle(e).borderTopStyle,
);
expect(await state(0)).toBe('rgb(56, 123, 102)|solid'); // recorded
expect(await state(2)).toBe('rgb(66, 105, 160)|double'); // inferred
// an inferred biopsy link: inferred as well
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
expect(await text(3)).toContain('Inferida por fechas');
});
test('ficha (simulado): the cut-off hides what is dated after it; a biopsy asked and not reported is pending', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
});
const cutoff = plus(sample, 45); // after the request, before the report
await open(page, `${url.split('?')[0]}?corte=${cutoff}&citologia=${sample}`);
const stages = historial(page).locator('app-stages li');
const states = await stages.locator('.info span:nth-child(2)').allInnerTexts();
expect(states.map((s) => s.trim())).toEqual([
'Registrada',
'Registrada',
'Inferida por fechas',
'Pendiente',
'Sin dato',
]);
await expect(historial(page)).toContainText(`a la fecha de corte ${cutoff}`);
const pending = await stages
.nth(3)
.locator('.node')
.evaluate((e) => getComputedStyle(e).backgroundColor);
expect(pending).toBe('rgb(255, 241, 201)');
const unknown = await stages
.nth(4)
.locator('.node')
.evaluate((e) => getComputedStyle(e).borderTopStyle);
expect(unknown).toBe('dashed');
await expect(stages.nth(4)).toContainText('Sin fecha');
await expect(stages.nth(4)).toContainText('Desde toma: —');
// a cut-off before the sample: nothing is known
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
await withRoute(page, sample, { report: 14 });
await open(page, `${url.split('?')[0]}?corte=${plus(sample, -1)}&citologia=${sample}`);
expect(
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
).toEqual(Array(5).fill('Sin dato'));
});
test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tell zero from absent', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
[0, 0],
[5, 0.5, 0.4, 0.6],
]),
risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [
[0, 0.02, 0.01, 0.03],
[5, 0.98, 0.95, 1],
]),
risk('c', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]), // no immediate horizon
risk('d', 'Parcial v1', 'cacu.partial', '2026-05-01', [[0, 0.5]]), // no five-year horizon
]);
await open(page, url);
await expect(
page.getByRole('heading', { name: 'Supervivencia v3 · fecha índice 2026-02-01' }),
).toBeVisible();
await expect(
page.getByRole('heading', { name: 'Recurrencia v2 · fecha índice 2026-03-01' }),
).toBeVisible();
const at = async (label: string, nth: number) => drawn(scale(page, label, nth));
// group order follows the page's models: survival, recurrence, other, partial
const groups = await page.locator('.risk-scale').count();
expect(groups).toBe(8); // both horizons of four models
const model = async (n: number) => [await at(IMMEDIATE, n), await at(FIVE, n)];
const [survival, recurrence, other, partial] = [
await model(0),
await model(1),
await model(2),
await model(3),
];
expect(survival[0]).toMatchObject({ markers: 1, left: '0%', value: '0.0 %', grey: 0 }); // a real zero
expect(survival[1]).toMatchObject({ left: '50%', value: '50.0 %' });
expect(recurrence[0]).toMatchObject({ left: '2%', value: '2.0 %' });
expect(recurrence[1]).toMatchObject({ left: '98%', value: '98.0 %' });
expect(other[0]).toMatchObject({ markers: 0, grey: 1 }); // absent, not zero
expect(other[1]).toMatchObject({ left: '100%', value: '100.0 %' });
expect(partial[0]).toMatchObject({ left: '50%' });
expect(partial[1]).toMatchObject({ markers: 0, grey: 1 });
await expect(scale(page, IMMEDIATE, 2)).toContainText('No disponible');
await expect(scale(page, FIVE, 3)).toContainText('No disponible');
await expect(scale(page, FIVE, 0)).toContainText('IC 95 %: 40.0–60.0 %');
await expect(scale(page, FIVE, 1)).toContainText('IC 95 %: 95.0–100.0 %');
await expect(scale(page, IMMEDIATE, 0)).not.toContainText('IC 95 %'); // none published, none invented
// the descriptive note stays, and the model table and curve of rebuild are still there
await expect(page.getByText('no representan umbrales clínicos')).toBeVisible();
await expect(page.getByRole('columnheader', { name: 'Probabilidad', exact: true })).toBeVisible();
});
test('ficha (simulado): the scale is drawn in four equal segments with the numeric divisions', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
]);
await open(page, url);
const box = scale(page, FIVE);
await expect(box.locator('.risk-labels span')).toHaveText([
'0 %',
'25 %',
'50 %',
'75 %',
'100 %',
]);
const line = await box.locator('.risk-line').evaluate((e) => getComputedStyle(e).backgroundImage);
for (const colour of [
'rgb(66, 167, 126)',
'rgb(168, 194, 67)',
'rgb(223, 134, 64)',
'rgb(194, 66, 105)',
])
expect(line).toContain(colour);
// the marker sits at 50 % of the bar
const [bar, mark] = await Promise.all([
box.locator('.risk-plot').boundingBox(),
box.locator('.risk-marker').boundingBox(),
]);
expect(Math.abs(mark!.x + mark!.width / 2 - (bar!.x + bar!.width / 2))).toBeLessThan(3);
});
for (const width of [1440, 480]) {
test(`ficha (simulado) at ${width} px: the stages and the scales lay out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
link: 'recorded',
});
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
[0, 0],
[5, 0.98, 0.95, 1],
]),
risk('b', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]),
]);
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
await page.waitForTimeout(800);
expect(await layoutProblems(page)).toEqual([]);
const tops = await historial(page)
.locator('app-stages li .node')
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
// wide: one row of nodes; narrow: a column (each below the previous)
if (width > 700) expect(new Set(tops).size).toBe(1);
else {
expect(tops).toEqual([...tops].sort((a, b) => a - b));
expect(new Set(tops).size).toBe(5);
}
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
});
}
const code = (name: string, valueCode: string) => ({ url: EXT + name, valueCode });
const nodeOf = (page: Page, n: number) => historial(page).locator('app-stages li').nth(n);
/** A record, by the API, whose cytology (the latest of the first patients) satisfies `wanted`. */
async function recordWhere(page: Page, wanted: (report: any) => boolean) {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
const ids: string[] = patients.entry.map((e: any) => e.resource.id);
for (let i = 0; i < ids.length; i += 25) {
const subject = ids
.slice(i, i + 25)
.map((p) => 'Patient/' + p)
.join(',');
const found = await (
await page.request.get(`/api/cacu/fhir/DiagnosticReport?_count=200&subject=${subject}`)
).json();
for (const { resource: r } of found.entry ?? [])
if (r.code?.coding?.[0]?.code === 'cervical_cytology' && wanted(r))
return {
id: r.subject.reference.split('/')[1] as string,
sample: r.effectiveDateTime as string,
};
}
throw new Error('no record with those stages in the first patients');
}
const has = (r: any, name: string) => (r.extension ?? []).some((e: any) => e.url === EXT + name);
test('ficha: the stages say what the backend demonstrates, with their sources', async ({
page,
}) => {
const { id, sample } = await recordWhere(
page,
(r) => has(r, 'stage-colposcopy-state') && has(r, 'stage-biopsy-state'),
);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const states = await historial(page)
.locator('app-stages li .info span:nth-child(2)')
.allInnerTexts();
expect(states[0]).toBe('Registrada');
expect(states[2]).toBe('Inferida por fechas'); // colposcopy is always inferred
expect(['Inferida por fechas', 'Registrada']).toContain(states[3]);
const colposcopy = (await nodeOf(page, 2).innerText()).replace(/\s+/g, ' ');
expect(colposcopy).toMatch(/Procedencia: (Nota clínica|Orden de biopsia)/);
expect(colposcopy).toContain('Desde anterior:');
expect((await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ')).toMatch(
/Procedencia: (Asociación por fechas|Registro de la biopsia)/,
);
// the first two stages come from the form
expect(await nodeOf(page, 0).innerText()).toContain('Procedencia: Formulario de citología');
});
test('ficha (simulado): a stage the backend flags as ambiguous is drawn so, with no interval resting on it', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
extra: [
code('stage-biopsy-state', 'ambiguous'),
code('stage-biopsy-source', 'date-association'),
code('stage-colposcopy-state', 'inferred'),
code('stage-colposcopy-source', 'clinical-note'),
code('stage-colposcopy-source', 'biopsy-order'),
],
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
expect(biopsy).toContain(`Ambigua ${plus(sample, 50)}`);
expect(biopsy).toContain('Procedencia: Asociación por fechas');
expect(biopsy).toContain('Desde anterior: — Desde toma: —');
expect(
await nodeOf(page, 3)
.locator('.node')
.evaluate((e) => getComputedStyle(e).borderTopStyle),
).toBe('double');
// no interval rests on the ambiguous day, so the next stage has none from the previous one either
expect((await nodeOf(page, 4).innerText()).replace(/\s+/g, ' ')).toContain('Desde anterior: —');
// a colposcopy dated by a note and a biopsy order lists both sources
expect(await nodeOf(page, 2).innerText()).toContain(
'Procedencia: Nota clínica · Orden de biopsia',
);
});
test('ficha (simulado): a biopsy the backend says is pending shows its request, not a day', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
extra: [
code('stage-biopsy-state', 'pending'),
code('stage-biopsy-source', 'date-association'),
code('biopsy-link', 'inferred'),
],
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
expect(biopsy).toContain('Pendiente');
expect(biopsy).toContain(`Solicitada el ${plus(sample, 40)}`);
expect(biopsy).toContain('Desde toma: —');
// colposcopy and diagnosis are never pending: no request is known for them
expect(
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
).not.toContain('Pendiente' + 'x');
const states = (
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts()
).map((t) => t.trim());
expect(states.filter((t) => t === 'Pendiente')).toHaveLength(1);
});
// ---- the record's tests and its antecedents
const antecedents = (page: Page) => page.locator('[data-section=antecedentes]');
const tests = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Pruebas y resultados' }),
});
test('ficha: antecedents and gynecologic evaluation have their own section; tests keep their results', async ({
page,
}) => {
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const card = antecedents(page);
await expect(card).toBeVisible();
await expect(card).toContainText('no son diagnósticos confirmados');
await expect(card).toContainText(`Citología cervical · toma ${sample}`);
for (const title of [
'Detección de cáncer de cérvix',
'Condición ginecoobstétrica a la detección',
'Actualmente presenta',
'A la exploración se observa',
])
await expect(card.locator('dl.facts dt', { hasText: title })).toBeVisible();
// the earlier forms are collapsed, each with its own day
const earlier = card.locator('details.findings');
if (await earlier.count()) {
expect(await earlier.getAttribute('open')).toBeNull();
await earlier.locator('summary').click();
await expect(earlier.locator('tbody tr').first().locator('td').first()).toHaveText(
/\d{4}-\d{2}-\d{2}/,
);
}
// the tests keep date, study, report and the results of the study, without the form's antecedents
const table = tests(page);
await expect(table.getByRole('columnheader')).toHaveText([
'Toma',
'Estudio',
'Reporte',
'Resultados',
]);
const text = await table.innerText();
expect(text).toContain('Resultado (Bethesda)');
expect(text).not.toContain('Detección de cáncer de cérvix');
expect(text).not.toContain('A la exploración se observa');
// the extra findings are collapsed under their report
const findings = table.locator('details.findings').first();
await expect(findings.locator('summary')).toContainText('Hallazgos (');
expect(await findings.getAttribute('open')).toBeNull();
expect((await findings.locator('li').first().textContent())!.trim().length).toBeGreaterThan(0);
});
test('ficha (simulado): a missing antecedent says it is not documented; with none, no section', async ({
page,
}) => {
const { url } = await firstRecord(page);
const strip = (keep: string[]) =>
page.route('**/api/cacu/fhir/Observation**', async (route) => {
const response = await route.fetch();
const body = await response.json();
body.entry = (body.entry ?? []).filter((e: any) => {
const field = (e.resource.code?.coding?.[0]?.code ?? '').split('.').pop();
const antecedent = [
'screening_history',
'gynecologic_condition',
'presenting_symptom',
'cervix_appearance',
].includes(field);
return !antecedent || keep.includes(field);
});
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
await strip(['screening_history']);
await open(page, url);
const card = antecedents(page);
await expect(card.locator('dl.facts dd').first()).not.toHaveText('No documentado');
await expect(card.locator('dl.facts dd', { hasText: 'No documentado' })).toHaveCount(3);
await page.unroute('**/api/cacu/fhir/Observation**');
await strip([]);
await open(page, url);
await expect(antecedents(page)).toHaveCount(0);
// the record's tests are still there without them
await expect(tests(page).getByRole('table')).toBeVisible();
});
test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ page }) => {
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const saved = page.waitForEvent('download');
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
const download = await saved;
expect(download.suggestedFilename()).toBe('expediente-cacu.pdf');
const file = await download.path();
expect(file).toBeTruthy();
const { readFileSync } = await import('node:fs');
const bytes = readFileSync(file!);
expect(bytes.subarray(0, 4).toString()).toBe('%PDF');
expect(bytes.length).toBeGreaterThan(5_000);
});
// ---- the NCI reference comparison (experimental) and the institutional curves ---------------------
const REFERENCE = '**/api/cacu/fhir/Patient/*/$reference-risk*';
const section = (page: Page) => page.locator('[data-section=referencia-nci]');
const value = (p: any) =>
p.valueCode ?? p.valueString ?? p.valueDate ?? p.valueInteger ?? p.valueDecimal ?? p.valueBoolean;
/** The first patients' answers of the API, to find one with a given state (the data is synthetic). */
async function referenceWhere(page: Page, status: string) {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
for (const { resource } of patients.entry) {
const answer = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$reference-risk`);
if (!answer.ok()) throw new Error(`the reference operation answered ${answer.status()}`);
const body = await answer.json();
if (value(body.parameter.find((p: any) => p.name === 'status')) === status)
return { id: resource.id as string, body };
}
throw new Error(`no patient with the state ${status}`);
}
const part = (name: string, extra: object) => ({ name, ...extra });
const answerOf = (...parameter: object[]) => ({ resourceType: 'Parameters', parameter });
/** A resolved answer for fixtures, with the given horizons and comparisons. */
function fixture(
horizons: { years: number; reference?: number; comparison?: object[] }[],
more: object[] = [],
) {
return answerOf(
part('status', { valueCode: 'resolved' }),
part('experimental', { valueBoolean: true }),
part('cutoff', { valueDate: '2026-11-30' }),
part('scenario', {
part: [
part('table', { valueCode: 'screening' }),
part('label', { valueString: 'Tamizaje' }),
part('key', {
part: [
part('name', { valueCode: 'history' }),
part('value', { valueString: 'Cotest-negative' }),
],
}),
],
}),
part('source', {
part: [
part('id', { valueString: 'fixture-table' }),
part('file', { valueString: 'fixture.xlsx' }),
],
}),
...more,
...horizons.map((h) =>
part('horizon', {
part: [
part('years', { valueInteger: h.years }),
part('published', { valueBoolean: h.reference !== undefined }),
...(h.reference !== undefined ? [part('reference', { valueDecimal: h.reference })] : []),
...(h.comparison ?? []),
],
}),
),
);
}
const comparison = (status: string, reasons: string[], extra: object[] = []) =>
part('comparison', {
part: [
part('model', { valueCode: 'fixture.model' }),
part('title', { valueString: 'Modelo de prueba' }),
part('outcome', { valueString: 'CIN3+' }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const answerWith = (page: Page, body: object, status = 200) =>
page.route(REFERENCE, (route) =>
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }),
);
test('referencia NCI: a resolved cytology shows its reference with scenario, source and no institutional model', async ({
page,
}) => {
const { id, body } = await referenceWhere(page, 'resolved');
await open(page, `/indicadores/cacu/pacientes/${id}`);
const box = section(page);
await expect(box).toBeVisible();
await expect(box.locator('dd[data-status=resolved]')).toHaveText('Referencia disponible');
await expect(box).toContainText('Tamizaje');
await expect(box).toContainText('CIN3 o más grave (CIN3+)');
await expect(box).toContainText('Master_NCI_Risk_Table.xlsx');
const rows = box.locator('tbody tr');
await expect(rows).toHaveCount(2);
await expect(rows.first()).toContainText('Inmediato (al índice)');
await expect(rows.nth(1)).toContainText('5 años');
// the figures are the API's: percent with two decimals, and no institutional model is made up
const expected = body.parameter
.filter((p: any) => p.name === 'horizon')
.map((h: any) =>
(h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2),
);
for (const [i, pct] of expected.entries())
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`);
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
// the antecedents used are collapsed
const used = box.locator('details.used');
expect(await used.getAttribute('open')).toBeNull();
await used.locator('summary').click();
await expect(used).toContainText('Fila de origen');
await expect(used).toContainText('Citología evaluada');
// the other risk displays of the record are still there, and the reference is below the scales
await expect(scale(page, FIVE)).toBeVisible();
const [scales, reference] = await Promise.all([
scale(page, FIVE).boundingBox(),
box.boundingBox(),
]);
expect(reference!.y).toBeGreaterThan(scales!.y);
await expect(
page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
).toBeVisible();
});
test('referencia NCI: a cytology the tables cannot resolve says the state and why, with no figure', async ({
page,
}) => {
const { id } = await referenceWhere(page, 'unverifiable_correspondence');
await open(page, `/indicadores/cacu/pacientes/${id}`);
const box = section(page);
await expect(box.locator('dd[data-status=unverifiable_correspondence]')).toHaveText(
'Correspondencia no verificable',
);
await expect(box.locator('ul.why li').first()).not.toBeEmpty();
await expect(box.locator('table')).toHaveCount(0);
await expect(box).not.toContainText('%');
});
test('referencia NCI: with the feature off (404) the section is not there and the record is whole', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
{ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] },
404,
);
await open(page, url);
await expect(section(page)).toHaveCount(0);
await expect(scale(page, FIVE)).toBeVisible();
});
test('referencia NCI (simulado): a comparison that is valid shows the difference as institutional minus reference', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 5,
reference: 0.0027,
comparison: [
comparison(
'comparable',
[],
[
part('institutional', { valueDecimal: 0.0127 }),
part('institutional-low', { valueDecimal: 0.005 }),
part('institutional-high', { valueDecimal: 0.02 }),
part('difference-pp', { valueDecimal: 1 }),
],
),
],
},
]),
);
await open(page, url);
const row = section(page).locator('tbody tr').first();
await expect(row).toContainText('Modelo de prueba');
await expect(row).toContainText('1.27 %');
await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
await expect(row.locator('td').nth(3)).toContainText('+1.00');
await expect(row.locator('td').nth(3)).not.toContainText('No comparable');
});
test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 0,
reference: 0.0001,
comparison: [
comparison(
'not_comparable',
['outcome_differs', 'horizon_not_published_by_model', 'population_not_verified'],
[part('institutional', { valueDecimal: 0.05 })],
),
],
},
{ years: 5, reference: 0.0027 },
]),
);
await open(page, url);
const first = section(page).locator('tbody tr').first();
await expect(first.locator('td').nth(3)).toContainText('No comparable');
await expect(first.locator('td').nth(3)).toContainText(
'El desenlace del modelo no es el de la tabla (CIN3+)',
);
await expect(first.locator('td').nth(3)).toContainText(
'no publica una predicción a este horizonte',
);
await expect(first.locator('td').nth(3)).not.toContainText(/[+-]\d/); // no signed difference
await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted
});
test('referencia NCI (simulado): a year-one reference is a year, never the immediate risk; a blank is not zero', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
await open(page, url);
const rows = section(page).locator('tbody tr');
await expect(rows.first()).toContainText('1 año');
await expect(section(page)).not.toContainText('Inmediato');
await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %');
});
for (const width of [1440, 480]) {
test(`referencia NCI (simulado) at ${width} px: the section lays out cleanly beside the scales and curves`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await answerWith(
page,
fixture(
[
{
years: 0,
reference: 0.0001,
comparison: [
comparison(
'not_comparable',
['outcome_differs', 'population_not_verified'],
[part('institutional', { valueDecimal: 0.05 })],
),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
comparison(
'comparable',
[],
[
part('institutional', { valueDecimal: 0.0127 }),
part('difference-pp', { valueDecimal: 1 }),
],
),
],
},
],
[part('assumption', { valueString: 'un supuesto sin verificar' })],
),
);
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
]),
]);
await open(page, url);
await section(page).locator('details.used summary').click();
await page.waitForTimeout(800);
expect(await layoutProblems(page)).toEqual([]);
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
});
}
test('curvas (simulado): one series per model at its published horizons, its band only where it has intervals, and no NCI data', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
]),
risk('c', 'Sin intervalo v1', 'cacu.other', '2026-06-01', [
[2, 0.1],
[4, 0.2],
]),
risk('d', 'Un punto v1', 'cacu.partial', '2026-06-01', [[5, 0.5]]),
]);
await open(page, url);
const card = page.locator('details.curves');
await expect(card.locator('summary')).toHaveText('Curvas de probabilidad con su intervalo');
await expect(card).toHaveAttribute('open', '');
await expect(card.locator('li').first()).toContainText(
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 % (IC 95 %: 5.0–12.0 %); 3 años: 21.0 %',
);
const plot = await card.locator('.js-plotly-plot').evaluate((e: any) => ({
names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name),
series: Object.fromEntries(
e.data.filter((t: any) => t.mode?.includes('markers')).map((t: any) => [t.name, t.x]),
),
bands: e.data.filter((t: any) => t.fill === 'tonexty').map((t: any) => t.name),
ticks: e.layout.xaxis.tickvals,
title: e.layout.xaxis.title.text,
}));
expect(plot.series).toEqual({
'Riesgo LIEAG+': [1, 3, 5],
'Riesgo cáncer': [1, 3, 5],
'Sin intervalo': [2, 4],
'Un punto': [5],
});
expect(plot.bands).toEqual(['IC 95 % Riesgo LIEAG+', 'IC 95 % Riesgo cáncer']); // none for the models without intervals
expect(plot.ticks).toEqual([1, 2, 3, 4, 5]);
expect(plot.title).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
// the reference is a separate table: its 0.27 % is nowhere in the figure
expect(
JSON.stringify(await card.locator('.js-plotly-plot').evaluate((e: any) => e.data)),
).not.toContain('0.27');
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
});
-122
View File
@@ -1,122 +0,0 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+101 -331
View File
@@ -1,8 +1,6 @@
import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { statSync } from 'node:fs';
import { expect, Locator, Page, test } from '@playwright/test';
/** 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()}`));
@@ -11,7 +9,6 @@ function watch(page: Page): string[] {
return problems;
}
// The pages show only to someone signed in (the API itself answers everyone).
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
@@ -19,350 +16,123 @@ test.beforeEach(async ({ page }) => {
expect(signed.status()).toBe(204);
});
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
await page.goto('/conectar');
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page).toHaveURL(/\/conectar$/);
await page.getByRole('button', { name: 'Cuenta' }).click();
await page.getByRole('menuitem', { name: 'Salir' }).click();
await expect(page).toHaveURL(/\/login/);
await page.close();
});
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("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
test('tea indicators: every tab loads, and the follow-up list exports to Excel', async ({
page,
}) => {
const problems = watch(page);
const report = page.waitForResponse(
(r) =>
r.url().includes('MeasureReport') &&
r.url().includes('measure=cacu-eu7') &&
!r.url().includes('%2C'),
const listed = page.waitForResponse(
(r) => r.url().includes('/tea/fhir/Measure') && !r.url().includes('MeasureReport'),
);
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`,
);
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
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.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await expect(page.getByText('Progresión del proceso diagnóstico')).toBeVisible();
await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click();
const rows = page.locator('app-tab-seguimiento table tbody tr');
await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/);
const name = await downloaded(
page,
page.getByRole('button', { name: 'Exportar a Excel' }),
'xlsx',
);
expect(name).toMatch(/^tea-seguimiento-/);
await page.getByRole('tab', { name: 'Análisis de riesgo' }).click();
await expect(page.locator('app-tab-riesgos app-tea-list')).toBeVisible();
await expect(page.getByText('Cargando pacientes…')).toHaveCount(0);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
await expect(page.locator('app-tab-definiciones details')).toHaveCount(measures);
expect(problems).toEqual([]);
});
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).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 page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
await expect(page.getByText('Historial médico')).toBeVisible();
await expect(page.getByText('Pruebas y resultados')).toBeVisible();
await expect(
page.locator('app-paciente table').nth(1).locator('tbody tr').first(),
).not.toContainText('Sin estudios');
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
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');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click();
const first = page.locator('app-tab-seguimiento table tbody tr').first();
await expect(first.locator('td').first()).toHaveText(/^N-?\d{4}$/);
await first.getByRole('link', { name: 'Expediente' }).click();
await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
await expect(page.locator('app-tea-section').first()).toBeVisible();
const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf');
expect(record).toMatch(/^tea-seguimiento-/);
await page.getByRole('link', { name: 'Riesgo' }).click();
await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible();
await expect(page.locator('app-tea-section').first()).toBeVisible();
expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch(
/^tea-riesgos-/,
);
expect(problems).toEqual([]);
});
test('conectar: open the hospital pipeline, preview a source, run it to success', async ({
test('tea gobernanza: every section in sync mode, and the preview saved as PDF', async ({
page,
}) => {
const problems = watch(page);
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.goto('/gobernanza/tea');
await page.getByLabel('Modo').selectOption('sync');
await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).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([]);
});
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('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');
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');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
});
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
page,
}) => {
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
const problems = watch(page);
await page.goto('/conectar');
await page.getByLabel('Nueva canalización').fill('asistente');
await page.getByLabel('Nueva canalización').press('Enter');
await page.getByRole('button', { name: 'Fuente de datos' }).click();
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
await page.locator('[data-type="sqlserver"]').click();
await page.locator('[data-field="host"]').fill(site.hostname);
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
await page.locator('mat-select[data-field="table"]').click();
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it');
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
await page.getByRole('button', { name: 'Cancelar' }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
expect(problems).toEqual([]);
});
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
* opportunity section on, in order, and the kind of each plot (its traces' types). */
function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}
-88
View File
@@ -1,88 +0,0 @@
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',
});
});
}
+2492 -213
View File
File diff suppressed because it is too large Load Diff
+2116 -263
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.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"pdfmake": "0.3.15",
"plotly.js": "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.5",
"@types/pdfmake": "0.3.3",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
+1 -5
View File
@@ -1,8 +1,5 @@
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,
@@ -12,10 +9,9 @@ export default defineConfig({
use: {
baseURL: 'http://127.0.0.1:4310',
viewport: { width: 1440, height: 1000 },
actionTimeout: 60_000, // a stuck step fails, not the whole run
actionTimeout: 60_000,
},
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,2 +1 @@
// `/api` to the API the e2e run started (API_URL).
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
+100
View File
@@ -0,0 +1,100 @@
import type { Observation, ObservationComponent } from 'fhir/r4';
import { describe, expect, it } from 'vitest';
import { ados2Component, ados2Groups } from './ados2';
import { EXT } from './fhir';
function item(
field: string,
domain: string,
subdomain: string,
code: string,
title: string,
value?: number,
): ObservationComponent {
return {
code: {
coding: [{ code: `ados2.${field}` }, { code, display: title }],
text: title,
},
extension: [
{ url: EXT + 'ados2-domain', valueCoding: { code: domain[0], display: domain } },
{ url: EXT + 'ados2-subdomain', valueCoding: { code: subdomain, display: subdomain } },
],
valueQuantity: value == null ? undefined : { value },
};
}
const AS = 'Afectación social (AS)';
const CRR = 'Comportamiento restringido y repetitivo (CRR)';
const observation: Observation = {
resourceType: 'Observation',
status: 'final',
code: { coding: [{ code: 'ados2' }] },
component: [
{ code: { coding: [{ code: 'ados2.module' }] }, valueCodeableConcept: { text: 'Módulo 1' } },
item('pointing', AS, 'Comunicación', 'A-7', 'Señalar', 2),
item('gestures', AS, 'Comunicación', 'A-8', 'Gestos', 1),
item(
'unusual_eye_contact',
AS,
'Interacción social recíproca',
'B-1',
'Contacto visual inusual',
),
item(
'intonation',
CRR,
'Comportamientos restringidos y repetitivos',
'A-3',
'Entonación de las vocalizaciones o verbalizaciones',
3,
),
{ code: { coding: [{ code: 'ados2.response_to_name' }] } },
],
};
describe('Ítems del ADOS-2', () => {
it('agrupa los ítems del módulo por dominio y subdominio en su orden', () => {
expect(ados2Groups(observation)).toEqual([
{
domain: AS,
subdomains: [
{
subdomain: 'Comunicación',
items: [
{ code: 'A-7', title: 'Señalar', score: 2 },
{ code: 'A-8', title: 'Gestos', score: 1 },
],
},
{
subdomain: 'Interacción social recíproca',
items: [{ code: 'B-1', title: 'Contacto visual inusual', score: undefined }],
},
],
},
{
domain: CRR,
subdomains: [
{
subdomain: 'Comportamientos restringidos y repetitivos',
items: [
{
code: 'A-3',
title: 'Entonación de las vocalizaciones o verbalizaciones',
score: 3,
},
],
},
],
},
]);
expect(ados2Groups(undefined)).toEqual([]);
});
it('encuentra el ítem de una asociación por su número', () => {
expect(ados2Component(observation, 2)?.code.text).toBe('Señalar');
expect(ados2Component(observation, 8)?.code.coding?.[0].code).toBe('ados2.response_to_name');
expect(ados2Component(observation, 0)).toBeUndefined();
});
});
+82
View File
@@ -0,0 +1,82 @@
import type { Observation, ObservationComponent } from 'fhir/r4';
import { code, ext } from './fhir';
export const ADOS2_ITEMS = [
'vocalization_directed',
'pointing',
'gestures',
'unusual_eye_contact',
'facial_expressions',
'gaze_integration',
'shared_enjoyment',
'response_to_name',
'ignoring',
'requesting',
'showing',
'joint_attention_initiation',
'joint_attention_response',
'social_overtures_quality',
'social_overtures_caregiver',
'reciprocal_communication',
'rapport_quality',
'intonation',
'stereotyped_language',
'unusual_sensory_interest',
'hand_finger_mannerisms',
'repetitive_interests',
];
export interface Ados2Item {
code: string;
title: string;
score?: number;
}
export interface Ados2Subdomain {
subdomain: string;
items: Ados2Item[];
}
export interface Ados2Domain {
domain: string;
subdomains: Ados2Subdomain[];
}
function coded(component: ObservationComponent, name: string): string {
const coding = ext(component, name)?.valueCoding;
return coding?.display ?? coding?.code ?? '';
}
export function ados2Groups(observation: Observation | undefined): Ados2Domain[] {
const groups: Ados2Domain[] = [];
for (const component of observation?.component ?? []) {
const item = component.code.coding?.[1];
if (!ext(component, 'ados2-domain') || !item?.code) continue;
const domain = coded(component, 'ados2-domain');
const subdomain = coded(component, 'ados2-subdomain');
let group = groups.at(-1);
if (!group || group.domain !== domain) {
group = { domain, subdomains: [] };
groups.push(group);
}
let sub = group.subdomains.at(-1);
if (!sub || sub.subdomain !== subdomain) {
sub = { subdomain, items: [] };
group.subdomains.push(sub);
}
sub.items.push({
code: item.code,
title: component.code.text ?? item.display ?? item.code,
score: component.valueQuantity?.value,
});
}
return groups;
}
export function ados2Component(
observation: Observation | undefined,
number: number,
): ObservationComponent | undefined {
const field = ADOS2_ITEMS[number - 1];
return observation?.component?.find((c) => field && code(c.code) === `ados2.${field}`);
}
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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
@@ -0,0 +1,33 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface EegStudiesSummary$Params {
}
export function eegStudiesSummary(http: HttpClient, rootUrl: string, params?: EegStudiesSummary$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: number;
}>> {
const rb = new RequestBuilder(rootUrl, eegStudiesSummary.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: number;
}>;
})
);
}
eegStudiesSummary.PATH = '/tea/eegs/summary';
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Health } from '../../models/health';
export interface ExecutionHealth$Params {
mode?: ('sync' | 'local' | 'remote' | null);
scheduler?: (string | null);
reference?: (string | null);
}
export function executionHealth(http: HttpClient, rootUrl: string, params?: ExecutionHealth$Params, context?: HttpContext): Observable<StrictHttpResponse<Health>> {
const rb = new RequestBuilder(rootUrl, executionHealth.PATH, 'get');
if (params) {
rb.query('mode', params.mode, {});
rb.query('scheduler', params.scheduler, {});
rb.query('reference', params.reference, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Health>;
})
);
}
executionHealth.PATH = '/execution/health';
@@ -0,0 +1,30 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
+54
View File
@@ -0,0 +1,54 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface EegSummary$Params {
domain: Domain;
/**
* months: the domain's follow-up list over that window up to the cut-off
*/
'follow-up-window'?: (number | null);
/**
* explicit window start that overrides follow-up-window
*/
'follow-up-start'?: (string | null);
/**
* default: the last day with data
*/
'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null);
}
export function eegSummary(http: HttpClient, rootUrl: string, params: EegSummary$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, eegSummary.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-start', params['follow-up-start'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
eegSummary.PATH = '/{domain}/fhir/Patient/$eeg-summary';
+6 -6
View File
@@ -18,6 +18,11 @@ 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
*/
@@ -34,11 +39,6 @@ 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,10 +7,12 @@ 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<{
@@ -19,6 +21,7 @@ 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
@@ -0,0 +1,42 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Curve$Params {
domain: Domain;
name: string;
version: number;
feature?: string;
}
export function curve(http: HttpClient, rootUrl: string, params: Curve$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
[key: string]: any;
}>>> {
const rb = new RequestBuilder(rootUrl, curve.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('version', params.version, {});
rb.query('feature', params.feature, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<{
[key: string]: any;
}>>;
})
);
}
curve.PATH = '/models/{domain}/{name}/versions/{version}/curve';
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ExportModels$Params {
domain: Domain;
names?: (Array<string> | null);
versions?: 'champion' | 'latest' | 'all';
}
export function exportModels(http: HttpClient, rootUrl: string, params: ExportModels$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, exportModels.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('names', params.names, {});
rb.query('versions', params.versions, {});
}
return http.request(
rb.build({ responseType: 'blob', accept: 'application/zip', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
exportModels.PATH = '/models/{domain}/export';
+41
View File
@@ -0,0 +1,41 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyImportModels } from '../../models/body-import-models';
import { Domain } from '../../models/domain';
export interface ImportModels$Params {
domain: Domain;
sha256: string;
body: BodyImportModels
}
export function importModels(http: HttpClient, rootUrl: string, params: ImportModels$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, importModels.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.query('sha256', params.sha256, {});
rb.body(params.body, 'multipart/form-data');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
importModels.PATH = '/models/{domain}/import';
+40
View File
@@ -0,0 +1,40 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Lineage$Params {
domain: Domain;
name: string;
version: number;
}
export function lineage(http: HttpClient, rootUrl: string, params: Lineage$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
}>> {
const rb = new RequestBuilder(rootUrl, lineage.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('version', params.version, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: any;
}>;
})
);
}
lineage.PATH = '/models/{domain}/{name}/versions/{version}/lineage';
+40
View File
@@ -0,0 +1,40 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Retire$Params {
domain: Domain;
name: string;
version: number;
}
export function retire(http: HttpClient, rootUrl: string, params: Retire$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, retire.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('version', params.version, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
retire.PATH = '/models/{domain}/{name}/versions/{version}/retire';
+35
View File
@@ -0,0 +1,35 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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';
+38
View File
@@ -0,0 +1,38 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface TrainingInputs$Params {
domain: Domain;
name: string;
}
export function trainingInputs(http: HttpClient, rootUrl: string, params: TrainingInputs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
}>> {
const rb = new RequestBuilder(rootUrl, trainingInputs.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: any;
}>;
})
);
}
trainingInputs.PATH = '/models/{domain}/{name}/inputs';
@@ -0,0 +1,43 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyUploadTrainingInputs } from '../../models/body-upload-training-inputs';
import { Domain } from '../../models/domain';
export interface UploadTrainingInputs$Params {
domain: Domain;
name: string;
set: string;
body: BodyUploadTrainingInputs
}
export function uploadTrainingInputs(http: HttpClient, rootUrl: string, params: UploadTrainingInputs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
}>> {
const rb = new RequestBuilder(rootUrl, uploadTrainingInputs.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('set', params.set, {});
rb.body(params.body, 'multipart/form-data');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: any;
}>;
})
);
}
uploadTrainingInputs.PATH = '/models/{domain}/{name}/inputs/{set}/files';
+40
View File
@@ -0,0 +1,40 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface VersionChecks$Params {
domain: Domain;
name: string;
version: number;
}
export function versionChecks(http: HttpClient, rootUrl: string, params: VersionChecks$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
}>> {
const rb = new RequestBuilder(rootUrl, versionChecks.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('version', params.version, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: any;
}>;
})
);
}
versionChecks.PATH = '/models/{domain}/{name}/versions/{version}/checks';
+32
View File
@@ -0,0 +1,32 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { PreviewStatus } from '../../models/preview-status';
export interface PreviewStatus$Params {
run_id: string;
}
export function previewStatus(http: HttpClient, rootUrl: string, params: PreviewStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<PreviewStatus>> {
const rb = new RequestBuilder(rootUrl, previewStatus.PATH, 'get');
if (params) {
rb.path('run_id', params.run_id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<PreviewStatus>;
})
);
}
previewStatus.PATH = '/tea/preview/{run_id}';
@@ -7,17 +7,18 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyStartPreview } from '../../models/body-start-preview';
export interface TerminateRun$Params {
run_id: string;
export interface StartPreview$Params {
body: BodyStartPreview
}
export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
export function startPreview(http: HttpClient, rootUrl: string, params: StartPreview$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, terminateRun.PATH, 'post');
const rb = new RequestBuilder(rootUrl, startPreview.PATH, 'post');
if (params) {
rb.path('run_id', params.run_id, {});
rb.body(params.body, 'multipart/form-data');
}
return http.request(
@@ -32,4 +33,4 @@ export function terminateRun(http: HttpClient, rootUrl: string, params: Terminat
);
}
terminateRun.PATH = '/runs/{run_id}/terminate';
startPreview.PATH = '/tea/preview';
+32
View File
@@ -0,0 +1,32 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { 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
@@ -0,0 +1,39 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
import { RunSummary } from '../../models/run-summary';
export interface RunHistory$Params {
job?: (string | null);
domain?: (Domain | null);
limit?: number;
before?: (string | null);
}
export function runHistory(http: HttpClient, rootUrl: string, params?: RunHistory$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<RunSummary>>> {
const rb = new RequestBuilder(rootUrl, runHistory.PATH, 'get');
if (params) {
rb.query('job', params.job, {});
rb.query('domain', params.domain, {});
rb.query('limit', params.limit, {});
rb.query('before', params.before, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<RunSummary>>;
})
);
}
runHistory.PATH = '/runs';
+5 -6
View File
@@ -7,17 +7,18 @@ 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<{
[key: string]: string;
}>> {
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<Run>> {
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(
@@ -25,9 +26,7 @@ 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<{
[key: string]: string;
}>;
return r as StrictHttpResponse<Run>;
})
);
}
+36 -2
View File
@@ -9,6 +9,10 @@ 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';
@@ -45,12 +49,28 @@ 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';
@@ -59,6 +79,8 @@ export type { ReadReport$Json$Params as ReadReport$Json$Params } from './fn/mode
export { readReport$Json as readReport$Json } from './fn/models/read-report-json';
export 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';
@@ -73,14 +95,24 @@ 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 { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { CancelRun$Params as CancelRun$Params } from './fn/runs/cancel-run';
export { cancelRun as cancelRun } from './fn/runs/cancel-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';
@@ -111,6 +143,8 @@ 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 { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
+25 -1
View File
@@ -2,21 +2,30 @@
/* 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';
@@ -26,28 +35,43 @@ 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 { Reference } from './models/reference';
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 { 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';
+6 -2
View File
@@ -2,12 +2,16 @@
/* 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>;
relation?: Array<Relation>;
regions: Array<{
[key: string]: any;
}>;
valid: (boolean | null);
}
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
import { Scope } from '../models/scope';
export interface AnalyzeRequest {
execution?: (Execution | null);
scope?: Scope;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
export interface Analyze {
execution?: (Execution | null);
}
+6
View File
@@ -0,0 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyImportModels {
file: string;
}
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyStartPreview {
ados2?: (Blob | null);
birth_date?: (string | null);
edf: Blob;
pipeline?: string;
}
@@ -0,0 +1,6 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUploadTrainingInputs {
files: Array<Blob>;
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Cancel {
id: string;
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
status: string;
}
+32
View File
@@ -0,0 +1,32 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* EDF files (a column of file hashes) to the facts their header holds: patient code, sex,
* birth date, recording date, record code, duration and channel count, as `edf_*` columns.
* An unreadable file keeps its row with `edf_error` set.
*
* Use a filesystem source (`dlt.sources.filesystem:filesystem`) with the uploads folder as
* `bucket_url`, `file_glob: "*.edf"`, and `then: "persistance.readers:read_bytes"`. Read its
* `content` column with this node. Map `edf_patient_code`, `edf_birth_date`, and `edf_sex` to
* identity's `record_number`, `birth_date`, and `sex`, using the site's formats and ConceptMap.
*
* The patient code must match the hospital's record number including its prefix. Feed the
* identity map into the pipeline's link node alongside the hospital identity source. Map
* `edf_study_date` to `study_date` (format `%Y-%m-%d`), `edf_record_code` to `lab_record_id`,
* and `content` to `edf`, then feed that map and the link into a target with entity `eeg`.
*/
export interface Edf {
column: string;
id: string;
inputs?: Array<string>;
kind?: 'edf';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* What a request or a job config carries: None means the deployment's default.
*/
export interface Execution {
mode?: ('sync' | 'local' | 'remote' | null);
scheduler?: (string | null);
}
+20
View File
@@ -0,0 +1,20 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Health {
dashboard_ok?: (boolean | null);
dashboard_url?: (string | null);
error?: (string | null);
expected_workers?: (number | null);
latency_ms?: (number | null);
mode: 'sync' | 'local' | 'remote';
reachable: boolean;
reference?: ({
[key: string]: any;
} | null);
scheduler: (string | null);
threads?: (number | null);
version_error?: (string | null);
versions_ok?: (boolean | null);
workers?: (number | null);
}
-6
View File
@@ -1,16 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric {
code: string;
electrodes?: Array<Site>;
median?: (number | null);
model: (string | null);
outside: (number | null);
p5?: (number | null);
p95?: (number | null);
value: number;
z: (number | null);
zones?: Array<Site>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Options {
default_mode: 'sync' | 'local' | 'remote';
schedulers: Array<string>;
}
+2 -1
View File
@@ -1,6 +1,7 @@
/* 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';
@@ -11,5 +12,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 | Fhir | Join | Link | Target)>;
nodes: Array<(Source | Read | Route | Map | Extract | Edf | Fhir | Join | Link | Target)>;
}
+16
View File
@@ -0,0 +1,16 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface PreviewAdos2 {
classification: (string | null);
css: (number | null);
evaluation_date: (string | null);
items: {
[key: string]: (number | null);
};
module: (string | null);
read: Array<string>;
titles: {
[key: string]: string;
};
}
+21
View File
@@ -0,0 +1,21 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { PreviewMetric } from '../models/preview-metric';
export interface PreviewEeg {
age_months: (number | null);
bad_channels: (number | null);
channels: (number | null);
checks: Array<{
[key: string]: any;
}>;
clean_fraction: (number | null);
duration_min: (number | null);
error: (string | null);
level: string;
line_noise_db: (number | null);
metrics: Array<PreviewMetric>;
recorded_on: (string | null);
sleep: (boolean | null);
valid: (boolean | null);
}
+17
View File
@@ -0,0 +1,17 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Score } from '../models/score';
import { Site } from '../models/site';
export interface PreviewMetric {
code: string;
electrodes: {
[key: string]: Site;
};
model: (string | null);
score: (Score | null);
value: (number | null);
zones: {
[key: string]: Site;
};
}
+10
View File
@@ -0,0 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { PreviewAdos2 } from '../models/preview-ados-2';
import { PreviewEeg } from '../models/preview-eeg';
export interface PreviewResult {
ados2: (PreviewAdos2 | null);
eeg: PreviewEeg;
warnings: Array<string>;
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { PreviewResult } from '../models/preview-result';
export interface PreviewStatus {
result: (PreviewResult | null);
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
}
+21
View File
@@ -0,0 +1,21 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Tasks } from '../models/tasks';
import { Worker } from '../models/worker';
/**
* The run tag's JSON; the API returns it as it is.
*/
export interface Progress {
done: number;
elapsed_s: number;
eta_s: (number | null);
mode: 'sync' | 'local' | 'remote';
phase: string;
scheduler: (string | null);
tasks?: (Tasks | null);
total: number;
updated_at: string;
workers?: Array<Worker>;
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Reference {
line_hz?: 50 | 60;
/**
* Carpeta dentro de TEA_REFERENCE_ROOT con los EDF y edades.csv
*/
name: string;
}
-25
View File
@@ -1,25 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
+12
View File
@@ -0,0 +1,12 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface RunSummary {
domain: (string | null);
ended: (number | null);
id: string;
job: string;
started: (number | null);
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
status: string;
}
+22
View File
@@ -0,0 +1,22 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Progress } from '../models/progress';
import { Step } from '../models/step';
export interface Run {
domain: (string | null);
ended: (number | null);
error: (string | null);
id: string;
info: Array<string>;
job: string;
outputs?: ({
[key: string]: any;
} | null);
progress: (Progress | null);
started: (number | null);
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelling' | 'cancelled';
status: string;
steps: Array<Step>;
warnings: Array<string>;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* Which EEGs an analysis takes: the pending ones, the first `n` of them, or the named
* ones (re-analysis), each named by the `id` that `/tea/eegs` shows.
*/
export interface Scope {
ids?: Array<string>;
mode?: 'pending' | 'first_n' | 'ids';
n?: (number | null);
}
+10
View File
@@ -0,0 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Score {
median: (number | null);
outside: (number | null);
p5: (number | null);
p95: (number | null);
z: (number | null);
}
+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 {
site: string;
value: number;
z: (number | null);
score: (Score | null);
value: (number | null);
}
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Step {
ended: (number | null);
key: string;
started: (number | null);
status: string;
}
+10
View File
@@ -0,0 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Tasks {
erred?: number;
memory?: number;
processing?: number;
queued?: number;
waiting?: number;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface TrainingConfig {
defaults: {
[key: string]: any;
};
domain: string;
json_schema: {
[key: string]: any;
};
name: string;
}
+8
View File
@@ -1,7 +1,15 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution';
import { Reference } from '../models/reference';
export interface Training {
/**
* Fecha de corte de los datos (por omisión, hoy)
*/
as_of?: (string | null);
execution?: (Execution | null);
models?: Array<string>;
reference?: (Reference | null);
}
+1
View File
@@ -11,5 +11,6 @@ export interface Version {
[key: string]: string;
};
reports: Array<string>;
status: 'champion' | 'retired' | 'candidate';
version: number;
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Worker {
cpu_pct: number;
executing: number;
memory_bytes: number;
memory_limit: (number | null);
name: string;
threads: number;
}
+6
View File
@@ -13,6 +13,12 @@ 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' },
loadComponent: () => import('./paciente/tea-patient').then((m) => m.TeaRisk),
},
{
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');
const domain = route.paramMap.get('domain') ?? route.data['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
@@ -0,0 +1,53 @@
import { TestBed } from '@angular/core/testing';
import { MatDialog } from '@angular/material/dialog';
import { describe, expect, it, vi } from 'vitest';
import { CardActions } from './card-actions';
describe('CardActions', () => {
it('opens the published definition and emits back only through the filtered action', async () => {
const fixture = TestBed.createComponent(CardActions);
fixture.componentRef.setInput('measures', [
{
resourceType: 'Measure',
status: 'active',
title: 'Oportunidad',
description: 'Definición publicada',
group: [
{
population: [
{
code: { text: 'Numerador' },
criteria: { language: 'text/plain', description: 'Casos oportunos' },
},
{ criteria: { language: 'text/plain' } },
],
},
],
},
]);
const back = vi.fn();
fixture.componentInstance.back.subscribe(back);
fixture.detectChanges();
const host: HTMLElement = fixture.nativeElement;
expect(host.textContent).not.toContain('Volver');
host.querySelector<HTMLButtonElement>('[aria-label="Ver definición"]')!.click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(dialog.textContent).toContain('Oportunidad');
expect(dialog.textContent).toContain('Definición publicada');
expect(dialog.textContent).toContain('Numerador');
expect(dialog.textContent).toContain('Casos oportunos');
expect(dialog.textContent).toContain('Sin definición publicada');
TestBed.inject(MatDialog).closeAll();
fixture.componentRef.setInput('filtered', true);
fixture.detectChanges();
[...host.querySelectorAll('button')]
.find((button) => button.textContent?.trim() === 'Volver')!
.click();
expect(back).toHaveBeenCalledOnce();
});
});
+72
View File
@@ -0,0 +1,72 @@
import { Component, inject, input, output, TemplateRef } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatMenuModule } from '@angular/material/menu';
import type { Measure } from 'fhir/r4';
@Component({
selector: 'app-card-actions',
imports: [NgTemplateOutlet, MatButtonModule, MatDialogModule, MatMenuModule],
template: `
<button mat-icon-button type="button" aria-label="Ver definición" (click)="open(definition)">
?
</button>
@if (settings(); as content) {
<button mat-button type="button" [matMenuTriggerFor]="menu">Configuración</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
<ng-container [ngTemplateOutlet]="content" />
</ng-template>
</mat-menu>
}
@if (filtered()) {
<button mat-button type="button" (click)="back.emit()">Volver</button>
}
<ng-template #definition>
<h2 mat-dialog-title>Definición</h2>
<mat-dialog-content>
@for (measure of measures(); track $index) {
<h3>{{ measure.title }}</h3>
@if (measure.description) {
<p>{{ measure.description }}</p>
}
@for (group of measure.group ?? []; track $index) {
@for (population of group.population ?? []; track $index) {
<p>
@if (population.code?.text; as text) {
<strong>{{ text }}</strong>
}
@if (population.criteria.description; as description) {
{{ description }}
} @else if (!population.code?.text) {
Sin definición publicada
}
</p>
} @empty {
<p>Sin definición publicada</p>
}
} @empty {
<p>Sin definición publicada</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cerrar</button>
</mat-dialog-actions>
</ng-template>
`,
styles: ':host { display: inline-flex; align-items: center; gap: var(--space-1); }',
})
export class CardActions {
private readonly dialog = inject(MatDialog);
readonly measures = input.required<Measure[]>();
readonly settings = input<TemplateRef<unknown>>();
readonly filtered = input(false);
readonly back = output<void>();
protected open(template: TemplateRef<unknown>): void {
this.dialog.open(template);
}
}
+2 -1
View File
@@ -59,7 +59,6 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
export const KINDS: Record<Kind, string> = {
source: 'Fuente de datos',
read: 'Leer documentos',
@@ -67,6 +66,7 @@ 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,6 +79,7 @@ export const HELP: Record<Kind, string> = {
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
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,14 +1,3 @@
import type { Figure } from './plot';
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
export const METRIC_NAMES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
@@ -57,88 +46,3 @@ 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
@@ -1,69 +0,0 @@
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
@@ -0,0 +1,100 @@
import type { Bundle, Patient } from 'fhir/r4';
import { describe, expect, it, vi } from 'vitest';
import { allRows, downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index';
const mocks = vi.hoisted(() => {
const toFile = vi.fn();
const download = vi.fn();
return {
toFile,
write: vi.fn().mockReturnValue({ toFile }),
download,
createPdf: vi.fn().mockReturnValue({ download }),
addVirtualFileSystem: vi.fn(),
fonts: { 'Roboto-Regular.ttf': 'base64' },
};
});
vi.mock('write-excel-file/browser', () => ({ default: mocks.write }));
vi.mock('pdfmake/build/pdfmake', () => ({
default: { createPdf: mocks.createPdf, addVirtualFileSystem: mocks.addVirtualFileSystem },
}));
vi.mock('pdfmake/build/vfs_fonts', () => ({ default: mocks.fonts }));
const name = 'tea-indicadores-2026-11-30';
describe('export', () => {
it('writes capped data with a frozen header, a filter, and a parameters sheet', async () => {
const sheet = {
name: 'Indicadores',
columns: [{ header: 'Total', key: 'total', type: 'number' as const }],
rows: Array.from({ length: MAX_ROWS + 1 }, (_, total) => ({ total })),
};
await downloadXlsx(name, [sheet], { Periodo: '2026-11' });
expect(mocks.write).toHaveBeenCalledWith(
[
expect.objectContaining({ sheet: 'Indicadores', stickyRowsCount: 1 }),
expect.objectContaining({
sheet: 'Parámetros',
data: [expect.any(Array), ['Periodo', '2026-11']],
}),
],
expect.any(Object),
);
const [[dataSheet], options] = mocks.write.mock.calls[0];
expect(dataSheet.data).toHaveLength(MAX_ROWS + 2);
expect(dataSheet.data[MAX_ROWS]).toEqual([MAX_ROWS - 1]);
expect(dataSheet.data.at(-1)).toEqual([expect.stringContaining(String(MAX_ROWS))]);
const { transform } = options.features[0].files.transform['xl/worksheets/sheet{id}.xml'];
const xml = '<worksheet><sheetData><row/></sheetData></worksheet>';
expect(transform(xml, {}, { sheetIndex: 0 })).toContain(
`</sheetData><autoFilter ref="A1:A${MAX_ROWS + 1}"/>`,
);
expect(transform(xml, {}, { sheetIndex: 1 })).toBe(xml);
expect(mocks.toFile).toHaveBeenCalledWith(`${name}.xlsx`);
});
it('accepts domain, page, and date and refuses an id-like part', async () => {
expect(safeName(['tea', 'indicadores', '2026-11-30'])).toBe(name);
expect(() => safeName(['tea', 'patient-4821', '2026-11-30'])).toThrow();
await expect(downloadPdf('tea-patient-4821-2026-11-30', [])).rejects.toThrow();
});
it('follows next links, skipping empty entries and stopping inside the last page', async () => {
const patient = (id: string): Patient => ({ resourceType: 'Patient', id });
const bundle = (patients: Patient[], next: string): Bundle => ({
resourceType: 'Bundle',
type: 'searchset',
entry: [{}, ...patients.map((resource) => ({ resource }))],
link: [{ relation: 'next', url: next }],
});
const getPage = vi
.fn<(url: string) => Promise<Bundle>>()
.mockResolvedValueOnce(bundle([patient('1')], '/page/2'))
.mockResolvedValueOnce(bundle([patient('2'), patient('3')], '/page/3'));
await expect(allRows<Patient>('/page/1', getPage, 2)).resolves.toEqual([
patient('1'),
patient('2'),
]);
expect(getPage.mock.calls).toEqual([['/page/1'], ['/page/2']]);
});
it('passes the institutional header and generated timestamp footer to pdfmake', async () => {
const content = [{ text: 'Indicadores' }];
await downloadPdf(name, content);
expect(mocks.addVirtualFileSystem).toHaveBeenCalledWith(mocks.fonts);
expect(mocks.createPdf).toHaveBeenCalledWith(
expect.objectContaining({
content,
header: expect.objectContaining({ stack: ['ISSSTELEON', 'Plataforma de Indicadores'] }),
footer: expect.any(Function),
}),
);
const [definition] = mocks.createPdf.mock.calls[0];
expect(definition.footer(2, 4).text).toMatch(/^Página 2 de 4 · Generado el .+$/);
expect(mocks.download).toHaveBeenCalledWith(`${name}.pdf`);
});
});
+20
View File
@@ -0,0 +1,20 @@
import type { Bundle } from 'fhir/r4';
import { MAX_ROWS } from './xlsx';
export async function allRows<T>(
first: string,
getPage: (url: string) => Promise<Bundle>,
max = MAX_ROWS,
): Promise<T[]> {
const rows: T[] = [];
let next: string | undefined = first;
while (next && rows.length < max) {
const page = await getPage(next);
for (const { resource } of page.entry ?? []) {
if (resource) rows.push(resource as T);
if (rows.length >= max) return rows;
}
next = page.link?.find(({ relation }) => relation === 'next')?.url;
}
return rows;
}
+4
View File
@@ -0,0 +1,4 @@
export { allRows } from './fetch-all';
export { downloadPdf, type PdfContent } from './pdf';
export { safeName } from './safe-name';
export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx';
+31
View File
@@ -0,0 +1,31 @@
import type { Content } from 'pdfmake/interfaces';
import { validateName } from './safe-name';
export type { Content as PdfContent } from 'pdfmake/interfaces';
export async function downloadPdf(name: string, content: Content[]): Promise<void> {
const filename = `${validateName(name)}.pdf`;
const [{ default: pdfMake }, { default: fonts }] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
]);
pdfMake.addVirtualFileSystem(fonts);
const generatedAt = new Intl.DateTimeFormat('es-MX', {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date());
await pdfMake
.createPdf({
content,
pageMargins: [40, 65, 40, 45],
header: {
stack: ['ISSSTELEON', 'Plataforma de Indicadores'],
margin: [40, 20, 40, 0],
},
footer: (page, pages) => ({
text: `Página ${page} de ${pages} · Generado el ${generatedAt}`,
margin: [40, 10, 40, 0],
}),
})
.download(filename);
}
+34
View File
@@ -0,0 +1,34 @@
const domains = new Set(['cacu', 'cama', 'tea']);
const pages = new Set([
'indicadores',
'trazabilidad',
'riesgos',
'seguimiento',
'definiciones',
'gobernanza',
'revision',
'conectar',
]);
export function safeName(parts: string[]): string {
const [domain, page, date] = parts;
if (
parts.length !== 3 ||
!domains.has(domain) ||
!pages.has(page) ||
!/^\d{4}-\d{2}-\d{2}$/.test(date)
) {
throw new Error('El nombre debe contener un dominio, una página y una fecha.');
}
const parsed = new Date(date);
if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
throw new Error('La fecha del nombre no es válida.');
}
return parts.join('-');
}
export function validateName(name: string): string {
const match = /^([^-]+)-([^-]+)-(\d{4}-\d{2}-\d{2})$/.exec(name);
if (!match) throw new Error('El nombre de exportación no es válido.');
return safeName(match.slice(1));
}
+99
View File
@@ -0,0 +1,99 @@
import type { Cell, Row } from 'write-excel-file/browser';
import { validateName } from './safe-name';
export const MAX_ROWS = 5000;
export type Sheet = {
name: string;
columns: { header: string; key: string; type?: 'string' | 'number' | 'date' }[];
rows: Record<string, unknown>[];
};
function cell(value: unknown, type?: Sheet['columns'][number]['type']): Cell {
if (value == null || value === '') return null;
if (type === 'date' || (!type && value instanceof Date)) {
const date = value instanceof Date ? value : new Date(String(value));
return Number.isFinite(date.getTime()) ? { value: date, format: 'yyyy-mm-dd' } : null;
}
if (type === 'number') {
const number = typeof value === 'string' && value.trim() ? Number(value) : value;
return typeof number === 'number' && Number.isFinite(number) ? number : null;
}
if (!type && typeof value === 'number') return Number.isFinite(value) ? value : null;
if (!type && typeof value === 'boolean') return value;
return String(value);
}
function columnName(count: number): string {
let name = '';
while (count > 0) {
count--;
name = String.fromCharCode(65 + (count % 26)) + name;
count = Math.floor(count / 26);
}
return name;
}
function width(value: Cell): number {
if (value == null) return 0;
if (typeof value === 'object' && 'value' in value)
return value.value instanceof Date ? 10 : String(value.value).length;
return String(value).length;
}
export async function downloadXlsx(
name: string,
sheets: Sheet[],
parameters: Record<string, string>,
): Promise<void> {
const filename = `${validateName(name)}.xlsx`;
const { default: writeExcelFile } = await import('write-excel-file/browser');
const parameterSheet: Sheet = {
name: 'Parámetros',
columns: [
{ header: 'Parámetro', key: 'parameter' },
{ header: 'Valor', key: 'value' },
],
rows: Object.entries(parameters).map(([parameter, value]) => ({ parameter, value })),
};
const filterRanges: (string | undefined)[] = [];
const workbook = [...sheets, parameterSheet].map(({ name, columns, rows }, index) => {
const data: Row[] = [columns.map(({ header }) => ({ value: header, fontWeight: 'bold' }))];
for (const row of rows.slice(0, MAX_ROWS)) {
data.push(columns.map(({ key, type }) => cell(row[key], type)));
}
if (index < sheets.length && columns.length) {
filterRanges[index] = `A1:${columnName(columns.length)}${data.length}`;
}
if (rows.length >= MAX_ROWS) {
data.push([`Límite de exportación: ${MAX_ROWS} filas.`]);
}
return {
sheet: name,
data,
stickyRowsCount: 1,
columns: columns.map((_, column) => ({
width: Math.min(80, Math.max(10, ...data.map((row) => width(row[column]))) + 2),
})),
};
});
await writeExcelFile(workbook, {
features: [
{
files: {
transform: {
'xl/worksheets/sheet{id}.xml': {
transform: (xml, _, { sheetIndex }) => {
const ref = filterRanges[sheetIndex];
return ref
? xml.replace('</sheetData>', `</sheetData><autoFilter ref="${ref}"/>`)
: xml;
},
},
},
},
},
],
}).toFile(filename);
}
+44
View File
@@ -0,0 +1,44 @@
import { HttpErrorResponse } from '@angular/common/http';
import { exportErrorText, verifiedImport } from './bundles';
const hash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
describe('bundle import', () => {
beforeEach(() => {
const bytes = Uint8Array.from(hash.match(/../g)!, (hex) => parseInt(hex, 16));
vi.stubGlobal('crypto', { subtle: { digest: vi.fn().mockResolvedValue(bytes.buffer) } });
});
afterEach(() => vi.unstubAllGlobals());
it('refuses to upload a file with a different SHA-256', async () => {
const file = new Blob([new Uint8Array([97, 98, 99])]);
const upload = vi.fn();
await expect(verifiedImport(file, '0'.repeat(64), upload)).rejects.toThrow('no coincide');
expect(upload).not.toHaveBeenCalled();
});
it('submits the verified digest', async () => {
const file = new Blob([new Uint8Array([97, 98, 99])]);
const upload = vi.fn().mockResolvedValue({ run_id: 'run-1' });
await expect(verifiedImport(file, hash.toUpperCase(), upload)).resolves.toEqual({
run_id: 'run-1',
});
expect(upload).toHaveBeenCalledExactlyOnceWith(hash);
});
});
describe('bundle export', () => {
const failed = (body: string) =>
new HttpErrorResponse({ status: 409, error: new Blob([body], { type: 'application/json' }) });
it("shows the API's detail from a blob error body", async () => {
await expect(
exportErrorText(failed('{"detail":"nothing to export: no version selected"}')),
).resolves.toBe('nothing to export: no version selected');
});
it('shows a body that is not JSON as it came', async () => {
await expect(exportErrorText(failed('Bad gateway'))).resolves.toBe('Bad gateway');
});
});
+135
View File
@@ -0,0 +1,135 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, model, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { Api } from '../api/api';
import { exportModels, type ExportModels$Params } from '../api/fn/models/export-models';
import { importModels } from '../api/fn/models/import-models';
import type { Domain } from '../api/models/domain';
import { errorText } from './run-monitor';
export async function verifiedImport<T>(
file: Blob,
expected: string,
upload: (sha256: string) => Promise<T>,
): Promise<T> {
const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());
const sha256 = Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('');
if (expected.trim().toLowerCase() !== sha256) {
throw new Error('El SHA-256 del archivo no coincide con el esperado.');
}
return upload(sha256);
}
export async function exportErrorText(error: unknown): Promise<string> {
if (!(error instanceof HttpErrorResponse && error.error instanceof Blob)) return errorText(error);
const text = await error.error.text();
try {
const detail = JSON.parse(text).detail;
return typeof detail === 'string' ? detail : text;
} catch {
return text;
}
}
export function download(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
@Component({
selector: 'app-governance-bundles',
imports: [FormsModule, MatButtonModule],
template: `
<section class="card">
<h3>Bundles</h3>
<form (ngSubmit)="export()">
<label
>Versiones
<select name="versions" [(ngModel)]="selection">
<option value="champion">En producción</option>
<option value="latest">Últimas</option>
<option value="all">Todas</option>
</select>
</label>
<button mat-stroked-button type="submit" [disabled]="exporting()">Exportar bundle</button>
</form>
@if (exportedHash()) {
<p>
SHA-256 <code>{{ exportedHash() }}</code>
</p>
}
<form (ngSubmit)="import(file)">
<label>Archivo ZIP <input #file type="file" accept=".zip" required /></label>
<label>SHA-256 esperado <input name="hash" [(ngModel)]="hash" required /></label>
<button mat-stroked-button type="submit" [disabled]="importing() || disabled()">
Importar bundle
</button>
</form>
@if (message()) {
<p role="alert">{{ message() }}</p>
}
</section>
`,
})
export class Bundles {
private readonly api = inject(Api);
readonly domain = input.required<Domain>();
readonly disabled = input(false);
readonly started = output<string>();
protected readonly selection = signal<NonNullable<ExportModels$Params['versions']>>('champion');
protected readonly exportedHash = signal('');
protected readonly hash = signal('');
protected readonly message = signal('');
protected readonly exporting = signal(false);
readonly importing = model(false);
protected async export(): Promise<void> {
this.exporting.set(true);
this.message.set('');
this.exportedHash.set('');
const domain = this.domain();
try {
const response = await this.api.invoke$Response(exportModels, {
domain,
versions: this.selection(),
});
const sha256 = response.headers.get('X-Bundle-Sha256') ?? '';
this.exportedHash.set(sha256);
download(response.body, `${domain}-models-${sha256.slice(0, 12)}.zip`);
} catch (error) {
this.message.set(await exportErrorText(error));
} finally {
this.exporting.set(false);
}
}
protected async import(input: HTMLInputElement): Promise<void> {
const file = input.files?.[0];
if (!file || this.importing() || this.disabled()) return;
this.importing.set(true);
this.message.set('');
const domain = this.domain();
try {
const { run_id } = await verifiedImport(file, this.hash(), (sha256) =>
this.api.invoke(importModels, {
domain,
sha256,
body: { file: file as unknown as string },
}),
);
input.value = '';
if (domain === this.domain()) this.started.emit(run_id);
} catch (error) {
this.message.set(errorText(error));
} finally {
this.importing.set(false);
}
}
}
+71
View File
@@ -0,0 +1,71 @@
import { TestBed } from '@angular/core/testing';
import { Api } from '../api/api';
import { executionHealth } from '../api/fn/execution/execution-health';
import { executionOptions } from '../api/fn/execution/execution-options';
import { Execution } from './execution';
describe('execution', () => {
afterEach(() => {
TestBed.resetTestingModule();
vi.useRealTimers();
});
it('publishes the deployment default and the selected scheduler, and refreshes only when visible', async () => {
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
const doc = document;
const hidden = vi.spyOn(doc, 'hidden', 'get').mockReturnValue(false);
const invoke = vi.fn(async (operation: unknown) =>
operation === executionOptions
? { default_mode: 'local', schedulers: ['tcp://scheduler:8786'] }
: { mode: 'remote', reachable: true, workers: 2 },
);
try {
TestBed.overrideProvider(Api, { useValue: { invoke } });
const fixture = TestBed.createComponent(Execution);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.componentInstance.execution()).toEqual({ mode: 'local', scheduler: null });
expect(invoke).toHaveBeenCalledWith(executionHealth, { mode: 'local', scheduler: null });
const mode: HTMLSelectElement = fixture.nativeElement.querySelector('select');
mode.value = 'remote';
mode.dispatchEvent(new Event('change'));
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.componentInstance.execution()).toEqual({
mode: 'remote',
scheduler: 'tcp://scheduler:8786',
});
const scheduler: HTMLInputElement = fixture.nativeElement.querySelector('input');
scheduler.value = 'other:8786';
scheduler.dispatchEvent(new Event('change'));
fixture.detectChanges();
await fixture.whenStable();
expect(fixture.componentInstance.execution()).toEqual({
mode: 'remote',
scheduler: 'other:8786',
});
invoke.mockClear();
await vi.advanceTimersByTimeAsync(30_000);
fixture.detectChanges();
await fixture.whenStable();
expect(invoke).toHaveBeenCalledExactlyOnceWith(executionHealth, {
mode: 'remote',
scheduler: 'other:8786',
});
invoke.mockClear();
hidden.mockReturnValue(true);
await vi.advanceTimersByTimeAsync(30_000);
fixture.detectChanges();
expect(invoke).not.toHaveBeenCalled();
} finally {
hidden.mockRestore();
}
});
});
+117
View File
@@ -0,0 +1,117 @@
import { DOCUMENT } from '@angular/common';
import { Component, computed, effect, inject, model, resource, signal } from '@angular/core';
import { Api } from '../api/api';
import { executionHealth } from '../api/fn/execution/execution-health';
import { executionOptions } from '../api/fn/execution/execution-options';
import type { Execution as Choice } from '../api/models/execution';
import type { Health } from '../api/models/health';
@Component({
selector: 'app-execution',
template: `
<section class="card">
<h2>Ejecución</h2>
@if (options.hasValue()) {
<label
>Modo
<select #mode [value]="choice().mode ?? ''" (change)="select($any(mode.value))">
<option value="sync">Sync</option>
<option value="local">Local</option>
<option value="remote">Remoto</option>
</select>
</label>
@if (choice().mode === 'remote') {
<label
>Scheduler
<input
#scheduler
list="execution-schedulers"
[value]="choice().scheduler ?? ''"
(change)="address.set(scheduler.value)"
/>
</label>
<datalist id="execution-schedulers">
@for (host of options.value().schedulers; track host) {
<option [value]="host"></option>
}
</datalist>
}
}
@if (health.hasValue()) {
@let h = health.value();
<p role="status">
{{ h.reachable ? 'Disponible' : 'No disponible' }}
@if (h.workers != null) {
· Trabajadores: {{ h.workers }}
}
@if (h.memory_per_worker != null) {
· Memoria por trabajador: {{ h.memory_per_worker }}
}
@if (h.error) {
· {{ h.error }}
}
</p>
@if (h.dashboard_url && h.dashboard_ok !== false) {
<a [href]="h.dashboard_url" target="_blank" rel="noopener">Panel de Dask</a>
}
} @else if (health.error() || options.error()) {
<p role="alert">No se pudo consultar la ejecución.</p>
}
</section>
`,
})
export class Execution {
private readonly api = inject(Api);
private readonly document = inject(DOCUMENT);
private readonly visible = signal(!this.document.hidden);
readonly execution = model<Choice | undefined>(undefined);
protected readonly options = resource({ loader: () => this.api.invoke(executionOptions) });
protected readonly mode = signal<Choice['mode']>(undefined);
protected readonly address = signal<string | undefined>(undefined);
protected readonly choice = computed<Choice>(() => {
const options = this.options.hasValue() ? this.options.value() : undefined;
const mode = this.mode() ?? options?.default_mode;
return {
mode,
scheduler:
mode === 'remote' ? (this.address() ?? options?.schedulers[0] ?? '').trim() || null : null,
};
});
protected readonly health = resource({
params: () => (this.visible() && this.choice().mode ? this.choice() : undefined),
loader: async ({ params }) => {
const health: Health & { memory_per_worker?: string | number } = await this.api.invoke(
executionHealth,
params,
);
return health;
},
});
constructor() {
effect(() => {
const choice = this.choice();
this.execution.set(choice.mode ? choice : undefined);
});
effect((cleanup) => {
const refresh = () => {
if (!this.document.hidden) this.health.reload();
};
const visibilityChanged = () => this.visible.set(!this.document.hidden);
const timer = setInterval(refresh, 30_000);
this.document.addEventListener('visibilitychange', visibilityChanged);
cleanup(() => {
clearInterval(timer);
this.document.removeEventListener('visibilitychange', visibilityChanged);
});
});
}
protected select(mode: NonNullable<Choice['mode']>): void {
this.mode.set(mode);
if (mode === 'remote' && this.address() === undefined && this.options.hasValue()) {
this.address.set(this.options.value().schedulers[0] ?? '');
}
}
}
+82 -4
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures, scenarioFigure } from './figures';
import { interpretabilityFigures, scenarioFigure, studyPoints } 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); // band, curve, model points
expect(found.figure.data.length).toBe(3);
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
});
@@ -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); // the cohort's curves only
expect(found.length).toBe(1);
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect(drawn.figure.data.length).toBe(5);
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
});
@@ -71,6 +71,84 @@ 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([]);
});
+127 -17
View File
@@ -1,16 +1,16 @@
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[];
y: (number | null)[];
low?: (number | null)[];
high?: (number | null)[];
}
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
lines.push({
@@ -35,10 +35,64 @@ function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Pl
return lines;
}
/** 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 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;
}
export function interpretabilityFigures(
report: Record<string, any>,
ageCurve: AgeCurveOptions = {},
): { title: string; figure: Figure }[] {
switch (report['kind']) {
case 'curves': {
@@ -71,7 +125,6 @@ export function interpretabilityFigures(
},
},
},
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
];
}
case 'subgroups':
@@ -140,26 +193,75 @@ export function interpretabilityFigures(
},
];
}
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
case 'scenarios':
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': {
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
const curves = report['curves'];
const feature = ageCurve.feature ?? (curves.value ? 'value' : Object.keys(curves)[0]);
const value = curves[feature];
if (!value) return [];
const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`;
const label = feature === 'value' ? '' : ` · ${feature}`;
const overlay: Partial<Plotly.Data>[] = ageCurve.points?.length
? [
{
x: ageCurve.points.map((point) => point.age),
y: ageCurve.points.map((point) => point.value),
name: 'Estudios analizados',
type: 'scatter',
mode: 'markers',
},
]
: [];
if (value.kind === 'count_rate') {
const rate = Number.isFinite(value.rate) ? value.rate : null;
return [
{
title: `Tasa de referencia: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`,
title: `Tasa de referencia: ${rate?.toFixed(3) ?? '—'} por minuto (${value.reference} estudios)${label}`,
figure: {
data: [
{
x: value.ages,
y: [value.rate, value.rate],
y: [rate, rate],
name: 'Tasa',
type: 'scatter',
mode: 'lines',
},
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' } },
@@ -169,18 +271,28 @@ export function interpretabilityFigures(
},
];
}
const c = value.curve;
const centiles = ageCurve.centiles;
if (!centiles && ageCurve.waitForCentiles) return [];
const c = centiles
? {
age_months: centiles.map((point) => point.age_months),
median: centiles.map((point) => point.median),
p5: centiles.map((point) => point.p5),
p95: centiles.map((point) => point.p95),
}
: value.curve;
return [
{
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
figure: {
data: [
...banded(
'p5–p95',
'Mediana',
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
PALETTE[4],
),
].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)),
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
yaxis: { title: { text: 'Valor' } },
@@ -250,8 +362,6 @@ export function interpretabilityFigures(
}
}
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band (also a patient's, in her record). */
export function scenarioFigure(
title: string,
e: any,
+272 -180
View File
@@ -1,213 +1,305 @@
<section class="page">
<h1>{{ labels[domain()] ?? domain() }}</h1>
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
<h1>Gobernanza de modelos</h1>
<nav class="domains" aria-label="Dominios">
@for (d of domains.hasValue() ? domains.value() : []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<form class="card actions" (submit)="$event.preventDefault()">
<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>
<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>
<button
mat-stroked-button
type="button"
[disabled]="running()"
(click)="confirming.set('score')"
[disabled]="starting() || running()"
(click)="start('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
<button
mat-stroked-button
type="button"
[disabled]="starting() || running() || !execution()"
(click)="start('analyze')"
>
Analizar EEG
</button>
}
<button
mat-stroked-button
type="button"
[disabled]="editing() || !models.hasValue()"
(click)="prepareCandidates(bulkDialog)"
>
Promover candidatas
</button>
</div>
@if (training(); as name) {
<app-governance-training
[domain]="domainKey()"
[name]="name"
[execution]="execution()"
[(busy)]="starting"
[disabled]="running() || !execution()"
(started)="follow($event.id, 'Entrenamiento', $event.autoPromote)"
/>
}
@if (run(); as r) {
<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>
}
<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>
}
</form>
@if (message()) {
<p class="muted" role="status">{{ message() }}</p>
}
@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) {
@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>
<tr>
<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>
<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>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chosen.set({ name: m.name, version: v.version })"
(click)="chooseReport({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</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
</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
</button>
} @else {
Agregada
}
</td>
<td>
@if (!champion(v)) {
<button mat-stroked-button type="button" (click)="promote(m.name, v.version)">
Promover
<button
mat-stroked-button
type="button"
(click)="
showVersion('lineage', { name: m.name, version: v.version }, lineageDialog)
"
>
Linaje
</button>
}
</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>
</td>
</tr>
}
</tbody>
</table>
}
</div>
</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()" />
}
<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>
+18 -29
View File
@@ -1,8 +1,18 @@
:host {
display: block;
}
.subtitle {
margin: 4px 0 var(--space-4);
h1 {
text-align: center;
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
}
.actions {
display: flex;
@@ -20,7 +30,6 @@
white-space: nowrap;
}
.badge {
white-space: nowrap;
margin-left: var(--space-2);
padding: 2px 8px;
border-radius: 999px;
@@ -36,32 +45,12 @@ td a {
padding: 48px 0;
text-align: center;
}
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
.message {
white-space: pre-line;
}
.reports a {
margin-right: 0;
dialog {
max-width: min(90vw, 64rem);
}
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;
dialog form {
margin-top: var(--space-3);
}
+16
View File
@@ -0,0 +1,16 @@
import { checkActions } from './gobernanza';
describe('version checks', () => {
it('enables promotion only when the API says the version is promotable', () => {
expect(checkActions({ status: 'candidate', promotable: false, checks: [] }).promote).toBe(
false,
);
expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).promote).toBe(true);
expect(checkActions({ status: 'retired', promotable: false, checks: [] }).promote).toBe(false);
});
it('disables retirement for the champion', () => {
expect(checkActions({ status: 'champion', promotable: true, checks: [] }).retire).toBe(false);
expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).retire).toBe(true);
});
});
+333 -137
View File
@@ -1,31 +1,35 @@
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 { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
import { analyze } from '../api/fn/models/analyze';
import { models } from '../api/fn/models/models';
import { promote } from '../api/fn/models/promote';
import { readReport$Json } from '../api/fn/models/read-report-json';
import { score } from '../api/fn/models/score';
import { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status';
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 { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import type { Domain } from '../api/models/domain';
import type { Version } from '../api/models/version';
import type { Execution as Choice } from '../api/models/execution';
import type { Run } from '../api/models/run';
import { DOMAINS } from '../app';
import { Plot } from '../plot';
import { interpretabilityFigures } from './figures';
import { Loading } from '../loading';
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';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
@@ -33,34 +37,63 @@ const REPORTS: Record<string, string> = {
clinical_validation: 'Validación clínica',
};
/** 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. */
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' };
}
@Component({
selector: 'app-gobernanza',
imports: [
Loading,
DatePipe,
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
RouterLink,
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;
private readonly refreshed = signal(0);
protected readonly errorText = errorText;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
protected readonly refreshed = signal(0);
protected refresh(): void {
this.refreshed.update((value) => value + 1);
}
protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
loader: async ({ params: { domain } }) => {
const found = await this.api.invoke(models, { domain });
return Promise.all(
@@ -72,136 +105,299 @@ export class Gobernanza {
);
},
});
protected readonly chosen = signal<{ name: string; version: number } | undefined>(undefined);
protected readonly training = signal('');
protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>(
undefined,
);
protected readonly starting = signal(false);
protected readonly running = signal(false);
protected readonly editing = signal(false);
protected readonly message = signal('');
protected readonly chosen = signal<VersionKey | undefined>(undefined);
protected readonly checksFor = signal<VersionKey | undefined>(undefined);
protected readonly lineageFor = signal<VersionKey | undefined>(undefined);
protected readonly checks = resource({
params: () => {
const key = this.checksFor();
return key ? { ...key, domain: this.domainKey(), at: this.refreshed() } : undefined;
},
loader: async ({ params: { at, ...params } }) => this.getChecks(params.domain, params),
});
protected readonly checkActions = checkActions;
protected readonly lineage = resource({
params: () => {
const key = this.lineageFor();
return key ? { ...key, domain: this.domainKey() } : undefined;
},
loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage,
});
protected readonly candidates = signal<VersionKey[]>([]);
protected readonly report = resource({
params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain },
params: () => {
const key = this.chosen();
return key ? { ...key, domain: this.domainKey() } : undefined;
},
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(() => {
const found = this.report.value();
return found ? interpretabilityFigures(found as Record<string, unknown>) : [];
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',
});
});
/** 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('');
protected champion(v: Version): boolean {
return v.aliases.includes('champion');
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 reportUrl(name: string, version: number, report: string): string {
return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`;
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 async upload(name: string, version: number, event: Event): Promise<void> {
const file = (event.target as HTMLInputElement).files?.[0];
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
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 async promote(name: string, version: number): Promise<void> {
const domain = this.domainKey();
try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.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];
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));
}
}
protected showVersion(
kind: 'checks' | 'lineage',
key: VersionKey,
dialog: HTMLDialogElement,
): void {
(kind === 'checks' ? this.checksFor : this.lineageFor).set(key);
dialog.showModal();
}
protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise<void> {
const domain = this.domainKey();
this.editing.set(true);
this.message.set('');
try {
if (action === 'promote') await this.api.invoke(promote, { domain, ...key });
else await this.api.invoke(retire, { domain, ...key });
this.message.set(
missing
? `No se promovió: faltan informes (${missing
.split(', ')
.map((r) => this.reportNames[r] ?? r)
.join(', ')}).`
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
`${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`,
);
this.refresh();
} 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));
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);
}
this.refreshed.update((n) => n + 1);
}
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
protected async 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 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');
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();
}
}
+101
View File
@@ -0,0 +1,101 @@
import { HttpErrorResponse } from '@angular/common/http';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Api } from '../api/api';
import { cancelRun } from '../api/fn/runs/cancel-run';
import { runStatus } from '../api/fn/runs/run-status';
import type { Progress } from '../api/models/progress';
import type { Run } from '../api/models/run';
import { eta, RunMonitor } from './run-monitor';
const progress: Progress = {
done: 4,
total: 10,
mode: 'local',
phase: 'training',
elapsed_s: 20,
eta_s: null,
scheduler: null,
updated_at: '2026-11-30T12:00:00Z',
};
function run(state: Run['state']): Run {
return {
id: 'run-1',
domain: 'tea',
job: 'train',
status: state,
state,
info: [],
warnings: [],
steps: [],
error: null,
progress,
started: null,
ended: null,
};
}
async function render(fixture: ComponentFixture<RunMonitor>): Promise<void> {
fixture.detectChanges();
await Promise.resolve();
fixture.detectChanges();
}
describe('run monitor', () => {
afterEach(() => {
TestBed.resetTestingModule();
vi.useRealTimers();
});
for (const state of ['succeeded', 'failed', 'cancelled'] as const) {
it('stops polling after ' + state, async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
const invoke = vi
.fn()
.mockResolvedValueOnce(run('running'))
.mockResolvedValueOnce(run(state));
TestBed.configureTestingModule({ providers: [{ provide: Api, useValue: { invoke } }] });
const fixture = TestBed.createComponent(RunMonitor);
fixture.componentRef.setInput('runId', 'run-1');
const finished = vi.fn();
fixture.componentInstance.finished.subscribe(finished);
await render(fixture);
expect(invoke).toHaveBeenCalledExactlyOnceWith(runStatus, { run_id: 'run-1' });
await vi.advanceTimersByTimeAsync(1999);
expect(invoke).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(finished).toHaveBeenCalledExactlyOnceWith(run(state));
await vi.advanceTimersByTimeAsync(6000);
expect(invoke).toHaveBeenCalledTimes(2);
});
}
it('estimates seconds remaining from observed throughput', () => {
expect(eta(progress)).toBe(30);
expect(eta({ ...progress, done: 0 })).toBeNull();
expect(eta({ ...progress, done: 10 })).toBe(0);
});
it('requests cancellation and displays the conflict detail', async () => {
const invoke = vi.fn(async (endpoint: unknown) => {
if (endpoint === cancelRun) {
throw new HttpErrorResponse({
status: 409,
error: { detail: 'the run is still starting; try again' },
});
}
return run('running');
});
TestBed.configureTestingModule({ providers: [{ provide: Api, useValue: { invoke } }] });
const fixture = TestBed.createComponent(RunMonitor);
fixture.componentRef.setInput('runId', 'run-1');
await render(fixture);
const cancel: HTMLButtonElement = fixture.nativeElement.querySelector('button');
cancel.click();
await render(fixture);
expect(invoke).toHaveBeenCalledWith(cancelRun, { run_id: 'run-1' });
expect(fixture.nativeElement.textContent).toContain('the run is still starting; try again');
});
});
+164
View File
@@ -0,0 +1,164 @@
import { DecimalPipe, KeyValuePipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, effect, inject, input, output, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { Api } from '../api/api';
import { cancelRun } from '../api/fn/runs/cancel-run';
import { runStatus } from '../api/fn/runs/run-status';
import type { Progress } from '../api/models/progress';
import type { Run } from '../api/models/run';
export function errorText(error: unknown): string {
if (error instanceof HttpErrorResponse) {
const detail = error.error?.detail ?? error.error;
return typeof detail === 'string' ? detail : detail ? JSON.stringify(detail) : error.message;
}
return error instanceof Error ? error.message : String(error);
}
export function eta(progress: Progress): number | null {
return progress.done > 0 && progress.total > 0
? (Math.max(0, progress.total - progress.done) * progress.elapsed_s) / progress.done
: null;
}
@Component({
selector: 'app-run-monitor',
imports: [DecimalPipe, KeyValuePipe, MatButtonModule],
template: `
<section aria-label="Monitor de ejecución">
@if (run(); as r) {
<p role="status">{{ r.status }}</p>
@for (step of r.steps; track step.key) {
<div>{{ step.key }} · {{ step.status }}</div>
}
@if (r.progress; as p) {
<div>
{{ p.phase }} · {{ p.done }} / {{ p.total }}
@if (p.total > 0) {
({{ (100 * p.done) / p.total | number: '1.0-0' }} %)
<progress [value]="p.done" [max]="p.total"></progress>
}
@if (eta(p) !== null) {
· ETA {{ eta(p) | number: '1.0-0' }} s
}
</div>
@for (worker of p.workers ?? []; track worker.name) {
<div>
{{ worker.name }} · CPU {{ worker.cpu_pct | number: '1.0-1' }} % · RAM
{{ worker.memory_bytes / 1048576 | number: '1.0-1' }} MiB
@if (worker.memory_limit != null) {
/ {{ worker.memory_limit / 1048576 | number: '1.0-1' }} MiB
}
· Tareas activas: {{ worker.executing }}
</div>
}
@for (task of p.tasks | keyvalue; track task.key) {
<div>{{ task.key }}: {{ task.value }}</div>
}
}
@if (r.info.length) {
<h4>Información</h4>
<ul>
@for (line of r.info; track $index) {
<li>{{ line }}</li>
}
</ul>
}
@if (r.warnings.length) {
<h4>Advertencias</h4>
<ul>
@for (line of r.warnings; track $index) {
<li>{{ line }}</li>
}
</ul>
}
@if (r.error) {
<p role="alert">{{ r.error }}</p>
}
@if (!terminal.has(r.state)) {
<button
mat-stroked-button
type="button"
[disabled]="cancelling() || r.state === 'cancelling'"
(click)="cancel()"
>
Cancelar
</button>
}
} @else {
<p role="status">Consultando ejecución…</p>
}
@if (pollError()) {
<p role="alert">{{ pollError() }}</p>
}
@if (cancelError()) {
<p role="alert">{{ cancelError() }}</p>
}
</section>
`,
})
export class RunMonitor {
private readonly api = inject(Api);
readonly runId = input.required<string>();
readonly finished = output<Run>();
protected readonly run = signal<Run | undefined>(undefined);
protected readonly pollError = signal('');
protected readonly cancelError = signal('');
protected readonly cancelling = signal(false);
protected readonly terminal = new Set<Run['state']>(['succeeded', 'failed', 'cancelled']);
protected readonly eta = eta;
constructor() {
effect((cleanup) => {
const run_id = this.runId();
this.run.set(undefined);
this.pollError.set('');
this.cancelError.set('');
this.cancelling.set(false);
let active = true;
let timer: ReturnType<typeof setTimeout>;
const poll = async () => {
try {
const run = await this.api.invoke(runStatus, { run_id });
if (!active) return;
this.run.set(run);
this.pollError.set('');
if (this.terminal.has(run.state)) {
this.finished.emit(run);
return;
}
} catch (error) {
if (!active) return;
this.pollError.set(errorText(error));
}
timer = setTimeout(poll, 2000);
};
void poll();
cleanup(() => {
active = false;
clearTimeout(timer);
});
});
}
protected async cancel(): Promise<void> {
const run_id = this.runId();
this.cancelling.set(true);
this.cancelError.set('');
try {
const { state, status } = await this.api.invoke(cancelRun, { run_id });
if (this.runId() === run_id) {
this.run.update((run) =>
run && !this.terminal.has(run.state) && !this.terminal.has(state)
? { ...run, state, status }
: run,
);
}
} catch (error) {
if (this.runId() === run_id) this.cancelError.set(errorText(error));
} finally {
if (this.runId() === run_id) this.cancelling.set(false);
}
}
}
+119
View File
@@ -0,0 +1,119 @@
import { describe, expect, it } from 'vitest';
import type { PreviewResult } from '../../api/models/preview-result';
import { previewPdfContent, previewPdfName } from './preview-pdf';
const score = { z: 2.1, p5: 1, median: 2, p95: 3, outside: 1 };
const result: PreviewResult = {
eeg: {
valid: true,
level: 'complete',
recorded_on: '2026-01-10',
age_months: 24,
clean_fraction: 0.9,
bad_channels: 0,
channels: 19,
duration_min: 20,
line_noise_db: 3,
sleep: true,
error: null,
checks: [
{ code: 'duration', value: 20, unit: 'min', low: 10, high: null, abnormal: false },
{ code: 'flat', electrode: 'O1', text: 'plano', abnormal: true },
],
metrics: [
{
code: 'posterior_rhythm',
value: 6.5,
model: 'tea.eeg-posterior-rhythm/1',
score,
electrodes: { O1: { value: 6.4, score: null } },
zones: { occipital: { value: 6.6, score } },
},
],
},
ados2: {
module: 'module_1',
evaluation_date: '2026-01-12',
items: { pointing: 2, gestures: null, intonation: null, ignoring: 1 },
titles: { pointing: 'A-7 Señalar', gestures: 'A-8 Gestos' },
css: 7,
classification: 'autism',
read: ['module', 'pointing'],
},
warnings: ['sin curva en producción para spindles_n2'],
};
describe('previewPdfContent', () => {
it('prints the verdict, checks, scored metrics, ADOS-2 items by title and warnings', () => {
expect(previewPdfContent(result)).toEqual([
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
'complete · Válido',
{ text: 'Comprobaciones', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
{
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
body: [
['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'],
['duration', '—', '20 min', '10 / —', 'No'],
['flat', 'O1', 'plano', '— / —', 'Sí'],
],
},
},
{ text: 'Métricas', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
{
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
body: [
['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'],
['posterior_rhythm', '6.5', '2.1', '1 / 2 / 3', '1'],
['posterior_rhythm · O1', '6.4', '—', '— / — / —', '—'],
['posterior_rhythm · occipital', '6.6', '2.1', '1 / 2 / 3', '1'],
],
},
},
{ text: 'ADOS-2', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
'autism · CSS 7',
{
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', 'auto'],
body: [
['Ítem', 'Puntuación'],
['A-7 Señalar', '2'],
['A-8 Gestos', '—'],
['ignoring', '1'],
],
},
},
{ text: 'Advertencias', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
{ ul: ['sin curva en producción para spindles_n2'] },
]);
});
it('marks an invalid study with its error and no ADOS-2 or warnings', () => {
const content = previewPdfContent({
eeg: { ...result.eeg, valid: false, error: 'sin canales', checks: [], metrics: [] },
ados2: null,
warnings: [],
});
expect(content).toEqual([
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
'complete · No válido',
'sin canales',
{ text: 'Comprobaciones', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
'—',
{ text: 'Métricas', bold: true, fontSize: 14, margin: [0, 12, 0, 5] },
'—',
]);
});
it('names the file by domain, page and day only', () => {
expect(previewPdfName(new Date('2026-11-30T12:00:00Z'))).toBe('tea-gobernanza-2026-11-30');
});
});
+104
View File
@@ -0,0 +1,104 @@
import { downloadPdf, type PdfContent } from '../../export/pdf';
import { safeName } from '../../export/safe-name';
import type { PreviewResult } from '../../api/models/preview-result';
import type { Score } from '../../api/models/score';
function shown(value: unknown): string {
return value == null || value === '' ? '—' : String(value);
}
function yesNo(value: unknown): string {
return value === true ? 'Sí' : value === false ? 'No' : '—';
}
function verdict(valid: boolean | null): string {
return valid === true ? 'Válido' : valid === false ? 'No válido' : '—';
}
function scoreCells(score: Score | null): string[] {
return [
shown(score?.z),
`${shown(score?.p5)} / ${shown(score?.median)} / ${shown(score?.p95)}`,
shown(score?.outside),
];
}
function table(headers: string[], rows: string[][]): PdfContent {
if (!rows.length) return '—';
return {
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', ...headers.slice(1).map(() => 'auto' as const)],
body: [headers, ...rows],
},
};
}
function heading(text: string): PdfContent {
return { text, bold: true, fontSize: 14, margin: [0, 12, 0, 5] };
}
export function previewPdfName(day = new Date()): string {
return safeName(['tea', 'gobernanza', day.toISOString().slice(0, 10)]);
}
export function previewPdfContent(result: PreviewResult): PdfContent[] {
const { eeg, ados2, warnings } = result;
const content: PdfContent[] = [
{ text: 'Vista previa del estudio EEG', fontSize: 18, bold: true },
`${eeg.level} · ${verdict(eeg.valid)}`,
];
if (eeg.error) content.push(eeg.error);
content.push(
heading('Comprobaciones'),
table(
['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'],
eeg.checks.map((check) => [
shown(check['code']),
shown(check['electrode']),
`${shown(check['value'] ?? check['text'])}${check['unit'] ? ' ' + check['unit'] : ''}`,
`${shown(check['low'])} / ${shown(check['high'])}`,
yesNo(check['abnormal']),
]),
),
);
content.push(
heading('Métricas'),
table(
['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'],
eeg.metrics.flatMap((metric) => [
[metric.code, shown(metric.value), ...scoreCells(metric.score)],
...[...Object.entries(metric.electrodes), ...Object.entries(metric.zones)].map(
([site, value]) => [
`${metric.code} · ${site}`,
shown(value.value),
...scoreCells(value.score),
],
),
]),
),
);
if (ados2) {
content.push(
heading('ADOS-2'),
`${shown(ados2.classification)} · CSS ${shown(ados2.css)}`,
table(
['Ítem', 'Puntuación'],
Object.entries(ados2.items)
.filter(([field, value]) => field in ados2.titles || value != null)
.map(([field, value]) => [ados2.titles[field] ?? field, shown(value)]),
),
);
}
if (warnings.length) content.push(heading('Advertencias'), { ul: [...warnings] });
return content;
}
export function downloadPreviewPdf(result: PreviewResult): Promise<void> {
return downloadPdf(previewPdfName(), previewPdfContent(result));
}
+203
View File
@@ -0,0 +1,203 @@
import { KeyValuePipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { Api } from '../../api/api';
import { previewStatus } from '../../api/fn/preview/preview-status';
import { startPreview } from '../../api/fn/preview/start-preview';
import type { PreviewResult } from '../../api/models/preview-result';
import type { Run } from '../../api/models/run';
import { RunMonitor, errorText } from '../run-monitor';
import { downloadPreviewPdf } from './preview-pdf';
@Component({
selector: 'app-eeg-preview',
imports: [FormsModule, KeyValuePipe, MatButtonModule, RunMonitor],
template: `
<section>
<h3>Vista previa</h3>
<form (ngSubmit)="start(edf.files?.[0], ados.files?.[0], birth.value)">
<label>EDF <input #edf type="file" accept=".edf" required /></label>
<label>ADOS-2 (PDF) <input #ados type="file" accept=".pdf" /></label>
<label>Fecha de nacimiento <input #birth type="date" /></label>
<button mat-stroked-button type="submit" [disabled]="busy()">Vista previa</button>
</form>
@if (error()) {
<p role="alert">{{ error() }}</p>
}
@if (runId(); as id) {
<app-run-monitor [runId]="id" (finished)="finish($event, dialog)" />
}
<dialog #dialog aria-label="Vista previa del estudio">
@if (result(); as r) {
<h3>Resultado de la vista previa</h3>
<p>
{{ r.eeg.level }} ·
{{ r.eeg.valid === true ? 'Válido' : r.eeg.valid === false ? 'No válido' : '—' }}
</p>
@if (r.eeg.error) {
<p role="alert">{{ r.eeg.error }}</p>
}
<h4>Comprobaciones</h4>
<table class="plain">
<thead>
<tr>
<th>Comprobación</th>
<th>Electrodo</th>
<th>Resultado</th>
<th>Rango</th>
<th>Anormal</th>
</tr>
</thead>
<tbody>
@for (check of r.eeg.checks; track $index) {
<tr>
<td>{{ check['code'] }}</td>
<td>{{ check['electrode'] ?? '—' }}</td>
<td>{{ check['value'] ?? check['text'] ?? '—' }} {{ check['unit'] }}</td>
<td>{{ check['low'] ?? '—' }} / {{ check['high'] ?? '—' }}</td>
<td>
{{
check['abnormal'] === true ? 'Sí' : check['abnormal'] === false ? 'No' : '—'
}}
</td>
</tr>
}
</tbody>
</table>
<h4>Métricas</h4>
<table class="plain">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>z</th>
<th>p5 / mediana / p95</th>
<th>Fuera de rango</th>
</tr>
</thead>
<tbody>
@for (metric of r.eeg.metrics; track metric.code) {
<tr>
<th>{{ metric.code }}</th>
<td>{{ metric.value ?? '—' }}</td>
<td>{{ metric.score?.z ?? '—' }}</td>
<td>
{{ metric.score?.p5 ?? '—' }} / {{ metric.score?.median ?? '—' }} /
{{ metric.score?.p95 ?? '—' }}
</td>
<td>{{ metric.score?.outside ?? '—' }}</td>
</tr>
@for (site of metric.electrodes | keyvalue; track site.key) {
<tr>
<td>{{ site.key }}</td>
<td>{{ site.value.value ?? '—' }}</td>
<td>{{ site.value.score?.z ?? '—' }}</td>
<td>
{{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} /
{{ site.value.score?.p95 ?? '—' }}
</td>
<td>{{ site.value.score?.outside ?? '—' }}</td>
</tr>
}
@for (site of metric.zones | keyvalue; track site.key) {
<tr>
<td>{{ site.key }}</td>
<td>{{ site.value.value ?? '—' }}</td>
<td>{{ site.value.score?.z ?? '—' }}</td>
<td>
{{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} /
{{ site.value.score?.p95 ?? '—' }}
</td>
<td>{{ site.value.score?.outside ?? '—' }}</td>
</tr>
}
}
</tbody>
</table>
@if (r.ados2; as ados2) {
<h4>ADOS-2</h4>
<p>{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}</p>
<dl>
@for (item of ados2.items | keyvalue: unsorted; track item.key) {
<dt>{{ ados2.titles[item.key] ?? item.key }}</dt>
<dd>{{ item.value ?? '—' }}</dd>
}
</dl>
}
@if (r.warnings.length) {
<h4>Advertencias</h4>
<ul>
@for (warning of r.warnings; track $index) {
<li>{{ warning }}</li>
}
</ul>
}
}
@if (pdfError()) {
<p role="alert">{{ pdfError() }}</p>
}
<form method="dialog">
@if (result(); as r) {
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="pdf(r)">
Guardar como PDF
</button>
}
<button mat-stroked-button>Cerrar</button>
</form>
</dialog>
</section>
`,
})
export class EegPreview {
private readonly api = inject(Api);
protected readonly busy = signal(false);
protected readonly error = signal('');
protected readonly runId = signal('');
protected readonly result = signal<PreviewResult | null>(null);
protected readonly unsorted = () => 0;
protected readonly exporting = signal(false);
protected readonly pdfError = signal('');
protected async pdf(result: PreviewResult): Promise<void> {
this.exporting.set(true);
this.pdfError.set('');
try {
await downloadPreviewPdf(result);
} catch (error) {
this.pdfError.set(errorText(error));
} finally {
this.exporting.set(false);
}
}
protected async start(edf?: File, ados2?: File, birth_date?: string): Promise<void> {
if (!edf) return;
this.busy.set(true);
this.error.set('');
this.result.set(null);
try {
const { run_id } = await this.api.invoke(startPreview, {
body: { edf, ados2, birth_date: birth_date || undefined },
});
this.runId.set(run_id);
} catch (error) {
this.error.set(errorText(error));
this.busy.set(false);
}
}
protected async finish(run: Run, dialog: HTMLDialogElement): Promise<void> {
try {
if (run.state !== 'succeeded') return;
const { result } = await this.api.invoke(previewStatus, { run_id: run.id });
this.result.set(result);
if (result) dialog.showModal();
else this.error.set('La vista previa no devolvió un resultado.');
} catch (error) {
this.error.set(errorText(error));
} finally {
this.busy.set(false);
}
}
}
+129
View File
@@ -0,0 +1,129 @@
<section class="card model">
<h2>Estudios EEG</h2>
<form (ngSubmit)="analyze()">
<label
>Alcance
<select name="scope" [(ngModel)]="mode">
<option value="pending">Pendientes</option>
<option value="first_n">Primeros N</option>
<option value="ids">Por ID</option>
</select>
</label>
@if (mode() === 'first_n') {
<label
>Número de estudios <input type="number" name="count" min="1" required [(ngModel)]="count"
/></label>
}
@if (mode() === 'ids') {
<label
>ID de estudios (uno por línea) <textarea name="ids" required [(ngModel)]="ids"></textarea>
</label>
}
<button mat-flat-button type="submit" [disabled]="busy() || !execution()">Analizar</button>
</form>
<form (ngSubmit)="upload(files)">
<label>Archivos EDF <input #files type="file" accept=".edf" multiple required /></label>
<button mat-stroked-button type="submit" [disabled]="busy()">Subir EDF</button>
</form>
@if (error()) {
<p role="alert">{{ error() }}</p>
}
@if (runId(); as id) {
<app-run-monitor [runId]="id" (finished)="finish()" />
}
<app-eeg-preview />
<h3>Resumen</h3>
@if (summary.hasValue()) {
<dl>
@for (count of summary.value() | keyvalue; track count.key) {
<dt>{{ labels[count.key] ?? count.key }}</dt>
<dd>{{ count.value }}</dd>
}
</dl>
} @else if (summary.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (history.hasValue()) {
@if (history.value().last; as last) {
<p>
Última ejecución TEA: {{ last.status }}
@if (last.ended != null) {
· {{ last.ended * 1000 | date: 'short' }}
}
</p>
}
<p>
{{
history.value().current
? 'Indicadores al día'
: 'Indicadores pendientes: corre el análisis TEA'
}}
</p>
} @else if (history.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (eegs.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (eegMetrics.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
<div class="model">
<table class="plain eegs">
<thead>
<tr>
<th>Fecha</th>
<th>Registro</th>
<th>Análisis</th>
</tr>
</thead>
<tbody>
@for (e of eegs.hasValue() ? eegs.value() : []; track e.id) {
<tr>
<td>
<button mat-button type="button" [disabled]="!e.analysed" (click)="eeg.set(e.id)">
{{ e.study_date }}
</button>
</td>
<td>{{ e.lab_record_id ?? '—' }}</td>
<td>
{{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }}
{{ e.level ? '(' + e.level + ')' : '' }}
</td>
</tr>
} @empty {
<tr>
<td colspan="3" class="muted">Sin EEG cargados.</td>
</tr>
}
</tbody>
</table>
@if (eegMetrics.hasValue() && eegMetrics.value(); as m) {
<h3>EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses</h3>
<table class="plain">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>z</th>
<th>Curva</th>
</tr>
</thead>
<tbody>
@for (x of m.metrics; track x.code) {
<tr>
<td>{{ metricNames[x.code] ?? x.code }}</td>
<td class="num">{{ x.value | number: '1.2-2' }}</td>
<td class="num">{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}</td>
<td>{{ x.model ?? 'sin curva en producción' }}</td>
</tr>
} @empty {
<tr>
<td colspan="4" class="muted">Sin métricas (EEG no válido).</td>
</tr>
}
</tbody>
</table>
}
</div>
</section>
+158
View File
@@ -0,0 +1,158 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, output, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { Api } from '../../api/api';
import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs';
import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary';
import { studies } from '../../api/fn/eeg/studies';
import { study } from '../../api/fn/eeg/study';
import { pipeline } from '../../api/fn/ingest/pipeline';
import { startRun } from '../../api/fn/ingest/start-run';
import { upload } from '../../api/fn/ingest/upload';
import { runHistory } from '../../api/fn/runs/run-history';
import type { Execution } from '../../api/models/execution';
import type { Scope } from '../../api/models/scope';
import { errorText, RunMonitor } from '../run-monitor';
import { EegPreview } from './preview';
@Component({
selector: 'app-eeg-studies',
imports: [
DatePipe,
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
RunMonitor,
EegPreview,
],
templateUrl: './studies.html',
})
export class EegStudies {
private readonly api = inject(Api);
readonly execution = input<Execution>();
readonly refresh = input(0);
readonly changed = output<void>();
protected readonly eegs = resource({
params: () => this.refresh(),
loader: () => this.api.invoke(studies),
});
protected readonly eeg = signal<string | undefined>(undefined);
protected readonly eegMetrics = resource({
params: () => {
const eeg_id = this.eeg();
return eeg_id ? { eeg_id, refresh: this.refresh() } : undefined;
},
loader: ({ params: { eeg_id } }) => this.api.invoke(study, { eeg_id }),
});
protected readonly summary = resource({
params: () => this.refresh(),
loader: () => this.api.invoke(eegStudiesSummary),
});
protected readonly history = resource({
params: () => this.refresh(),
loader: async () => {
const [last] = await this.api.invoke(runHistory, { job: 'tea_eeg', domain: 'tea', limit: 1 });
if (last?.state !== 'succeeded' || last.ended == null) return { last, current: false };
const ended = last.ended;
const limit = 200;
let before: string | undefined;
for (;;) {
const runs = await this.api.invoke(runHistory, {
job: 'analyze',
domain: 'tea',
limit,
before,
});
if (runs.some((run) => run.ended != null && run.ended > ended))
return { last, current: false };
if (runs.length < limit) return { last, current: true };
before = runs[runs.length - 1].id;
}
},
});
protected readonly labels: Record<string, string> = {
eegs: 'Estudios',
analysed: 'Analizados',
valid: 'Válidos',
not_valid: 'No válidos',
failed: 'Fallidos',
metrics: 'Métricas',
metrics_with_z: 'Métricas con z',
high: 'Altas',
low: 'Bajas',
};
protected readonly metricNames: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
protected readonly mode = signal<NonNullable<Scope['mode']>>('pending');
protected readonly count = signal<number | null>(null);
protected readonly ids = signal('');
protected readonly busy = signal(false);
protected readonly error = signal('');
protected readonly runId = signal('');
protected readonly errorText = errorText;
protected async analyze(): Promise<void> {
const execution = this.execution();
if (!execution) return;
const mode = this.mode();
const scope: Scope = { mode };
if (mode === 'first_n') {
const count = this.count();
if (count == null || !Number.isInteger(count) || count < 1) return;
scope.n = count;
}
if (mode === 'ids') {
scope.ids = this.ids().split(/\s+/).filter(Boolean);
if (!scope.ids.length) return;
}
await this.start(() => this.api.invoke(analyzeEegs, { body: { scope, execution } }));
}
protected async upload(input: HTMLInputElement): Promise<void> {
const files = Array.from(input.files ?? []);
if (!files.length) return;
if (files.some((file) => !file.name.toLowerCase().endsWith('.edf'))) {
this.error.set('Selecciona archivos EDF.');
return;
}
await this.start(async () => {
try {
await this.api.invoke(pipeline, { pipeline_id: 'tea' });
await this.api.invoke(upload, { body: { files: files as unknown as string[] } });
const run = await this.api.invoke(startRun, { pipeline_id: 'tea', body: {} });
input.value = '';
return run;
} catch (error) {
if (error instanceof HttpErrorResponse && error.status === 404) {
throw new Error('No hay un pipeline TEA configurado');
}
throw error;
}
});
}
protected finish(): void {
this.busy.set(false);
this.changed.emit();
}
private async start(submit: () => Promise<{ [key: string]: string }>): Promise<void> {
this.busy.set(true);
this.error.set('');
try {
const { run_id } = await submit();
this.runId.set(run_id);
} catch (error) {
this.error.set(errorText(error));
this.busy.set(false);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
import { trainingForm } from './training';
describe('training form', () => {
it('removes execution and resolves the TEA reference fields with their defaults', () => {
const { schema, model } = trainingForm({
name: 'all',
domain: 'tea',
defaults: { execution: { mode: 'local', scheduler: null }, reference: { line_hz: 50 } },
json_schema: {
type: 'object',
properties: {
execution: { type: 'object' },
as_of: { anyOf: [{ type: 'string', format: 'date' }, { type: 'null' }] },
reference: { anyOf: [{ $ref: '#/$defs/Reference' }, { type: 'null' }] },
},
$defs: {
Reference: {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string' },
line_hz: { type: 'integer', enum: [50, 60], default: 50 },
},
},
},
},
});
expect(schema.properties).not.toHaveProperty('execution');
expect(schema.properties?.['as_of']).toMatchObject({
type: ['string', 'null'],
format: 'date',
});
expect(schema.properties?.['reference']).toMatchObject({
type: ['object', 'null'],
properties: { name: { type: 'string' }, line_hz: { enum: [50, 60] } },
});
expect(model).toEqual({ reference: { line_hz: 50 } });
});
});
+243
View File
@@ -0,0 +1,243 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, model, output, resource, signal } from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { FormlyForm, provideFormlyCore } from '@ngx-formly/core';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material';
import type { JSONSchema7, JSONSchema7TypeName } from 'json-schema';
import { Api } from '../api/api';
import { train } from '../api/fn/models/train';
import { trainingConfig } from '../api/fn/models/training-config';
import { trainingInputs } from '../api/fn/models/training-inputs';
import { uploadTrainingInputs } from '../api/fn/models/upload-training-inputs';
import type { Domain } from '../api/models/domain';
import type { Execution } from '../api/models/execution';
import type { TrainingConfig } from '../api/models/training-config';
import { FORMLY_TYPES } from '../conectar/schema-form';
import { errorText } from './run-monitor';
type Schema = JSONSchema7 & { $defs?: Record<string, Schema> };
interface InputSets {
allowed: string[];
description: string;
sets: { name: string; edf_files: number; has_ages: boolean }[];
}
export function trainingForm(config: TrainingConfig) {
const raw = structuredClone(config.json_schema) as Schema;
const model = structuredClone(config.defaults);
delete model['execution'];
delete raw.properties?.['execution'];
raw.required = raw.required?.filter((key) => key !== 'execution');
const normalize = (schema: Schema): Schema => {
if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]);
if (schema.anyOf) {
const { anyOf, ...rest } = schema;
const selected = normalize(
anyOf.find((entry) => typeof entry === 'object' && entry.type !== 'null') as Schema,
);
return { ...selected, ...rest, type: [selected.type as JSONSchema7TypeName, 'null'] };
}
if (schema.properties) {
return {
...schema,
properties: Object.fromEntries(
Object.entries(schema.properties).map(([key, value]) => [
key,
normalize(value as Schema),
]),
),
};
}
return schema;
};
const schema = normalize(raw);
const reference = schema.properties?.['reference'] as Schema | undefined;
if (reference) reference.required = reference.required?.filter((key) => key !== 'name');
return { schema, model };
}
function allowedFile(file: File, allowed: string[]): boolean {
return allowed.some((pattern) => {
if (pattern === '*.edf') return file.name.toLowerCase().endsWith('.edf');
return file.name === pattern;
});
}
@Component({
selector: 'app-governance-training',
imports: [FormsModule, ReactiveFormsModule, FormlyForm, MatButtonModule],
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
template: `
<section class="card">
<h3>{{ name() === 'all' ? 'Entrenar modelos' : 'Reentrenar ' + name() }}</h3>
@if (config.hasValue()) {
@let form = config.value();
<form (ngSubmit)="start(form.model)">
<formly-form [form]="form.form" [fields]="form.fields" [model]="form.model" />
@if (domain() === 'tea') {
<label
><input type="checkbox" name="promote" [(ngModel)]="autoPromote" /> Promover al
terminar</label
>
}
<button
mat-flat-button
type="submit"
[disabled]="busy() || disabled() || form.form.invalid"
>
Entrenar
</button>
</form>
} @else if (config.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (inputs.hasValue() && inputs.value(); as sets) {
<h4>Archivos de entrenamiento</h4>
<p>{{ sets.description }}</p>
<ul>
@for (set of sets.sets; track set.name) {
<li>
{{ set.name }} · {{ set.edf_files }} EDF ·
{{ set.has_ages ? 'Con edades' : 'Sin edades' }}
</li>
}
</ul>
<form (ngSubmit)="upload(setName.value, files)">
<label
>Conjunto
<input #setName list="training-input-sets" required />
</label>
<datalist id="training-input-sets">
@for (set of sets.sets; track set.name) {
<option [value]="set.name"></option>
}
</datalist>
<label
>Archivos
<input #files type="file" multiple required [accept]="accept(sets.allowed)" />
</label>
<button mat-stroked-button type="submit" [disabled]="uploading()">Subir archivos</button>
</form>
} @else if (inputs.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (message()) {
<p role="status">{{ message() }}</p>
}
</section>
`,
})
export class Training {
private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema);
readonly domain = input.required<Domain>();
readonly name = input.required<string>();
readonly execution = input<Execution>();
readonly disabled = input(false);
readonly started = output<{ id: string; autoPromote: boolean }>();
protected readonly config = resource({
params: () => ({ domain: this.domain(), name: this.name() }),
loader: async ({ params }) => {
const { schema, model } = trainingForm(await this.api.invoke(trainingConfig, params));
const fields = [
this.jsonschema.toFieldConfig(schema, {
map: (field, source) => {
if (source.format === 'date') {
field.props = { ...field.props, type: 'date' };
}
if (field.key === 'line_hz') {
field.type = 'select';
field.props = {
...field.props,
options: [
{ value: 50, label: '50 Hz' },
{ value: 60, label: '60 Hz' },
],
};
}
return field;
},
}),
];
return { fields, model, form: new UntypedFormGroup({}) };
},
});
protected readonly inputs = resource({
params: () => ({ domain: this.domain(), name: this.name() }),
loader: async ({ params }) => {
try {
return (await this.api.invoke(trainingInputs, params)) as InputSets;
} catch (error) {
if (error instanceof HttpErrorResponse && error.status === 404) return undefined;
throw error;
}
},
});
readonly busy = model(false);
protected readonly uploading = signal(false);
protected readonly message = signal('');
protected readonly autoPromote = signal(false);
protected readonly errorText = errorText;
protected async start(model: TrainingConfig['defaults']): Promise<void> {
if (this.busy() || this.disabled()) return;
this.busy.set(true);
this.message.set('');
const domain = this.domain();
const name = this.name();
const autoPromote = domain === 'tea' && this.autoPromote();
const reference = model['reference'];
try {
const { run_id } = await this.api.invoke(train, {
domain,
body: {
as_of: model['as_of'] || undefined,
reference: reference?.name ? reference : undefined,
execution: this.execution(),
...(name === 'all' ? {} : { models: [name] }),
},
});
this.started.emit({ id: run_id, autoPromote });
} catch (error) {
this.message.set(errorText(error));
} finally {
this.busy.set(false);
}
}
protected accept(allowed: string[]): string {
return allowed
.map((pattern) =>
pattern.startsWith('*.') ? pattern.slice(1) : '.' + pattern.split('.').pop(),
)
.join(',');
}
protected async upload(set: string, input: HTMLInputElement): Promise<void> {
const files = Array.from(input.files ?? []);
const allowed = this.inputs.hasValue() ? (this.inputs.value()?.allowed ?? []) : [];
if (!files.length || files.some((file) => !allowedFile(file, allowed))) {
this.message.set('Archivos permitidos: ' + allowed.join(', '));
return;
}
this.uploading.set(true);
this.message.set('');
try {
await this.api.invoke(uploadTrainingInputs, {
domain: this.domain(),
name: this.name(),
set: set.trim(),
body: { files },
});
input.value = '';
this.inputs.reload();
} catch (error) {
this.message.set(errorText(error));
} finally {
this.uploading.set(false);
}
}
}

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