Compare commits

...

48 Commits

Author SHA1 Message Date
alberto 98eda5bc28 Gobernanza: Analizar EEG leads to Estudios EEG, which hosts the single-study evaluation; the timeline is only a dotted line; the probability curve and the age-norm bands are drawn from the model and the centiles 2026-12-01 18:35:42 -06:00
alberto f7eb170e15 One-step ticks only when the axis spans five or less, counted from zero 2026-12-01 17:29:05 -06:00
alberto b6e9acd3ba OpenAPI document with the training source titles 2026-12-01 17:26:09 -06:00
alberto 8ebf870f41 Plot axes are built fresh for every chart
The module-level axis defaults were shared by every chart, and Plotly writes its detected axis type, range and autorange back into the layout it is given, so one chart's category axis and range leaked into the others (count axes typed as categories, percent ranges ignored). Each layout now gets its own axis objects.
2026-12-01 17:23:53 -06:00
alberto ef407ce0a7 Every chart uses the shared short number format: axes, hover and bar/value text
Counts print as integers and other values with at most one decimal, in tick labels (valueAxis, percentAxis), hover templates and bar and pie text.
2026-12-01 17:20:28 -06:00
alberto 5cd601651c Count axes are linear with whole-number or one-decimal tick labels from one shared builder
The EEG quality chart's count axis was typed as a category axis, which put 0 on the right; every count and value axis now takes its type and tick format from valueAxis: linear, whole numbers for counts (one step when the range is narrow), one decimal otherwise, with Plotly choosing the number of ticks.
2026-12-01 17:15:35 -06:00
alberto 8ca3b053bd C1a: code only, no comments, no Markdown
Remove 125 JavaScript, TypeScript, and stylesheet comments and nine configuration comments. The submodule had zero tracked Markdown files. Remove the Markdown-only EditorConfig section.

Keep the generated client headers and tool directives. Delete other comments in place without regenerating the client or changing OpenAPI data.
2026-12-01 16:55:32 -06:00
alberto c2d4747d69 F1e: the baseline exports from the page 2026-12-01 15:56:31 -06:00
alberto 08c447006c F1e: complete-child case finds the child by search and reads hidden marks as attached 2026-12-01 15:28:54 -06:00
alberto a4bf48b60d F1e: complete-child case reads the semester with the EEGs; export refusal is expected 2026-12-01 15:09:10 -06:00
alberto 13146fdca4 F1e: page cases tolerate collapsed box plots and read the bundle guard's refusal 2026-12-01 14:53:29 -06:00
alberto 4118b050b8 F1: Sankey laid out by Plotly's own columns, with no hand-set x/y
Root cause of the crossing bands and overlap: with explicit node x/y Plotly keeps the nodes where they are set but orders the links leaving a node on its own, so a stopped band could leave the top of a node while its target sat at the bottom (bands crossed), zero-flow nodes stayed in the figure and tiny nodes landed on one another, and long one-line labels ran into the next column's labels. Now the stopped nodes are plain sinks that Plotly justifies to the right column, ordered neuropediátrica, psicológica, M-CHAT from top to bottom so bands never cross; nodes without flow are dropped; labels break in two lines; the padding keeps two-line labels apart. The card spans the whole row. Checked by screenshots of the live page across monthly and semester periods.
2026-12-01 14:36:30 -06:00
alberto 2404a3a66b F1: Sankey stopped nodes bottom to top M-CHAT, psicológica, neuropediátrica; full card width; layout test removed 2026-12-01 14:20:58 -06:00
alberto 58fdfd53d7 F1: Sankey stopped nodes in the rightmost column 2026-12-01 14:14:00 -06:00
alberto 6a6691bdd5 F1e: page case for the complete child; Gobernanza case without the removed sections 2026-12-01 14:05:40 -06:00
alberto 5bd7793cf7 Merge parity/F1h 2026-12-01 14:04:28 -06:00
alberto 7d2a861993 F1: record section test expects the dotted line with its markers 2026-12-01 14:04:28 -06:00
alberto 0fd5cc70ec F1: whole-number axis range typed as a pair; explicit ranges win 2026-12-01 13:51:14 -06:00
alberto 71777537e1 F1h: Gobernanza without Vista previa and Subir archivos, button spacing
Keep preview state in Modelos and reset the toggle on domain changes. Hide the form while collapsed so the current selections, run monitor and result dialog survive toggling. Keep the existing evaluation and PDF handlers.

Use one wrapping button-row class with space-3 gaps and block margins. Inside table cells use the existing cell padding between rows. Apply the same class to the indicators export and keep the existing domain navigation bottom margin.

Delete the training upload UI and hand-edit the client and OpenAPI. Preserve the generator format and update the Modelos component spec and Gobernanza page case to cover both toggle states.
2026-12-01 13:49:28 -06:00
alberto e14a85261c Merge parity/F1g 2026-12-01 13:45:25 -06:00
alberto b001594ac7 Merge parity/F1f 2026-12-01 13:45:25 -06:00
alberto 4929def121 F1g: whole-number axes, risk list link, dotted timeline, head map
Share the integer tick rule between Trazabilidad and TEA record figures.
Use the plotted extent, including stacked totals or interval bounds, to
target four divisions. Round spacing up to a 1/2/5 step with a minimum of
one, anchor ticks at zero, ignore nonfinite values, and include integer
bounds when a fractional extent contains no integer.

Point the existing patient link at the TEA risk route and remove the
details accordion and separate risk action. Exercise the link from the
risk list in the existing patient page case. Connect completed diamonds
in step order on the existing marker trace, using its color for the
dotted line and retaining the duration bars and annotations.

The scalp figure used the ear electrodes as markers outside the circle,
omitted the ears, and masked sample centers without clipping Plotly's
rendered contour cells at the scalp boundary. Its interpolation also
colored distant areas with no adjacent sample. Use the reference's 19
scalp positions, nose and ear paths, and reverse-wound mask painted in
the card's white surface color beneath the outline. Derive the mask and
the existing 41-point grid in headMapGeometry. Use the reference's 0.45
interpolation reach with inverse squared distance, taking a coincident
sample directly and preserving the existing zone inputs and z color
scale. Test mirror positions, scalp bounds, and plotted contour values.

Prettier, Ruff check, Ruff format check, and git diff --check passed.
Angular and Playwright execution are reserved for the test machines.
2026-12-01 13:42:54 -06:00
alberto 789145b93c F1f: TEA indicator chart formats (sex by age group, men blue, women magenta)
Reuse the existing male blue and female magenta, in that order. Read the published sex-by-result and age-by-sex cells and omit unknown sex. Keep the report age labels and sort by the starting month. Use zero for absent count cells and omit rates without denominators.

Keep M24 count heights and percentage labels. Stack the two outcomes within each sex using Plotly offset groups. Use the previous prevalence alpha of 0.25 for both transparent outcomes. For M31, use the published outcome counts and keep the sex focus control by outlining the selected bars while preserving both fill colors. Use the standard chart card height and identify changed figures by measure in the page checks.

Prettier, targeted figure type checking, and the 23 indicator logic tests passed. Full application type checking requires the unavailable pdfmake dependencies in this checkout. Angular and Playwright runs are reserved for the test machines.
2026-12-01 13:36:44 -06:00
alberto 5bf022b36f F1: training form driven by the API schema; Sankey stopped nodes at the left
The training form flattens the discriminated source union generically: the discriminator becomes a select labelled by each variant's title, a variant's fields hide unless it is chosen, and the payload keeps only the chosen variant's fields. No variant names, option labels or Hz labels live in the WebApp. The Sankey places the three 'Se quedó en' nodes in the leftmost column, every node at its own position.
2026-12-01 13:32:26 -06:00
alberto f57a42b22a F1: Gobernanza page case reads the Carpeta textbox by role 2026-12-01 13:06:00 -06:00
alberto 8d7464065d F1: openapi.json regenerated from the merged API, client regenerated, training form types
The checked-in document listed routes the API no longer has; the inputs route now types its response, so the training form reads allowed by index and the schema type drops the JSON schema's own $defs.
2026-12-01 12:19:18 -06:00
alberto ec60f61704 Merge parity/F1a 2026-12-01 11:52:00 -06:00
alberto 2d0c8565ae tea-indicators.spec: one teaSteps import 2026-12-01 11:52:00 -06:00
alberto 3d4032f5d6 Merge parity/F1c
# Conflicts:
#	src/app/indicadores/tea-indicators.spec.ts
2026-12-01 11:51:57 -06:00
alberto 728d89f62e Merge parity/F1b 2026-12-01 11:51:43 -06:00
alberto c4920ed7eb F1b: user fixes
Use the existing Plotly card and registered Sankey trace. Build transition totals from the remaining stages and omit zero-flow links. Build the prevalence donut from the report counts, with a grey slice for missing sex and controls to highlight each recorded sex. Use grouped bars for M23 and separate age and sex stacks for M24. Use the existing stacked history style for M31 and put the M30 figure behind one page flag. Cover the builders and the existing TEA page case.
2026-12-01 11:33:06 -06:00
alberto 344dafd9fc F1a: user fixes
Keep preview visibility in the domain page and reset it on domain changes. Build the source controls from the folder schema, keep folder edits while hidden, and send only the discriminator for site training. Place the existing upload controls in the next card and use the server-declared file types. Keep shared ingestion endpoints used by Conectar and remove the EEG-page upload flow.

Docker socket access was denied and the local environment lacks fastapi-users. Generate the changed OpenAPI route and schemas from the real models router with the production app settings, verify its other routes and schemas against the checked-in document, and run ng-openapi-gen directly from the cached dependencies.
2026-12-01 11:32:48 -06:00
alberto a2bf98e9da F1c: user fixes
Render the worklist stepper from the Patient stage and read M-CHAT, CSS
and alteration count from its FHIR extensions. Keep the compact stepper
private to Seguimiento and share the dated screening logic with the
patient record. Use the first dated event for each step, require prior
steps, and use the later date when an event predates its prerequisite.
Only a good-quality EEG completes that stage.

Use horizontal Plotly bars on the destination rows for elapsed spans,
diamonds for completed steps, and labels for pending steps. Keep the
screening order on the axis and show 30 days on either side when all
completed steps share one date. Reuse the registered bar and scatter
traces and the rebuild palette.

Use completed months at the applied cutoff and show the marked headline
association with the reference formatting. Resolve item labels from
the model's ADOS-2 observation and fall back to the item code. Move the
existing detail and risk actions into the patient-name cell to keep the
requested ten columns. Keep raw association numbers and separate CI
bounds in Excel and keep the screening dates in the follow-up export.

Update the two logic specs and the follow-up, risk and record page
assertions. All 34 targeted Vitest cases passed with Plotly rendering
stubbed. The local TypeScript check reached the existing PDF export
code and reported missing pdfmake typings. Angular and page runs are
reserved for the test machines.
2026-12-01 11:32:17 -06:00
alberto 7c98566579 T17: sweep of the WebApp after the feature-parity work
Removed the legacy indicator layout, unused chart helpers, styles and
exports, the card-actions component, fetch-all and explanatory comments;
one pager shared by the four worklists, shared filter-row styles, one
FHIR name and CURP reader, downloads through export/, the concept-map
editor on Material controls.
2026-12-01 06:48:57 -06:00
alberto 8237e9f483 T15/T16: one page case per page and tab: sign-in, Conectar, Revisión, CaCu, CaMa, TEA tabs, record, risk, Gobernanza
Shared helpers (admin sign-in fixture, watch, downloaded) live in e2e/support.ts.
Conectar checks the EDF reader among the node kinds; CaCu and CaMa show their
four tabs over a platform without their data; the training-inputs 404 of a
domain without training files is the one allowed response.
2026-12-01 05:06:43 -06:00
alberto 2ea5106d32 T8: the record page test goes back through the frame's Regresar link 2026-12-01 04:17:02 -06:00
alberto 32332b0fcf Merge parity/main into parity/T8-tea-lists 2026-12-01 03:55:35 -06:00
alberto fcb3634fa9 T8/T9: TEA Seguimiento and Análisis de riesgo as two components in rebuild's list style
tea-list is replaced by tab-seguimiento-tea and tab-riesgos-tea over one
tea-rows module (params, rows, workbook, export), with Material filters,
cards and pager. The risk list defaults to every child and keeps the
association pairs per row; the focused patient is fetched with the list's
own search. Specs and page cases follow.
2026-12-01 03:55:35 -06:00
alberto 9e50655d51 T13: the execution spec picks the mode through the Material select 2026-12-01 02:25:00 -06:00
alberto a1c079ce43 Merge parity/main into parity/T13-gobernanza 2026-12-01 02:16:45 -06:00
alberto 3a26c63931 T13: Gobernanza as one page with its sections in fixed places
Keep the route, title, subtitle, domain navigation and composition in
gobernanza.{ts,html,scss}. Ejecución keeps mode and health in execution.ts.
Add models.{ts,html,scss} to own the actions, run monitor, status, versions,
reports, figures, clinical validation, and checks and lineage dialogs.

Render training.ts after Modelos with the existing source, configuration,
promotion checkbox, input sets and upload. Keep ZIP export and import in
bundles.ts. Keep scope, study list, EDF upload and run progress in
tea/studies.{ts,html}, and render tea/preview.ts separately for TEA with
its EDF and ADOS-2 selection, results and PDF export.

Use a page grid for section spacing and the global card style. Keep
table, action and dialog styles local to Modelos. Use Material fields
for editable values and Material buttons to open native file pickers,
retaining input labels and showing the selected filenames. Keep the
native suggestion lists for scheduler and input set names.

Default the training target to all on domain changes. Both Modelos
training actions focus the Entrenamiento heading and use the same
Formly submit path. Use the existing shared start flag and version
refresh via the Modelos component. Reset the training promotion
checkbox on domain changes and the upload selection with its input
listing. Ignore training submissions that finish in a different domain.

Move gobernanza.spec.ts to models.spec.ts alongside checkActions.
Keep bundles, execution, training, run-monitor, figures and preview PDF
logic specs. Update e2e/pages.spec.ts for Material selections and
the Modelos monitor, and check section order and training focus.

Prettier 3.10.1 and git diff --cached --check passed. The main checkout
has no local Prettier installation, so use the available lockfile
version directly from the requested working directory. Angular builds,
unit tests and Playwright are deferred to the VM per the spec.
2026-12-01 02:15:51 -06:00
alberto 374d58f5a5 Merge parity/main into parity/T10-tea-record 2026-12-01 02:02:56 -06:00
alberto 6df008bf8a T10/T11: the TEA record and the risk page render inside rebuild's patient frame
Paciente renders the TEA record and, on the risk route, the risk page with
the same frame as CaCu and CaMa: back link, title with id, identity block
from the FHIR Patient (name, birth date, sex, one row per identifier
system), sections as one card component, Material controls for the
altered-zones toggle and the pair choice, export button in rebuild's style.
tea-patient.ts, tea-record.html, tea-risk.html and tea-section.html/scss are
deleted; the logic specs follow the new structure.
2026-12-01 02:02:56 -06:00
alberto 52ca5876d0 T7: Trazabilidad of the TEA page shows M30 (altered EEG share with its interval)
The TEA Resumen/Trazabilidad/Definiciones tabs already are rebuild's generic
tabs over tp's measures after T1; Casos por estatus (M28) and the EEG quality
(M29) are in place. M30 is the one figure the reference shows only in
Trazabilidad, as a line with its interval; M31 belongs to the out-of-scope
tea-estatus page.
2026-12-01 01:30:27 -06:00
alberto 48e6c9f390 T3: openapi.json and API client regenerated for the training source 2026-12-01 01:20:29 -06:00
alberto f0dd3ec52f Merge parity/main into parity/T3-training-source 2026-12-01 01:09:45 -06:00
alberto 61aeed35ff T3: training form edits the training source; kind and mains as selects 2026-12-01 00:53:30 -06:00
alberto d8cb6420a4 T2: page specs no longer point at the removed reference captures 2026-12-01 00:46:19 -06:00
142 changed files with 5167 additions and 5406 deletions
-5
View File
@@ -1,4 +1,3 @@
# Editor configuration, see https://editorconfig.org
root = true root = true
[*] [*]
@@ -11,7 +10,3 @@ trim_trailing_whitespace = true
[*.ts] [*.ts]
quote_type = single quote_type = single
ij_typescript_use_double_quotes = false ij_typescript_use_double_quotes = false
[*.md]
max_line_length = off
trim_trailing_whitespace = false
-9
View File
@@ -1,17 +1,12 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist /dist
/tmp /tmp
/out-tsc /out-tsc
/bazel-out /bazel-out
# Node
/node_modules /node_modules
npm-debug.log npm-debug.log
yarn-error.log yarn-error.log
# IDEs and editors
.idea/ .idea/
.project .project
.classpath .classpath
@@ -20,7 +15,6 @@ yarn-error.log
.settings/ .settings/
*.sublime-workspace *.sublime-workspace
# Visual Studio Code
.vscode/* .vscode/*
!.vscode/settings.json !.vscode/settings.json
!.vscode/tasks.json !.vscode/tasks.json
@@ -29,7 +23,6 @@ yarn-error.log
!.vscode/mcp.json !.vscode/mcp.json
.history/* .history/*
# Miscellaneous
/.angular/cache /.angular/cache
.sass-cache/ .sass-cache/
/connect.lock /connect.lock
@@ -39,10 +32,8 @@ testem.log
/typings /typings
__screenshots__/ __screenshots__/
# System files
.DS_Store .DS_Store
Thumbs.db Thumbs.db
# Playwright
/test-results/ /test-results/
/playwright-report/ /playwright-report/
+369 -49
View File
@@ -1,29 +1,5 @@
import { statSync } from 'node:fs'; import { expect } from '@playwright/test';
import { expect, Locator, Page, test } from '@playwright/test'; import { downloaded, test, watch } from './support';
function watch(page: Page): string[] {
const problems: string[] = [];
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
page.on('response', (r) => r.status() >= 400 && problems.push(`${r.status()} ${r.url()}`));
page.on('pageerror', (e) => problems.push(`page: ${e.message}`));
return problems;
}
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
});
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('tea indicators: every tab loads, and the follow-up list exports to Excel', async ({ test('tea indicators: every tab loads, and the follow-up list exports to Excel', async ({
page, page,
@@ -34,16 +10,48 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel',
); );
await page.goto('/indicadores/tea'); await page.goto('/indicadores/tea');
const measures = (await (await listed).json()).entry.length; const measures = (await (await listed).json()).entry.length;
expect(measures).toBe(11);
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await expect(page.locator('app-tab-indicadores [data-measure]').first()).toBeVisible(); const indicators = page.locator('app-tab-indicadores');
await expect(indicators.locator('[data-measure]')).toHaveCount(10);
await expect(indicators.locator('[data-figure="sankey"] .sankey')).toBeVisible();
await expect(indicators.locator('[data-measure="M31_PREVALENCIA"] .barlayer')).toBeVisible();
await expect(
indicators.locator('[data-measure="M24_CONFIRMACION_DIAGNOSTICO"] app-plot'),
).toHaveCount(1);
await expect(
indicators.locator('[data-measure="M23_PACIENTES_EVALUADOS"] mat-button-toggle-group'),
).toHaveCount(0);
await expect(
indicators.getByRole('heading', { name: 'Porcentaje de EEG normal y anormal' }),
).toHaveCount(0);
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.getByText('Progresión del proceso diagnóstico')).toBeVisible(); const history = page.locator('app-tab-trazabilidad');
await expect(history.locator('[data-measure]')).toHaveCount(11);
await expect(
history.getByRole('heading', { name: 'Prevalencia registrada de TEA' }),
).toBeVisible();
await expect(
history.getByRole('heading', { name: 'Porcentaje de EEG normal y anormal' }),
).toBeVisible();
await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible(); await expect(page.locator('app-tab-trazabilidad app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const rows = page.locator('app-tab-seguimiento table tbody tr'); const rows = page.locator('app-tab-seguimiento-tea table tbody tr');
await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/); await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/);
await expect(rows.first().locator('app-tea-stepper li')).toHaveCount(4);
await expect(page.locator('app-tab-seguimiento-tea').getByRole('columnheader')).toHaveText([
'Expediente',
'Nombre',
'Sexo',
'Edad (meses)',
'Etapa',
'Puntaje M-CHAT',
'CSS ADOS-2',
'Estatus de EEG',
'Alteraciones encontradas',
]);
const name = await downloaded( const name = await downloaded(
page, page,
page.getByRole('button', { name: 'Exportar a Excel' }), page.getByRole('button', { name: 'Exportar a Excel' }),
@@ -52,11 +60,177 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel',
expect(name).toMatch(/^tea-seguimiento-/); expect(name).toMatch(/^tea-seguimiento-/);
await page.getByRole('tab', { name: 'Análisis de riesgo' }).click(); await page.getByRole('tab', { name: 'Análisis de riesgo' }).click();
await expect(page.locator('app-tab-riesgos app-tea-list')).toBeVisible(); const risk = page.locator('app-tab-riesgos-tea');
await expect(page.getByText('Cargando pacientes…')).toHaveCount(0); await expect(
risk.getByRole('heading', { name: 'EEG de los pacientes del periodo' }),
).toBeVisible();
await expect(risk.locator('table.worklist tbody tr').first().locator('td').first()).toHaveText(
/^N-?\d{4}$/,
);
await expect(risk.locator('table.worklist > thead').getByRole('columnheader')).toHaveText([
'Expediente',
'Nombre',
'Sexo',
'Edad (meses)',
'Asociación principal',
'Razón de momios',
'IC 95 %',
'q',
'Probabilidad',
'Probabilidad de referencia',
]);
await risk.getByRole('combobox', { name: 'Modelo de asociación' }).click();
await page.getByRole('option', { name: 'Con resultados' }).click();
await expect(risk.locator('table.worklist tbody tr').first()).toBeVisible();
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(measures); const definitions = page.locator('app-tab-definiciones');
await expect(definitions.locator('details')).toHaveCount(measures);
await expect(
definitions.getByText('Porcentaje de EEG normal y anormal', { exact: true }),
).toBeVisible();
await definitions.getByText('Prevalencia registrada de TEA', { exact: true }).click();
await expect(definitions.getByText(/Every child loaded on the platform/)).toBeVisible();
expect(problems).toEqual([]);
});
test('tea complete child: every screen has data', async ({ page }) => {
const problems = watch(page);
const recordNumber = /^N-?0011$/;
const filled = /^\s*(?!—\s*$)\S/;
const mark = '.point, .slice path, .sankey-node, .box';
const tab = (name: string) => page.getByRole('tab', { name }).click();
const section = (title: string) =>
page.locator('app-tea-section').filter({
has: page.locator('mat-card-title').getByText(title, { exact: true }),
});
const find = async (host: string) => {
const search = page.locator(host).getByRole('searchbox', { name: 'Buscar paciente' });
await search.fill('N0011');
await search.press('Enter');
};
const childRow = (table: string) =>
page
.locator(table)
.getByRole('row')
.filter({
has: page.getByRole('cell', { name: recordNumber }),
});
await page.goto('/indicadores/tea');
const summary = page.locator('app-tab-indicadores');
await summary.getByText('Semestral', { exact: true }).click();
await summary.getByRole('combobox', { name: 'Periodo seleccionado' }).click();
await page.getByRole('option', { name: '2025-S2', exact: true }).click();
await summary.getByRole('button', { name: 'Aplicar' }).click();
await expect(summary.locator('.summary mark').first()).toHaveText(/\d/);
const summaryFigures = summary.locator('.figure-card, .box-card');
await expect(summaryFigures).toHaveCount(10);
for (const card of await summaryFigures.all()) {
await expect(card.locator(`app-plot :is(${mark})`).first()).toBeAttached();
}
await expect(summary.getByText('Sin datos publicados')).toHaveCount(0);
await tab('Trazabilidad');
const history = page.locator('app-tab-trazabilidad');
const panels = history.locator('[data-measure]');
await expect(panels).toHaveCount(11);
for (const panel of await panels.all()) {
await expect(panel.locator(`app-plot :is(${mark})`).first()).toBeAttached();
}
await expect(history.getByText('Sin datos para el periodo.')).toHaveCount(0);
await tab('Seguimiento');
await find('app-tab-seguimiento-tea');
const followUp = childRow('app-tab-seguimiento-tea table.worklist');
await expect(followUp.getByRole('cell')).toHaveCount(9);
await expect(followUp.locator('td:not(:nth-child(5))')).toHaveText(Array(8).fill(filled));
await expect(followUp.locator('app-tea-stepper li.completed')).toHaveCount(4);
await expect(followUp.getByRole('cell').last()).toHaveText(/^[1-9]\d*$/);
await tab('Análisis de riesgo');
const risk = page.locator('app-tab-riesgos-tea');
await find('app-tab-riesgos-tea');
await risk.getByRole('combobox', { name: 'Modelo de asociación' }).click();
await page.getByRole('option', { name: 'Con resultados' }).click();
const riskRow = childRow('app-tab-riesgos-tea table.worklist');
await expect(riskRow.getByRole('cell')).toHaveText(Array(10).fill(filled));
await tab('Datos y definiciones');
const definitions = page.locator('app-tab-definiciones');
await expect(definitions.locator('details')).toHaveCount(11);
await definitions.getByText('Prevalencia registrada de TEA', { exact: true }).click();
await expect(definitions.getByText(/Every child loaded on the platform/)).toBeVisible();
await tab('Seguimiento');
await followUp.getByRole('link').click();
await expect(page.getByText(recordNumber)).toBeVisible();
const gantt = section('Línea del tiempo');
await expect(gantt.locator('app-plot .barlayer .point').first()).toBeAttached();
const diamonds = gantt.locator('app-plot .scatterlayer path.point');
await expect(diamonds).toHaveCount(4);
for (const diamond of await diamonds.all()) {
await expect(diamond).toHaveAttribute('d', /^M[\d.]+,0L0,[\d.]+L-/);
}
await expect(section('ADOS-2').locator('tbody tr').first().locator('td').nth(2)).toHaveText(
/^[AB]-\d+$/,
);
await expect(section('Calidad del EEG').locator('tbody tr').first()).toBeVisible();
const alterations = section('Alteraciones');
await expect(
alterations.locator('h3:text-is("Norma por edad · p5–p95") + app-plot .point').first(),
).toBeAttached();
await expect(
alterations.locator('h3:text-is("Mapa de la cabeza") + app-plot .contourlayer path').first(),
).toBeAttached();
await expect(section('Relación con el ADOS-2').locator('tbody tr').first()).toBeVisible();
await page.getByRole('link', { name: 'Análisis de riesgo' }).click();
await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible();
await expect(section('Qué calcula').locator('p').first()).toHaveText(/ADOS-2/);
await expect(
section('Puntuaciones z por métrica y zona').locator('app-plot .point').first(),
).toBeAttached();
await expect(
section('Razones de momios por par').locator('app-plot .point').first(),
).toBeAttached();
await expect(
section('Probabilidad frente a la referencia').locator('tbody tr').first(),
).toBeVisible();
await expect(section('Probabilidad según z').locator('app-plot .point').first()).toBeAttached();
await expect(section('Limitaciones').locator('p').first()).toHaveText(/cohorte/);
await page.goto('/gobernanza/tea');
await expect(page.getByRole('region', { name: 'Ejecución' }).getByRole('status')).toContainText(
'Disponible',
);
const models = page.getByRole('region', { name: 'Modelos' });
const modelCards = models.locator('section.model');
await expect(modelCards).toHaveCount(8);
for (const model of await modelCards.all()) {
await expect(model.getByText('champion', { exact: true })).toBeVisible();
}
await expect(page.locator('app-governance-training formly-form')).toBeVisible();
await expect(page.getByText('Subir archivos', { exact: true })).toHaveCount(0);
const bundles = page.getByRole('region', { name: 'Bundles' });
await expect(bundles.getByRole('combobox', { name: 'Versiones' })).toHaveText('En producción');
await expect(bundles.getByRole('button', { name: 'Exportar bundle' })).toBeEnabled();
const studies = page.locator('app-eeg-studies');
const completeEeg = studies.getByRole('row').filter({ hasText: 'LAB-N-0011-1' });
await expect(completeEeg).toContainText(/\bVálido\b/);
await completeEeg.getByRole('button').click();
await expect(
studies
.locator('table.plain:not(.eegs) tbody tr td')
.filter({ hasText: /^tea\./ })
.first(),
).toBeVisible();
await studies.getByRole('button', { name: 'Evaluar un solo estudio' }).click();
const preview = page.locator('app-eeg-preview');
await expect(preview.getByLabel('EDF')).toBeAttached();
await expect(preview.getByLabel('ADOS-2 (PDF)')).toBeAttached();
await expect(preview.getByLabel('Fecha de nacimiento')).toBeVisible();
await expect(page.getByRole('heading', { name: 'Vista previa', level: 2 })).toHaveCount(0);
expect(problems).toEqual([]); expect(problems).toEqual([]);
}); });
@@ -64,22 +238,45 @@ test('tea patient: the record and the risk page load and export to PDF', async (
const problems = watch(page); const problems = watch(page);
await page.goto('/indicadores/tea'); await page.goto('/indicadores/tea');
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const first = page.locator('app-tab-seguimiento table tbody tr').first(); const first = page.locator('app-tab-seguimiento-tea table tbody tr').first();
await expect(first.locator('td').first()).toHaveText(/^N-?\d{4}$/); await expect(first.locator('td').first()).toHaveText(/^N-?\d{4}$/);
await first.getByRole('link', { name: 'Expediente' }).click(); await first.getByRole('link').click();
await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/); await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
await expect(page.locator('app-tea-section').first()).toBeVisible(); const timeline = page.locator('app-tea-section').first();
await expect(timeline.getByText('Línea del tiempo', { exact: true })).toBeVisible();
await expect(timeline.locator('app-plot .scatterlayer .point').first()).toBeVisible();
await expect(timeline.getByRole('table')).toHaveCount(0);
const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf'); const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf');
expect(record).toMatch(/^tea-seguimiento-/); expect(record).toMatch(/^tea-seguimiento-/);
await page.getByRole('link', { name: 'Riesgo' }).click(); await page.getByRole('link', { name: 'Regresar' }).click();
const focused = page.locator('app-tab-seguimiento-tea');
await expect(focused.getByRole('button', { name: 'Ver todos los pacientes' })).toBeVisible();
const focusedRows = focused.locator('table tbody tr');
await expect(focusedRows).toHaveCount(1);
await expect(focusedRows.first().locator('td')).toHaveCount(9);
await expect(focusedRows.first().locator('app-tea-stepper')).toBeVisible();
await focusedRows.first().getByRole('link').click();
await page.getByRole('link', { name: 'Análisis de riesgo' }).click();
await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible();
await expect(page.locator('app-tea-section').first()).toBeVisible(); await expect(page.locator('app-tea-section').first()).toBeVisible();
expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch( expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch(
/^tea-riesgos-/, /^tea-riesgos-/,
); );
await page.goto('/indicadores/tea');
await page.getByRole('tab', { name: 'Análisis de riesgo' }).click();
const riskList = page.locator('app-tab-riesgos-tea table.worklist');
const patientLink = riskList.getByRole('row').nth(1).getByRole('link');
await expect(patientLink).toHaveAttribute(
'href',
/\/indicadores\/tea\/pacientes\/[^/]+\/riesgo$/,
);
await patientLink.click();
await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+\/riesgo$/);
await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible();
expect(problems).toEqual([]); expect(problems).toEqual([]);
}); });
@@ -88,24 +285,48 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF',
}) => { }) => {
const problems = watch(page); const problems = watch(page);
await page.goto('/gobernanza/tea'); await page.goto('/gobernanza/tea');
await page.getByLabel('Modo').selectOption('sync'); await expect(page.locator('app-gobernanza').getByRole('heading', { level: 2 })).toHaveText([
'Ejecución',
'Modelos',
'Entrenamiento',
'Bundles',
'Estudios EEG',
]);
await expect(page.getByRole('heading', { name: 'Subir archivos', exact: true })).toHaveCount(0);
await expect(page.getByText('Archivos de entrenamiento', { exact: true })).toHaveCount(0);
await page.getByRole('combobox', { name: 'Modo' }).click();
await page.getByRole('option', { name: 'Sync' }).click();
await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).toBeVisible(); await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).toBeVisible();
await page.getByRole('button', { name: 'Entrenar modelos' }).click(); await page.getByRole('button', { name: 'Entrenar modelos' }).click();
await expect(page.getByRole('heading', { name: 'Entrenar modelos', level: 3 })).toBeVisible(); const training = page.getByRole('heading', { name: 'Entrenamiento', level: 2 });
await expect(training).toBeVisible();
await expect(training).toBeFocused();
await expect(page.locator('app-governance-training formly-form')).toBeVisible(); await expect(page.locator('app-governance-training formly-form')).toBeVisible();
const monitor = page.locator('app-gobernanza > section > section app-run-monitor'); const source = page.getByRole('combobox', { name: 'Origen' });
const folder = page.getByRole('textbox', { name: 'Carpeta', exact: true });
const line = page.getByRole('combobox', { name: 'Frecuencia de la red eléctrica (Hz)' });
await expect(source).toHaveText('Niños del sitio sin el diagnóstico');
await expect(folder).toBeHidden();
await expect(line).toBeHidden();
await source.click();
await page.getByRole('option', { name: 'Carpeta de EDF con edades' }).click();
await expect(folder).toBeVisible();
await expect(line).toBeVisible();
await source.click();
await page.getByRole('option', { name: 'Niños del sitio sin el diagnóstico' }).click();
await expect(folder).toBeHidden();
await expect(line).toBeHidden();
await expect(page.getByRole('button', { name: 'Calcular riesgos' })).toHaveCount(0);
await page.getByRole('button', { name: 'Analizar EEG' }).click(); await page.getByRole('button', { name: 'Analizar EEG' }).click();
await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Estudios EEG', level: 2 })).toBeFocused();
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 page.getByRole('button', { name: 'Promover candidatas' }).click();
await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible(); await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible();
const studies = page.locator('app-eeg-studies'); const studies = page.locator('app-eeg-studies');
await expect(studies.locator('input[type=file]')).toHaveCount(0);
await expect(studies.locator('table.eegs tbody tr').first()).toContainText(/Válido|No válido/); 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 studies.locator('table.eegs tbody button:enabled').first().click();
await expect(studies.getByRole('heading', { name: /^EEG .* meses$/ })).toBeVisible(); await expect(studies.getByRole('heading', { name: /^EEG .* meses$/ })).toBeVisible();
@@ -115,7 +336,27 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF',
{ timeout: 10 * 60_000 }, { timeout: 10 * 60_000 },
); );
const preview = page.locator('app-eeg-preview'); const toggle = studies.getByRole('button', { name: 'Evaluar un solo estudio' });
const preview = studies.locator('app-eeg-preview');
const edf = preview.getByRole('button', { name: 'EDF', exact: true });
const ados = preview.getByRole('button', { name: 'ADOS-2 (PDF)', exact: true });
const birth = preview.getByLabel('Fecha de nacimiento');
await expect(toggle).toHaveAttribute('aria-pressed', 'false');
await expect(edf).toBeHidden();
await expect(ados).toBeHidden();
await expect(birth).toBeHidden();
await toggle.click();
await expect(toggle).toHaveAttribute('aria-pressed', 'true');
await expect(page.getByRole('heading', { name: 'Vista previa', exact: true })).toHaveCount(0);
await expect(edf).toBeVisible();
await expect(ados).toBeVisible();
await expect(birth).toBeVisible();
await toggle.click();
await expect(toggle).toHaveAttribute('aria-pressed', 'false');
await expect(edf).toBeHidden();
await expect(ados).toBeHidden();
await expect(birth).toBeHidden();
await toggle.click();
await preview.getByLabel('EDF').setInputFiles(process.env['TEA_EDF']!); await preview.getByLabel('EDF').setInputFiles(process.env['TEA_EDF']!);
await preview.getByLabel('ADOS-2 (PDF)').setInputFiles(process.env['TEA_ADOS2']!); await preview.getByLabel('ADOS-2 (PDF)').setInputFiles(process.env['TEA_ADOS2']!);
await preview.getByLabel('Fecha de nacimiento').fill(process.env['TEA_BIRTH']!); await preview.getByLabel('Fecha de nacimiento').fill(process.env['TEA_BIRTH']!);
@@ -131,8 +372,87 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF',
await dialog.getByRole('button', { name: 'Cerrar' }).click(); await dialog.getByRole('button', { name: 'Cerrar' }).click();
const bundles = page.locator('app-governance-bundles'); const bundles = page.locator('app-governance-bundles');
await bundles.getByLabel('Versiones').selectOption('all'); await bundles.getByRole('combobox', { name: 'Versiones' }).click();
await bundles.getByRole('button', { name: 'Exportar bundle' }).click(); await page.getByRole('option', { name: 'Todas' }).click();
await expect(bundles.getByRole('alert')).toContainText('nothing to export'); const [bundle] = await Promise.all([
expect(problems.filter((p) => !p.includes('409'))).toEqual([]); page.waitForEvent('download'),
bundles.getByRole('button', { name: 'Exportar bundle' }).click(),
]);
expect(bundle.suggestedFilename()).toMatch(/^tea-models-[0-9a-f]{12}\.zip$/);
await expect(bundles.locator('code')).toHaveText(/^[0-9a-f]{64}$/);
expect(problems).toEqual([]);
});
test('conectar: the tea pipeline on the canvas, and a node form', async ({ page }) => {
const problems = watch(page);
await page.goto('/conectar');
const pipelines = page.locator('aside.pipelines a');
await expect(pipelines).toHaveCount(1);
await expect(pipelines.first()).toContainText('tea');
await pipelines.first().click();
const canvas = page.locator('.canvas');
await expect(page.getByRole('button', { name: 'Leer EDF' })).toBeVisible();
const extract = canvas.locator('.node-caption', { hasText: 'Extraer datos' });
await expect(extract).toBeVisible();
await extract.click();
const panel = page.locator('aside.panel');
await expect(panel.getByRole('heading', { name: 'Extraer datos · ados2_results' })).toBeVisible();
await expect(panel.locator('formly-form')).toBeVisible();
expect(problems).toEqual([]);
});
test('revision: the unrecognised-documents tab mirrors the pipeline', async ({ page }) => {
const problems = watch(page);
const answer = page.waitForResponse((r) => r.url().includes('/review/unrecognised'));
await page.goto('/revision');
await expect(page.getByRole('heading', { name: 'Revisión' })).toBeVisible();
const count = ((await (await answer).json()) as unknown[]).length;
const tab = page.getByRole('tab', { name: 'Documentos no reconocidos' });
await expect(tab).toHaveText(`Documentos no reconocidos (${count})`);
await tab.click();
if (count === 0) {
await expect(page.getByText('Sin documentos no reconocidos.')).toBeVisible();
} else {
await expect(page.locator('table.plain:not(.card) tbody tr')).toHaveCount(count);
}
expect(problems).toEqual([]);
});
test('cacu and cama indicators: the four tabs over domains without data', async ({ page }) => {
const problems = watch(page);
expect(await (await page.request.get('/api/domains')).json()).toEqual(['cacu', 'cama', 'tea']);
for (const [domain, title] of [
['cacu', 'Cáncer cervicouterino'],
['cama', 'Cáncer de mama'],
]) {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('heading', { name: title, level: 1 })).toBeVisible();
await expect(page.getByRole('tab')).toHaveText([
'Indicadores',
'Trazabilidad',
'Análisis de riesgos',
'Datos y definiciones',
]);
await expect(page.getByText('Sin datos en el periodo.').first()).toBeVisible();
}
expect(problems).toEqual([]);
});
test('cacu gobernanza: the shared sections only, none of the TEA ones', async ({ page }) => {
const problems = watch(page);
await page.goto('/gobernanza/cacu');
await expect(page.locator('app-gobernanza').getByRole('heading', { level: 2 })).toHaveText([
'Ejecución',
'Modelos',
'Entrenamiento',
'Bundles',
]);
await expect(page.locator('app-eeg-studies')).toHaveCount(0);
await expect(page.locator('app-eeg-preview')).toHaveCount(0);
const nav = page.getByRole('navigation', { name: 'Dominios' });
await expect(nav.getByRole('link', { name: 'Cáncer de mama' })).toBeVisible();
await expect(nav.getByRole('link', { name: 'Trastorno del espectro autista' })).toBeVisible();
expect(problems.filter((p) => !p.startsWith('console: Failed to load'))).toEqual([]);
}); });
+36
View File
@@ -0,0 +1,36 @@
import { expect, test } from '@playwright/test';
import { watch } from './support';
const besidesAuthProbes = (problems: string[]) =>
problems.filter(
(p) =>
!p.includes('/api/auth/') &&
!p.includes('/api/users/me') &&
!p.startsWith('console: Failed to load resource'),
);
test('sign-in: the guard asks first, and the form lands on the requested page', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/indicadores/tea');
await expect(page).toHaveURL(/\/login\?next=%2Findicadores%2Ftea$/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByLabel('Usuario', { exact: true }).fill('admin@isssteleon.mx');
await page.getByLabel('Contraseña', { exact: true }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar', exact: true }).click();
await expect(page).toHaveURL(/\/indicadores\/tea$/);
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
expect(besidesAuthProbes(problems)).toEqual([]);
});
test('sign-in: a wrong password shows the error and stays', async ({ page }) => {
const problems = watch(page);
await page.goto('/login');
await page.getByLabel('Usuario', { exact: true }).fill('admin@isssteleon.mx');
await page.getByLabel('Contraseña', { exact: true }).fill('solo-para-pruebas-pero-mal');
await page.getByRole('button', { name: 'Ingresar', exact: true }).click();
await expect(page.getByRole('alert')).toHaveText('Usuario o contraseña incorrectos.');
await expect(page).toHaveURL(/\/login$/);
expect(besidesAuthProbes(problems)).toEqual([]);
});
+36
View File
@@ -0,0 +1,36 @@
import { statSync } from 'node:fs';
import { expect, Locator, Page, test as base } from '@playwright/test';
export const test = base.extend<{ admin: void }>({
admin: [
async ({ page }, use) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
await use();
},
{ auto: true },
],
});
export function watch(page: Page): string[] {
const problems: string[] = [];
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
page.on('response', (r) => r.status() >= 400 && problems.push(`${r.status()} ${r.url()}`));
page.on('pageerror', (e) => problems.push(`page: ${e.message}`));
return problems;
}
export 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;
}
+67 -617
View File
@@ -255,24 +255,6 @@
"title": "Body_upload", "title": "Body_upload",
"type": "object" "type": "object"
}, },
"Body_upload_training_inputs": {
"properties": {
"files": {
"items": {
"format": "binary",
"type": "string"
},
"minItems": 1,
"title": "Files",
"type": "array"
}
},
"required": [
"files"
],
"title": "Body_upload_training_inputs",
"type": "object"
},
"Browsed": { "Browsed": {
"properties": { "properties": {
"entries": { "entries": {
@@ -1077,6 +1059,37 @@
"title": "FieldSpec", "title": "FieldSpec",
"type": "object" "type": "object"
}, },
"FolderTrainingSource": {
"additionalProperties": false,
"properties": {
"folder": {
"description": "Carpeta dentro de TEA_REFERENCE_ROOT",
"pattern": "^[A-Za-z0-9._-]{1,64}$",
"title": "Carpeta",
"type": "string"
},
"kind": {
"const": "folder",
"title": "Origen",
"type": "string"
},
"line_hz": {
"default": 50,
"enum": [
50,
60
],
"title": "Frecuencia de la red el\u00e9ctrica (Hz)",
"type": "integer"
}
},
"required": [
"kind",
"folder"
],
"title": "Carpeta de EDF con edades",
"type": "object"
},
"Group": { "Group": {
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
@@ -2348,31 +2361,6 @@
"title": "Read", "title": "Read",
"type": "object" "type": "object"
}, },
"Reference": {
"additionalProperties": false,
"properties": {
"line_hz": {
"default": 50,
"enum": [
50,
60
],
"title": "Frecuencia de la red el\u00e9ctrica (Hz)",
"type": "integer"
},
"name": {
"description": "Carpeta dentro de TEA_REFERENCE_ROOT con los EDF y edades.csv",
"pattern": "^[A-Za-z0-9._-]{1,64}$",
"title": "Cohorte de referencia",
"type": "string"
}
},
"required": [
"name"
],
"title": "Reference",
"type": "object"
},
"Rejection": { "Rejection": {
"properties": { "properties": {
"entity": { "entity": {
@@ -2865,6 +2853,21 @@
"title": "Site", "title": "Site",
"type": "object" "type": "object"
}, },
"SiteTrainingSource": {
"additionalProperties": false,
"properties": {
"kind": {
"const": "site",
"title": "Origen",
"type": "string"
}
},
"required": [
"kind"
],
"title": "Ni\u00f1os del sitio sin el diagn\u00f3stico",
"type": "object"
},
"Source": { "Source": {
"additionalProperties": false, "additionalProperties": false,
"description": "One table, file set or API resource, copied as it is (dlt). Merged on the source's\nown primary key or `primary_key`; replaced whole when it has none.", "description": "One table, file set or API resource, copied as it is (dlt). Merged on the source's\nown primary key or `primary_key`; replaced whole when it has none.",
@@ -2979,26 +2982,6 @@
"title": "Source", "title": "Source",
"type": "object" "type": "object"
}, },
"SourceRef": {
"properties": {
"args": {
"additionalProperties": true,
"default": {},
"title": "Args",
"type": "object"
},
"source": {
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
"title": "Source",
"type": "string"
}
},
"required": [
"source"
],
"title": "SourceRef",
"type": "object"
},
"SourceType": { "SourceType": {
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
@@ -3428,15 +3411,16 @@
"title": "Models", "title": "Models",
"type": "array" "type": "array"
}, },
"reference": { "source": {
"anyOf": [ "anyOf": [
{ {
"$ref": "#/components/schemas/Reference" "$ref": "#/components/schemas/TrainingSource"
}, },
{ {
"type": "null" "type": "null"
} }
] ],
"title": "Datos de entrenamiento"
} }
}, },
"title": "Training", "title": "Training",
@@ -3472,6 +3456,23 @@
"title": "TrainingConfig", "title": "TrainingConfig",
"type": "object" "type": "object"
}, },
"TrainingSource": {
"discriminator": {
"mapping": {
"folder": "#/components/schemas/FolderTrainingSource",
"site": "#/components/schemas/SiteTrainingSource"
},
"propertyName": "kind"
},
"oneOf": [
{
"$ref": "#/components/schemas/SiteTrainingSource"
},
{
"$ref": "#/components/schemas/FolderTrainingSource"
}
]
},
"Uploaded": { "Uploaded": {
"properties": { "properties": {
"bucket_url": { "bucket_url": {
@@ -3609,93 +3610,6 @@
"title": "UserRead", "title": "UserRead",
"type": "object" "type": "object"
}, },
"UserUpdate": {
"properties": {
"domains": {
"anyOf": [
{
"items": {
"$ref": "#/components/schemas/Domain"
},
"type": "array"
},
{
"type": "null"
}
],
"title": "Domains"
},
"email": {
"anyOf": [
{
"format": "email",
"type": "string"
},
{
"type": "null"
}
],
"title": "Email"
},
"is_active": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"title": "Is Active"
},
"is_superuser": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"title": "Is Superuser"
},
"is_verified": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "null"
}
],
"title": "Is Verified"
},
"name": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Name"
},
"password": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Password"
}
},
"title": "UserUpdate",
"type": "object"
},
"ValidationError": { "ValidationError": {
"properties": { "properties": {
"ctx": { "ctx": {
@@ -4162,33 +4076,6 @@
"summary": "Health" "summary": "Health"
} }
}, },
"/ingest/concept-maps": {
"get": {
"description": "Every ConceptMap a site saved: its id, latest version and when.",
"operationId": "concept_maps",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"items": {
"additionalProperties": true,
"type": "object"
},
"title": "Response Concept Maps",
"type": "array"
}
}
},
"description": "Successful Response"
}
},
"summary": "Concept Maps",
"tags": [
"ingest"
]
}
},
"/ingest/concept-maps/{map_id}": { "/ingest/concept-maps/{map_id}": {
"get": { "get": {
"description": "A site's codes in platform terms (FHIR R4B ConceptMap), latest version.", "description": "A site's codes in platform terms (FHIR R4B ConceptMap), latest version.",
@@ -4758,52 +4645,6 @@
] ]
} }
}, },
"/ingest/sources/resources": {
"post": {
"description": "What a source offers (a database's tables...): also tests that it can be reached.",
"operationId": "source_resources",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SourceRef"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"items": {
"type": "string"
},
"title": "Response Source Resources",
"type": "array"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Source Resources",
"tags": [
"ingest"
]
}
},
"/ingest/sources/test": { "/ingest/sources/test": {
"post": { "post": {
"description": "\"Probar conexi\u00f3n\": reaches the source with the answers given. A database lists its\ntables (until one is picked; then its first rows); files and records show their first\nrows. Never a server error: what went wrong comes back in plain words.", "description": "\"Probar conexi\u00f3n\": reaches the source with the answers given. A database lists its\ntables (until one is picked; then its first rows); files and records show their first\nrows. Never a server error: what went wrong comes back in plain words.",
@@ -5263,129 +5104,6 @@
] ]
} }
}, },
"/models/{domain}/{name}/inputs": {
"get": {
"operationId": "training_inputs",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "name",
"required": true,
"schema": {
"title": "Name",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": true,
"title": "Response Training Inputs",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Training Inputs",
"tags": [
"models"
]
}
},
"/models/{domain}/{name}/inputs/{set}/files": {
"post": {
"operationId": "upload_training_inputs",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "name",
"required": true,
"schema": {
"title": "Name",
"type": "string"
}
},
{
"in": "path",
"name": "set",
"required": true,
"schema": {
"title": "Set",
"type": "string"
}
}
],
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"$ref": "#/components/schemas/Body_upload_training_inputs"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": true,
"title": "Response Upload Training Inputs",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Upload Training Inputs",
"tags": [
"models"
]
}
},
"/models/{domain}/{name}/training-config": { "/models/{domain}/{name}/training-config": {
"get": { "get": {
"operationId": "training_config", "operationId": "training_config",
@@ -6766,80 +6484,6 @@
"tags": [ "tags": [
"users" "users"
] ]
},
"patch": {
"operationId": "users:patch_current_user",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserUpdate"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserRead"
}
}
},
"description": "Successful Response"
},
"400": {
"content": {
"application/json": {
"examples": {
"UPDATE_USER_EMAIL_ALREADY_EXISTS": {
"summary": "A user with this email already exists.",
"value": {
"detail": "UPDATE_USER_EMAIL_ALREADY_EXISTS"
}
},
"UPDATE_USER_INVALID_PASSWORD": {
"summary": "Password validation failed.",
"value": {
"detail": {
"code": "UPDATE_USER_INVALID_PASSWORD",
"reason": "Password should beat least 3 characters"
}
}
}
},
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Bad Request"
},
"401": {
"description": "Missing token or inactive user."
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"security": [
{
"APIKeyCookie": []
}
],
"summary": "Users:Patch Current User",
"tags": [
"users"
]
} }
}, },
"/users/register": { "/users/register": {
@@ -6915,200 +6559,6 @@
] ]
} }
}, },
"/users/{id}": {
"delete": {
"operationId": "users:delete_user",
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
}
],
"responses": {
"204": {
"description": "Successful Response"
},
"401": {
"description": "Missing token or inactive user."
},
"403": {
"description": "Not a superuser."
},
"404": {
"description": "The user does not exist."
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"security": [
{
"APIKeyCookie": []
}
],
"summary": "Users:Delete User",
"tags": [
"users"
]
},
"get": {
"operationId": "users:user",
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserRead"
}
}
},
"description": "Successful Response"
},
"401": {
"description": "Missing token or inactive user."
},
"403": {
"description": "Not a superuser."
},
"404": {
"description": "The user does not exist."
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"security": [
{
"APIKeyCookie": []
}
],
"summary": "Users:User",
"tags": [
"users"
]
},
"patch": {
"operationId": "users:patch_user",
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserUpdate"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserRead"
}
}
},
"description": "Successful Response"
},
"400": {
"content": {
"application/json": {
"examples": {
"UPDATE_USER_EMAIL_ALREADY_EXISTS": {
"summary": "A user with this email already exists.",
"value": {
"detail": "UPDATE_USER_EMAIL_ALREADY_EXISTS"
}
},
"UPDATE_USER_INVALID_PASSWORD": {
"summary": "Password validation failed.",
"value": {
"detail": {
"code": "UPDATE_USER_INVALID_PASSWORD",
"reason": "Password should beat least 3 characters"
}
}
}
},
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
},
"description": "Bad Request"
},
"401": {
"description": "Missing token or inactive user."
},
"403": {
"description": "Not a superuser."
},
"404": {
"description": "The user does not exist."
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"security": [
{
"APIKeyCookie": []
}
],
"summary": "Users:Patch User",
"tags": [
"users"
]
}
},
"/{domain}/fhir": { "/{domain}/fhir": {
"post": { "post": {
"description": "A standard hospital's Bundle: checked as FHIR, kept as sent in the sender's inbox,\nand placed by the sender's pipeline (a run starts; follow it at the Location).", "description": "A standard hospital's Bundle: checked as FHIR, kept as sent in the sender's inbox,\nand placed by the sender's pipeline (a run starts; follow it at the Location).",
-2
View File
@@ -2,10 +2,8 @@
"name": "webapp", "name": "webapp",
"version": "0.0.0", "version": "0.0.0",
"scripts": { "scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json", "start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build", "build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test", "test": "ng test",
"api": "ng-openapi-gen -c ng-openapi-gen.json" "api": "ng-openapi-gen -c ng-openapi-gen.json"
}, },
-4
View File
@@ -1,10 +1,6 @@
// This file was generated by running 'ng generate @angular/material:theme-color'.
// Proceed with caution if making changes to this file.
@use 'sass:map'; @use 'sass:map';
@use '@angular/material' as mat; @use '@angular/material' as mat;
// Note: Color palettes are generated from primary: #a8c243, tertiary: #5f9ea0
$_palettes: ( $_palettes: (
primary: ( primary: (
0: #000000, 0: #000000,
+4 -4
View File
@@ -1,7 +1,7 @@
import type { Observation, ObservationComponent } from 'fhir/r4'; import type { Observation, ObservationComponent } from 'fhir/r4';
import { code, ext } from './fhir'; import { code, ext } from './fhir';
export const ADOS2_ITEMS = [ const ADOS2_ITEMS = [
'vocalization_directed', 'vocalization_directed',
'pointing', 'pointing',
'gestures', 'gestures',
@@ -26,18 +26,18 @@ export const ADOS2_ITEMS = [
'repetitive_interests', 'repetitive_interests',
]; ];
export interface Ados2Item { interface Ados2Item {
code: string; code: string;
title: string; title: string;
score?: number; score?: number;
} }
export interface Ados2Subdomain { interface Ados2Subdomain {
subdomain: string; subdomain: string;
items: Ados2Item[]; items: Ados2Item[];
} }
export interface Ados2Domain { interface Ados2Domain {
domain: string; domain: string;
subdomains: Ados2Subdomain[]; subdomains: Ados2Subdomain[];
} }
-6
View File
@@ -3,9 +3,6 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
/**
* Provides the ApiConfiguration configuration object with a given root URL.
*/
export function provideApiConfiguration(rootUrl: string) { export function provideApiConfiguration(rootUrl: string) {
var config = new ApiConfiguration(); var config = new ApiConfiguration();
config.rootUrl = rootUrl; config.rootUrl = rootUrl;
@@ -15,9 +12,6 @@ export function provideApiConfiguration(rootUrl: string) {
}; };
} }
/**
* Global configuration
*/
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
-16
View File
@@ -11,9 +11,6 @@ import { StrictHttpResponse } from './strict-http-response';
export type ApiFnOptional<P, R> = (http: HttpClient, rootUrl: string, params?: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>; export type ApiFnOptional<P, R> = (http: HttpClient, rootUrl: string, params?: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
export type ApiFnRequired<P, R> = (http: HttpClient, rootUrl: string, params: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>; export type ApiFnRequired<P, R> = (http: HttpClient, rootUrl: string, params: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
/**
* Helper service to call API functions directly
*/
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class Api { export class Api {
constructor( constructor(
@@ -24,24 +21,14 @@ export class Api {
private _rootUrl?: string; private _rootUrl?: string;
/**
* Returns the root url for API operations. If not set directly here,
* will fallback to `ApiConfiguration.rootUrl`.
*/
get rootUrl(): string { get rootUrl(): string {
return this._rootUrl || this.config.rootUrl; return this._rootUrl || this.config.rootUrl;
} }
/**
* Sets the root URL for API operations
*/
set rootUrl(rootUrl: string) { set rootUrl(rootUrl: string) {
this._rootUrl = rootUrl; this._rootUrl = rootUrl;
} }
/**
* Executes an API call, returning the response body only
*/
invoke<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<R>; invoke<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<R>;
invoke<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<R>; invoke<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<R>;
async invoke<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<R> { async invoke<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<R> {
@@ -49,9 +36,6 @@ export class Api {
return (await resp).body; return (await resp).body;
} }
/**
* Executes an API call, returning the entire response
*/
invoke$Response<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>>; invoke$Response<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
invoke$Response<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<StrictHttpResponse<R>>; invoke$Response<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
invoke$Response<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>> { invoke$Response<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>> {
-9
View File
@@ -12,19 +12,10 @@ import { Domain } from '../../models/domain';
export interface EegSummary$Params { export interface EegSummary$Params {
domain: Domain; domain: Domain;
/**
* months: the domain's follow-up list over that window up to the cut-off
*/
'follow-up-window'?: (number | null); 'follow-up-window'?: (number | null);
/**
* explicit window start that overrides follow-up-window
*/
'follow-up-start'?: (string | null); 'follow-up-start'?: (string | null);
/**
* default: the last day with data
*/
'follow-up-cutoff'?: (string | null); 'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null); 'follow-up-status'?: (string | null);
} }
-3
View File
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface PostBundle$Params { export interface PostBundle$Params {
domain: Domain; domain: Domain;
/**
* the sender's pipeline (its fhir nodes read this inbox)
*/
sender: string; sender: string;
body: { body: {
[key: string]: any; [key: string]: any;
-3
View File
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface SearchCondition$Params { export interface SearchCondition$Params {
domain: Domain; domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null); subject?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface SearchDiagnosticReport$Params { export interface SearchDiagnosticReport$Params {
domain: Domain; domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null); subject?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
-3
View File
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface SearchEncounter$Params { export interface SearchEncounter$Params {
domain: Domain; domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null); subject?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
@@ -12,24 +12,12 @@ import { Domain } from '../../models/domain';
export interface SearchMeasureReport$Params { export interface SearchMeasureReport$Params {
domain: Domain; domain: Domain;
/**
* the Measure's id or canonical URL
*/
measure: string; measure: string;
/**
* semesters (2025-S1) or months (2025-03), comma-separated
*/
'reporting-period': string; 'reporting-period': string;
/**
* count only what was known by then
*/
'as-of'?: (string | null); 'as-of'?: (string | null);
/**
* durations count to this day
*/
'event-cutoff'?: (string | null); 'event-cutoff'?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface SearchObservation$Params { export interface SearchObservation$Params {
domain: Domain; domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null); subject?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
-27
View File
@@ -13,50 +13,23 @@ export interface SearchPatient$Params {
domain: Domain; domain: Domain;
'_id'?: (string | null); '_id'?: (string | null);
/**
* months: the domain's follow-up list over that window up to the cut-off
*/
'follow-up-window'?: (number | null); 'follow-up-window'?: (number | null);
/**
* explicit window start that overrides follow-up-window
*/
'follow-up-start'?: (string | null); 'follow-up-start'?: (string | null);
/**
* default: the last day with data
*/
'follow-up-cutoff'?: (string | null); 'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null); 'follow-up-status'?: (string | null);
/**
* each word starts a word of her name (case and accents ignored)
*/
name?: (string | null); name?: (string | null);
/**
* [system|]value: a CURP or record number (case ignored)
*/
identifier?: (string | null); identifier?: (string | null);
/**
* -recent or -risk-<outcome>
*/
'_sort'?: string; '_sort'?: string;
/**
* years
*/
'risk-horizon'?: (number | null); 'risk-horizon'?: (number | null);
/**
* any of ('DiagnosticReport:subject', 'RiskAssessment:subject', 'Observation:subject')
*/
'_revinclude'?: Array<string>; '_revinclude'?: Array<string>;
/**
* DiagnosticReport:result
*/
'_include:iterate'?: Array<string>; '_include:iterate'?: Array<string>;
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
-3
View File
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface SearchProcedure$Params { export interface SearchProcedure$Params {
domain: Domain; domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null); subject?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
@@ -12,9 +12,6 @@ import { Domain } from '../../models/domain';
export interface SearchRiskAssessment$Params { export interface SearchRiskAssessment$Params {
domain: Domain; domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null); subject?: (string | null);
'_count'?: (number | null); '_count'?: (number | null);
'_offset'?: number; '_offset'?: number;
-38
View File
@@ -1,38 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface 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';
@@ -1,43 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyUploadTrainingInputs } from '../../models/body-upload-training-inputs';
import { Domain } from '../../models/domain';
export interface UploadTrainingInputs$Params {
domain: Domain;
name: string;
set: string;
body: BodyUploadTrainingInputs
}
export function uploadTrainingInputs(http: HttpClient, rootUrl: string, params: UploadTrainingInputs$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
}>> {
const rb = new RequestBuilder(rootUrl, uploadTrainingInputs.PATH, 'post');
if (params) {
rb.path('domain', params.domain, {});
rb.path('name', params.name, {});
rb.path('set', params.set, {});
rb.body(params.body, 'multipart/form-data');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: any;
}>;
})
);
}
uploadTrainingInputs.PATH = '/models/{domain}/{name}/inputs/{set}/files';
-16
View File
@@ -13,8 +13,6 @@ export type { ExecutionHealth$Params as ExecutionHealth$Params } from './fn/exec
export { executionHealth as executionHealth } 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 type { ExecutionOptions$Params as ExecutionOptions$Params } from './fn/execution/execution-options';
export { executionOptions as executionOptions } 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'; export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/get-concept-map';
export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map'; export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map';
export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map'; export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map';
@@ -37,8 +35,6 @@ export type { OauthStart$Params as OauthStart$Params } from './fn/ingest/oauth-s
export { oauthStart as oauthStart } from './fn/ingest/oauth-start'; export { oauthStart as oauthStart } from './fn/ingest/oauth-start';
export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview'; export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
export { sourcePreview as sourcePreview } from './fn/ingest/source-preview'; export { sourcePreview as sourcePreview } from './fn/ingest/source-preview';
export type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
export { sourceResources as sourceResources } from './fn/ingest/source-resources';
export type { TestSource$Params as TestSource$Params } from './fn/ingest/test-source'; export type { TestSource$Params as TestSource$Params } from './fn/ingest/test-source';
export { testSource as testSource } from './fn/ingest/test-source'; export { testSource as testSource } from './fn/ingest/test-source';
export type { SourceTypes$Params as SourceTypes$Params } from './fn/ingest/source-types'; export type { SourceTypes$Params as SourceTypes$Params } from './fn/ingest/source-types';
@@ -57,10 +53,6 @@ export type { Score$Params as Score$Params } from './fn/models/score';
export { score as score } from './fn/models/score'; export { score as score } from './fn/models/score';
export type { Train$Params as Train$Params } from './fn/models/train'; export type { Train$Params as Train$Params } from './fn/models/train';
export { train as train } from './fn/models/train'; export { train as train } from './fn/models/train';
export type { TrainingInputs$Params as TrainingInputs$Params } from './fn/models/training-inputs';
export { trainingInputs as trainingInputs } from './fn/models/training-inputs';
export type { UploadTrainingInputs$Params as UploadTrainingInputs$Params } from './fn/models/upload-training-inputs';
export { uploadTrainingInputs as uploadTrainingInputs } from './fn/models/upload-training-inputs';
export type { TrainingConfig$Params as TrainingConfig$Params } from './fn/models/training-config'; export type { TrainingConfig$Params as TrainingConfig$Params } from './fn/models/training-config';
export { trainingConfig as trainingConfig } from './fn/models/training-config'; export { trainingConfig as trainingConfig } from './fn/models/training-config';
export type { Versions$Params as Versions$Params } from './fn/models/versions'; export type { Versions$Params as Versions$Params } from './fn/models/versions';
@@ -115,16 +107,8 @@ export type { PreviewStatus$Params as PreviewStatus$Params } from './fn/preview/
export { previewStatus as previewStatus } from './fn/preview/preview-status'; export { previewStatus as previewStatus } from './fn/preview/preview-status';
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user'; export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
export { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user'; export { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user';
export type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
export { usersPatchCurrentUser as usersPatchCurrentUser } from './fn/users/users-patch-current-user';
export type { RegisterRegister$Params as RegisterRegister$Params } from './fn/users/register-register'; export type { RegisterRegister$Params as RegisterRegister$Params } from './fn/users/register-register';
export { registerRegister as registerRegister } from './fn/users/register-register'; export { registerRegister as registerRegister } from './fn/users/register-register';
export type { UsersUser$Params as UsersUser$Params } from './fn/users/users-user';
export { usersUser as usersUser } from './fn/users/users-user';
export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/users/users-delete-user';
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle'; export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle'; export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition'; export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
+3 -4
View File
@@ -9,7 +9,6 @@ export type { BodyAddClinicalValidation } from './models/body-add-clinical-valid
export type { BodyImportModels } from './models/body-import-models'; export type { BodyImportModels } from './models/body-import-models';
export type { BodyStartPreview } from './models/body-start-preview'; export type { BodyStartPreview } from './models/body-start-preview';
export type { BodyUpload } from './models/body-upload'; export type { BodyUpload } from './models/body-upload';
export type { BodyUploadTrainingInputs } from './models/body-upload-training-inputs';
export type { Browsed } from './models/browsed'; export type { Browsed } from './models/browsed';
export type { Cancel } from './models/cancel'; export type { Cancel } from './models/cancel';
export type { Catalog } from './models/catalog'; export type { Catalog } from './models/catalog';
@@ -23,6 +22,7 @@ export type { Execution } from './models/execution';
export type { Extract } from './models/extract'; export type { Extract } from './models/extract';
export type { Fhir } from './models/fhir'; export type { Fhir } from './models/fhir';
export type { FieldSpec } from './models/field-spec'; export type { FieldSpec } from './models/field-spec';
export type { FolderTrainingSource } from './models/folder-training-source';
export type { Group } from './models/group'; export type { Group } from './models/group';
export type { Guided } from './models/guided'; export type { Guided } from './models/guided';
export type { Health } from './models/health'; export type { Health } from './models/health';
@@ -47,7 +47,6 @@ export type { PreviewStatus } from './models/preview-status';
export type { Progress } from './models/progress'; export type { Progress } from './models/progress';
export type { Provider } from './models/provider'; export type { Provider } from './models/provider';
export type { Read } from './models/read'; export type { Read } from './models/read';
export type { Reference } from './models/reference';
export type { Rejection } from './models/rejection'; export type { Rejection } from './models/rejection';
export type { Route } from './models/route'; export type { Route } from './models/route';
export type { Run } from './models/run'; export type { Run } from './models/run';
@@ -58,8 +57,8 @@ export type { Scope } from './models/scope';
export type { Score } from './models/score'; export type { Score } from './models/score';
export type { SignIn } from './models/sign-in'; export type { SignIn } from './models/sign-in';
export type { Site } from './models/site'; export type { Site } from './models/site';
export type { SiteTrainingSource } from './models/site-training-source';
export type { Source } from './models/source'; export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type'; export type { SourceType } from './models/source-type';
export type { Step } from './models/step'; export type { Step } from './models/step';
export type { Study } from './models/study'; export type { Study } from './models/study';
@@ -68,10 +67,10 @@ export type { Tasks } from './models/tasks';
export type { Tested } from './models/tested'; export type { Tested } from './models/tested';
export type { Training } from './models/training'; export type { Training } from './models/training';
export type { TrainingConfig } from './models/training-config'; export type { TrainingConfig } from './models/training-config';
export type { TrainingSource } from './models/training-source';
export type { Uploaded } from './models/uploaded'; export type { Uploaded } from './models/uploaded';
export type { UserCreate } from './models/user-create'; export type { UserCreate } from './models/user-create';
export type { UserRead } from './models/user-read'; export type { UserRead } from './models/user-read';
export type { UserUpdate } from './models/user-update';
export type { ValidationError } from './models/validation-error'; export type { ValidationError } from './models/validation-error';
export type { Version } from './models/version'; export type { Version } from './models/version';
export type { Worker } from './models/worker'; export type { Worker } from './models/worker';
-6
View File
@@ -3,14 +3,8 @@
export interface Condition { export interface Condition {
/**
* Por ejemplo «text», el texto leído del documento.
*/
column: string; column: string;
op: 'equals' | 'contains' | 'matches' | 'present'; op: 'equals' | 'contains' | 'matches' | 'present';
/**
* Lo que se busca; por ejemplo «citología».
*/
value?: string; value?: string;
} }
-4
View File
@@ -2,10 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One field of one record as a reviewer read it in the source document: an identity
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction { export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string; field: string;
-3
View File
@@ -3,9 +3,6 @@
import { Domain } from './domain'; import { Domain } from './domain';
/**
* Each possible value of `Domain`
*/
export const DOMAIN: Domain[] = [ export const DOMAIN: Domain[] = [
'cacu', 'cacu',
'cama', 'cama',
-18
View File
@@ -3,30 +3,12 @@
import { Position } from '../models/position'; 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 { export interface Edf {
column: string; column: string;
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'edf'; kind?: 'edf';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
} }
-3
View File
@@ -2,9 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* 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 { export interface Execution {
mode?: ('sync' | 'local' | 'remote' | null); mode?: ('sync' | 'local' | 'remote' | null);
scheduler?: (string | null); scheduler?: (string | null);
-23
View File
@@ -3,50 +3,27 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Platform fields read from text, each kept with the text it was read from.
*
* `auto` asks the LLM when one is configured and answering, else applies `patterns`;
* with neither, the row is held. Patterns are regexes with one group, per field (the
* LLM can propose them from sample documents); their values go through the ConceptMap
* and `formats` as in `map`.
*/
export interface Extract { export interface Extract {
column: (string | Array<string>); column: (string | Array<string>);
/**
* Dato → columna, sin leer el texto.
*/
columns?: { columns?: {
[key: string]: string; [key: string]: string;
}; };
concept_map?: (string | null); concept_map?: (string | null);
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
/**
* Para el modelo de lenguaje.
*/
hints?: string; hints?: string;
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'extract'; kind?: 'extract';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
method?: 'auto' | 'llm' | 'patterns'; method?: 'auto' | 'llm' | 'patterns';
/**
* Dato → expresión con un grupo ( ).
*/
patterns?: { patterns?: {
[key: string]: string; [key: string]: string;
}; };
-8
View File
@@ -3,11 +3,6 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* FHIR R4 Bundles a standard hospital sent (a column of their JSON) as rows of one
* entity: identity, death or a study (core.fhir_in). The sender's own codes go through
* its ConceptMap.
*/
export interface Fhir { export interface Fhir {
column?: string; column?: string;
concept_map?: (string | null); concept_map?: (string | null);
@@ -16,9 +11,6 @@ export interface Fhir {
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'fhir'; kind?: 'fhir';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
} }
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface FolderTrainingSource {
folder: string;
kind: 'folder';
line_hz?: 50 | 60;
}
-4
View File
@@ -2,10 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* How the Conectar dialog drew a source: its type (core.sources) and the answers given.
* The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none.
*/
export interface Guided { export interface Guided {
answers?: { answers?: {
[key: string]: any; [key: string]: any;
-9
View File
@@ -3,23 +3,14 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Two inputs side by side where their columns match.
*/
export interface Join { export interface Join {
how?: 'inner' | 'left'; how?: 'inner' | 'left';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'join'; kind?: 'join';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
/**
* Columna de la primera entrada = columna de la segunda.
*/
on: Array<[string, string]>; on: Array<[string, string]>;
position?: (Position | null); position?: (Position | null);
} }
-17
View File
@@ -3,33 +3,16 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Identity rows from every input, grouped into persons (Splink).
*
* Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
* and `r.` for the two records); persons are the connected groups. A person whose
* records disagree on birth date or sex is held for review as a whole. Pairs Splink
* scores above `review` that ended up apart are queued as possible matches.
*/
export interface Link { export interface Link {
fields?: Array<string>; fields?: Array<string>;
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'link'; kind?: 'link';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
/**
* Parecidos por encima de esto los ve un revisor.
*/
review?: number; review?: number;
/**
* Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).
*/
rules?: Array<string>; rules?: Array<string>;
} }
-4
View File
@@ -2,10 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* What "Probar conexión" shows: a database's tables (the resources of `source`, built
* from `args`), or the first rows the type's own node reads (files, records).
*/
export interface Listing { export interface Listing {
args?: { args?: {
[key: string]: any; [key: string]: any;
-19
View File
@@ -3,27 +3,14 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Columns to platform fields, the site's codes translated by its ConceptMap
* (core.concept_map), and its date formats.
*/
export interface Map { export interface Map {
/**
* La tabla de códigos del sitio.
*/
concept_map?: (string | null); concept_map?: (string | null);
/**
* Dato de la plataforma → columna del sitio.
*/
fields: { fields: {
[key: string]: string; [key: string]: string;
}; };
/**
* Por ejemplo %d/%m/%Y.
*/
formats?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
@@ -31,15 +18,9 @@ export interface Map {
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'map'; kind?: 'map';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
/**
* Un dato igual para todas las filas.
*/
values?: { values?: {
[key: string]: string; [key: string]: string;
}; };
-3
View File
@@ -4,9 +4,6 @@
import { Tasks } from '../models/tasks'; import { Tasks } from '../models/tasks';
import { Worker } from '../models/worker'; import { Worker } from '../models/worker';
/**
* The run tag's JSON; the API returns it as it is.
*/
export interface Progress { export interface Progress {
done: number; done: number;
elapsed_s: number; elapsed_s: number;
-3
View File
@@ -2,9 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* A sign-in button's OAuth 2.0 provider (authorization code flow).
*/
export interface Provider { export interface Provider {
authorize_params?: { authorize_params?: {
[key: string]: string; [key: string]: string;
-9
View File
@@ -3,22 +3,13 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
*/
export interface Read { export interface Read {
/**
* Donde la entrada trae cada documento.
*/
column: string; column: string;
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'read'; kind?: 'read';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
} }
-11
View File
@@ -1,11 +0,0 @@
/* 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;
}
-11
View File
@@ -4,24 +4,13 @@
import { Condition } from '../models/condition'; import { Condition } from '../models/condition';
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Only the rows where every condition holds (e.g. reports titled "Citología"). An
* `otherwise` route takes the rows of its input that none of the other routes on that
* input take (documents nobody recognises, for a reviewer), then its own conditions.
*/
export interface Route { export interface Route {
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'route'; kind?: 'route';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
/**
* Recoge lo que nadie reconoce, para revisarlo.
*/
otherwise?: boolean; otherwise?: boolean;
position?: (Position | null); position?: (Position | null);
when?: Array<Condition>; when?: Array<Condition>;
-4
View File
@@ -2,10 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* 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 { export interface Scope {
ids?: Array<string>; ids?: Array<string>;
mode?: 'pending' | 'first_n' | 'ids'; mode?: 'pending' | 'first_n' | 'ids';
@@ -1,6 +1,6 @@
/* eslint-disable */ /* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUploadTrainingInputs { export interface SiteTrainingSource {
files: Array<Blob>; kind: 'site';
} }
-22
View File
@@ -4,15 +4,8 @@
import { Guided } from '../models/guided'; import { Guided } from '../models/guided';
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* One table, file set or API resource, copied as it is (dlt). Merged on the source's
* own primary key or `primary_key`; replaced whole when it has none.
*/
export interface Source { export interface Source {
/**
* Los de la fuente dlt.
*/
args?: { args?: {
[key: string]: any; [key: string]: any;
}; };
@@ -21,29 +14,14 @@ export interface Source {
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'source'; kind?: 'source';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
/**
* Columnas que identifican una fila.
*/
primary_key?: Array<string>; primary_key?: Array<string>;
/**
* Cuál, si la fuente ofrece varios (una tabla).
*/
resource?: (string | null); resource?: (string | null);
/**
* Módulo:función de la fuente dlt.
*/
source: string; source: string;
/**
* Transformador dlt para los archivos.
*/
then?: (string | null); then?: (string | null);
} }
-10
View File
@@ -3,23 +3,13 @@
import { Position } from '../models/position'; import { Position } from '../models/position';
/**
* Rows of platform fields into one platform entity, each row given its person by the
* one `link` node among the inputs. Rule breaks are held for review.
*/
export interface Target { export interface Target {
/**
* En qué estudio de la plataforma se guarda.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'target'; kind?: 'target';
/**
* Cómo se ve en el diagrama.
*/
label?: string; label?: string;
position?: (Position | null); position?: (Position | null);
} }
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { FolderTrainingSource } from '../models/folder-training-source';
import { SiteTrainingSource } from '../models/site-training-source';
export type TrainingSource = (SiteTrainingSource | FolderTrainingSource);
+2 -5
View File
@@ -2,14 +2,11 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Execution } from '../models/execution'; import { Execution } from '../models/execution';
import { Reference } from '../models/reference'; import { TrainingSource } from '../models/training-source';
export interface Training { export interface Training {
/**
* Fecha de corte de los datos (por omisión, hoy)
*/
as_of?: (string | null); as_of?: (string | null);
execution?: (Execution | null); execution?: (Execution | null);
models?: Array<string>; models?: Array<string>;
reference?: (Reference | null); source?: (TrainingSource | null);
} }
-59
View File
@@ -3,10 +3,6 @@
import { HttpRequest, HttpParameterCodec, HttpParams, HttpHeaders, HttpContext } from '@angular/common/http'; import { HttpRequest, HttpParameterCodec, HttpParams, HttpHeaders, HttpContext } from '@angular/common/http';
/**
* Custom parameter codec to correctly handle the plus sign in parameter
* values. See https://github.com/angular/angular/issues/18261
*/
class ParameterCodec implements HttpParameterCodec { class ParameterCodec implements HttpParameterCodec {
encodeKey(key: string): string { encodeKey(key: string): string {
return encodeURIComponent(key); return encodeURIComponent(key);
@@ -26,17 +22,11 @@ class ParameterCodec implements HttpParameterCodec {
} }
const ParameterCodecInstance = new ParameterCodec(); const ParameterCodecInstance = new ParameterCodec();
/**
* Defines the options for appending a parameter
*/
interface ParameterOptions { interface ParameterOptions {
style?: string; style?: string;
explode?: boolean; explode?: boolean;
} }
/**
* Base class for a parameter
*/
abstract class Parameter { abstract class Parameter {
constructor(public name: string, public value: any, public options: ParameterOptions, defaultStyle: string, defaultExplode: boolean) { constructor(public name: string, public value: any, public options: ParameterOptions, defaultStyle: string, defaultExplode: boolean) {
this.options = options || {}; this.options = options || {};
@@ -74,9 +64,6 @@ abstract class Parameter {
} }
} }
/**
* A parameter in the operation path
*/
class PathParameter extends Parameter { class PathParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) { constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'simple', false); super(name, value, options, 'simple', false);
@@ -91,24 +78,20 @@ class PathParameter extends Parameter {
let separator = this.options.explode ? prefix === '' ? ',' : prefix : ','; let separator = this.options.explode ? prefix === '' ? ',' : prefix : ',';
let alreadySerialized = false; let alreadySerialized = false;
if (this.options.style === 'matrix') { if (this.options.style === 'matrix') {
// The parameter name is just used as prefix, except in some cases...
prefix = `;${this.name}=`; prefix = `;${this.name}=`;
if (this.options.explode && typeof value === 'object') { if (this.options.explode && typeof value === 'object') {
prefix = ';'; prefix = ';';
if (value instanceof Array) { if (value instanceof Array) {
// For arrays we have to repeat the name for each element
value = value.map(v => `${this.name}=${this.serializeValue(v, ';')}`); value = value.map(v => `${this.name}=${this.serializeValue(v, ';')}`);
value = value.join(';'); value = value.join(';');
alreadySerialized = true; alreadySerialized = true;
} else { } else {
// For objects we have to put each the key / value pairs
value = this.serializeValue(value, ';'); value = this.serializeValue(value, ';');
alreadySerialized = true alreadySerialized = true
} }
} }
} }
value = prefix + (alreadySerialized ? value : this.serializeValue(value, separator)); value = prefix + (alreadySerialized ? value : this.serializeValue(value, separator));
// Replace both the plain variable and the corresponding variant taking in the prefix and explode into account
path = path.replace(`{${this.name}}`, value); path = path.replace(`{${this.name}}`, value);
path = path.replace(`{${prefix}${this.name}${this.options.explode ? '*' : ''}}`, value); path = path.replace(`{${prefix}${this.name}${this.options.explode ? '*' : ''}}`, value);
return path; return path;
@@ -124,9 +107,6 @@ class PathParameter extends Parameter {
} }
} }
/**
* A parameter in the query
*/
class QueryParameter extends Parameter { class QueryParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) { constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'form', true); super(name, value, options, 'form', true);
@@ -134,7 +114,6 @@ class QueryParameter extends Parameter {
append(params: HttpParams): HttpParams { append(params: HttpParams): HttpParams {
if (this.value instanceof Array) { if (this.value instanceof Array) {
// Array serialization
if (this.options.explode) { if (this.options.explode) {
for (const v of this.value) { for (const v of this.value) {
params = params.append(this.name, this.serializeValue(v)); params = params.append(this.name, this.serializeValue(v));
@@ -146,9 +125,7 @@ class QueryParameter extends Parameter {
return params.append(this.name, this.serializeValue(this.value, separator)); return params.append(this.name, this.serializeValue(this.value, separator));
} }
} else if (this.value !== null && typeof this.value === 'object') { } else if (this.value !== null && typeof this.value === 'object') {
// Object serialization
if (this.options.style === 'deepObject') { if (this.options.style === 'deepObject') {
// Append a parameter for each key, in the form `name[key]`
for (const key of Object.keys(this.value)) { for (const key of Object.keys(this.value)) {
const propVal = this.value[key]; const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) { if (propVal !== null && propVal !== undefined) {
@@ -156,7 +133,6 @@ class QueryParameter extends Parameter {
} }
} }
} else if (this.options.explode) { } else if (this.options.explode) {
// Append a parameter for each key without using the parameter name
for (const key of Object.keys(this.value)) { for (const key of Object.keys(this.value)) {
const propVal = this.value[key]; const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) { if (propVal !== null && propVal !== undefined) {
@@ -164,7 +140,6 @@ class QueryParameter extends Parameter {
} }
} }
} else { } else {
// Append a single parameter whose values are a comma-separated list of key,value,key,value...
const array: any[] = []; const array: any[] = [];
for (const key of Object.keys(this.value)) { for (const key of Object.keys(this.value)) {
const propVal = this.value[key]; const propVal = this.value[key];
@@ -176,16 +151,12 @@ class QueryParameter extends Parameter {
params = params.append(this.name, this.serializeValue(array)); params = params.append(this.name, this.serializeValue(array));
} }
} else if (this.value !== null && this.value !== undefined) { } else if (this.value !== null && this.value !== undefined) {
// Plain value
params = params.append(this.name, this.serializeValue(this.value)); params = params.append(this.name, this.serializeValue(this.value));
} }
return params; return params;
} }
} }
/**
* A parameter in the HTTP request header
*/
class HeaderParameter extends Parameter { class HeaderParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) { constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'simple', false); super(name, value, options, 'simple', false);
@@ -205,9 +176,6 @@ class HeaderParameter extends Parameter {
} }
} }
/**
* Helper to build http requests from parameters
*/
export class RequestBuilder { export class RequestBuilder {
private _path = new Map<string, PathParameter>(); private _path = new Map<string, PathParameter>();
@@ -222,30 +190,18 @@ export class RequestBuilder {
public method: string) { public method: string) {
} }
/**
* Sets a path parameter
*/
path(name: string, value: any, options?: ParameterOptions): void { path(name: string, value: any, options?: ParameterOptions): void {
this._path.set(name, new PathParameter(name, value, options || {})); this._path.set(name, new PathParameter(name, value, options || {}));
} }
/**
* Sets a query parameter
*/
query(name: string, value: any, options?: ParameterOptions): void { query(name: string, value: any, options?: ParameterOptions): void {
this._query.set(name, new QueryParameter(name, value, options || {})); this._query.set(name, new QueryParameter(name, value, options || {}));
} }
/**
* Sets a header parameter
*/
header(name: string, value: any, options?: ParameterOptions): void { header(name: string, value: any, options?: ParameterOptions): void {
this._header.set(name, new HeaderParameter(name, value, options || {})); this._header.set(name, new HeaderParameter(name, value, options || {}));
} }
/**
* Sets the body content, along with the content type
*/
body(value: any, contentType = 'application/json'): void { body(value: any, contentType = 'application/json'): void {
if (value instanceof Blob) { if (value instanceof Blob) {
this._bodyContentType = value.type; this._bodyContentType = value.type;
@@ -253,7 +209,6 @@ export class RequestBuilder {
this._bodyContentType = contentType; this._bodyContentType = contentType;
} }
if (this._bodyContentType === 'application/x-www-form-urlencoded' && value !== null && typeof value === 'object') { if (this._bodyContentType === 'application/x-www-form-urlencoded' && value !== null && typeof value === 'object') {
// Handle URL-encoded data
const pairs: Array<[string, string]> = []; const pairs: Array<[string, string]> = [];
for (const key of Object.keys(value)) { for (const key of Object.keys(value)) {
let val = value[key]; let val = value[key];
@@ -269,7 +224,6 @@ export class RequestBuilder {
} }
this._bodyContent = pairs.map(p => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`).join('&'); this._bodyContent = pairs.map(p => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`).join('&');
} else if (this._bodyContentType === 'multipart/form-data') { } else if (this._bodyContentType === 'multipart/form-data') {
// Handle multipart form data
const formData = new FormData(); const formData = new FormData();
if (value !== null && value !== undefined) { if (value !== null && value !== undefined) {
for (const key of Object.keys(value)) { for (const key of Object.keys(value)) {
@@ -291,7 +245,6 @@ export class RequestBuilder {
} }
this._bodyContent = formData; this._bodyContent = formData;
} else { } else {
// The body is the plain content
this._bodyContent = value; this._bodyContent = value;
} }
} }
@@ -309,33 +262,24 @@ export class RequestBuilder {
return String(value); return String(value);
} }
/**
* Builds the request with the current set parameters
*/
build<T = any>(options?: { build<T = any>(options?: {
/** Which content types to accept */
accept?: string; accept?: string;
/** The expected response type */
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'; responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';
/** Whether to report progress on uploads / downloads */
reportProgress?: boolean; reportProgress?: boolean;
/** Allow passing HttpContext for HttpClient */
context?: HttpContext; context?: HttpContext;
}): HttpRequest<T> { }): HttpRequest<T> {
options = options || {}; options = options || {};
// Path parameters
let path = this.operationPath; let path = this.operationPath;
for (const pathParam of this._path.values()) { for (const pathParam of this._path.values()) {
path = pathParam.append(path); path = pathParam.append(path);
} }
const url = this.rootUrl + path; const url = this.rootUrl + path;
// Query parameters
let httpParams = new HttpParams({ let httpParams = new HttpParams({
encoder: ParameterCodecInstance encoder: ParameterCodecInstance
}); });
@@ -343,7 +287,6 @@ export class RequestBuilder {
httpParams = queryParam.append(httpParams); httpParams = queryParam.append(httpParams);
} }
// Header parameters
let httpHeaders = new HttpHeaders(); let httpHeaders = new HttpHeaders();
if (options.accept) { if (options.accept) {
httpHeaders = httpHeaders.append('Accept', options.accept); httpHeaders = httpHeaders.append('Accept', options.accept);
@@ -352,12 +295,10 @@ export class RequestBuilder {
httpHeaders = headerParam.append(httpHeaders); httpHeaders = headerParam.append(httpHeaders);
} }
// Request content headers
if (this._bodyContentType && !(this._bodyContent instanceof FormData)) { if (this._bodyContentType && !(this._bodyContent instanceof FormData)) {
httpHeaders = httpHeaders.set('Content-Type', this._bodyContentType); httpHeaders = httpHeaders.set('Content-Type', this._bodyContentType);
} }
// Perform the request
return new HttpRequest<T>(this.method.toUpperCase(), url, this._bodyContent, { return new HttpRequest<T>(this.method.toUpperCase(), url, this._bodyContent, {
params: httpParams, params: httpParams,
headers: httpHeaders, headers: httpHeaders,
-3
View File
@@ -3,9 +3,6 @@
import { HttpResponse } from '@angular/common/http'; import { HttpResponse } from '@angular/common/http';
/**
* Constrains the http response to not have the body defined as `T | null`, but `T` only.
*/
export type StrictHttpResponse<T> = HttpResponse<T> & { export type StrictHttpResponse<T> = HttpResponse<T> & {
readonly body: T; readonly body: T;
} }
-1
View File
@@ -16,7 +16,6 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes, withComponentInputBinding()), provideRouter(routes, withComponentInputBinding()),
provideHttpClient(), provideHttpClient(),
provideApiConfiguration('/api'), provideApiConfiguration('/api'),
// Icons are the Material Symbols font served with the app.
provideAppInitializer(() => { provideAppInitializer(() => {
inject(MatIconRegistry).setDefaultFontSetClass('material-symbols-outlined'); inject(MatIconRegistry).setDefaultFontSetClass('material-symbols-outlined');
}), }),
+2 -2
View File
@@ -16,8 +16,8 @@ export const routes: Routes = [
{ {
path: 'indicadores/tea/pacientes/:id/riesgo', path: 'indicadores/tea/pacientes/:id/riesgo',
canActivate: [domainAllowed], canActivate: [domainAllowed],
data: { domain: 'tea' }, data: { domain: 'tea', risk: true },
loadComponent: () => import('./paciente/tea-patient').then((m) => m.TeaRisk), loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
}, },
{ {
path: 'indicadores/:domain/pacientes/:id', path: 'indicadores/:domain/pacientes/:id',
+1 -3
View File
@@ -21,7 +21,7 @@
.title { .title {
flex: 1; flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line min-width: 0;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
@@ -29,7 +29,6 @@
font-weight: 500; font-weight: 500;
} }
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain, .domain,
.sections a, .sections a,
.user { .user {
@@ -90,7 +89,6 @@
.sections { .sections {
gap: var(--space-3); gap: var(--space-3);
} }
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name { .user .who-name {
display: none; display: none;
} }
-5
View File
@@ -16,7 +16,6 @@ export const DOMAINS: Record<Domain, string> = {
tea: 'Trastorno del espectro autista', tea: 'Trastorno del espectro autista',
}; };
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
imports: [ imports: [
@@ -43,17 +42,13 @@ export class App {
), ),
{ initialValue: '' }, { initialValue: '' },
); );
/** The section and domain of a page that has one (indicators, governance): the switcher
* moves between that section's domains. */
private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url())); private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores'); protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined); protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
protected readonly others = computed(() => protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)), (this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
); );
/** The sign-in page shows only the brand. */
protected readonly onLogin = computed(() => this.url().startsWith('/login')); protected readonly onLogin = computed(() => this.url().startsWith('/login'));
/** Where "Indicadores" goes: the first domain this user may see. */
protected readonly home = computed( protected readonly home = computed(
() => `/indicadores/${this.auth.user()?.domains[0] ?? 'cacu'}`, () => `/indicadores/${this.auth.user()?.domains[0] ?? 'cacu'}`,
); );
+1 -9
View File
@@ -5,7 +5,6 @@ import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration'; import { ApiConfiguration } from '../api/api-configuration';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
/** Who is signed in, and the domains the app shows them. */
export interface User { export interface User {
id: string; id: string;
email: string; email: string;
@@ -14,18 +13,14 @@ export interface User {
domains: Domain[]; domains: Domain[];
} }
/** The web app's sign-in (the API's fastapi-users, a session cookie). It decides only what
* the app shows: the API answers without a session. */
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class Auth { export class Auth {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl; private readonly root = inject(ApiConfiguration).rootUrl;
/** undefined: not asked yet; null: nobody signed in. */
private readonly current = signal<User | null | undefined>(undefined); private readonly current = signal<User | null | undefined>(undefined);
readonly user = this.current.asReadonly(); readonly user = this.current.asReadonly();
readonly signedIn = computed(() => !!this.current()); readonly signedIn = computed(() => !!this.current());
/** Whether the signed-in user may see the domain (an administrator sees every one). */
canSee(domain: string): boolean { canSee(domain: string): boolean {
const u = this.current(); const u = this.current();
return !!u && (u.is_superuser || u.domains.includes(domain as Domain)); return !!u && (u.is_superuser || u.domains.includes(domain as Domain));
@@ -40,7 +35,6 @@ export class Auth {
return this.current() ?? null; return this.current() ?? null;
} }
/** Signs in; a wrong user or password comes back as words for the form. */
async login(email: string, password: string): Promise<string | null> { async login(email: string, password: string): Promise<string | null> {
const body = new HttpParams().set('username', email.trim()).set('password', password); const body = new HttpParams().set('username', email.trim()).set('password', password);
try { try {
@@ -64,15 +58,13 @@ export class Auth {
} }
} }
/** Pages show only to someone signed in; the others go to the sign-in page and come back. */
export const signedIn: CanActivateFn = async (_route, state) => { export const signedIn: CanActivateFn = async (_route, state) => {
const auth = inject(Auth); const auth = inject(Auth);
const router = inject(Router); // before any await: inject works only in the guard's first turn const router = inject(Router);
const user = auth.user() === undefined ? await auth.load() : auth.user(); const user = auth.user() === undefined ? await auth.load() : auth.user();
return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } }); return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
}; };
/** A domain's pages show only to whom may see it. */
export const domainAllowed: CanActivateFn = (route) => { export const domainAllowed: CanActivateFn = (route) => {
const auth = inject(Auth); const auth = inject(Auth);
const domain = route.paramMap.get('domain') ?? route.data['domain']; const domain = route.paramMap.get('domain') ?? route.data['domain'];
-3
View File
@@ -22,7 +22,6 @@
width: 100%; width: 100%;
} }
/* The brand opens the screen and is the biggest thing on it. */
.logo { .logo {
align-self: center; align-self: center;
animation: logo-in 600ms ease-out both; animation: logo-in 600ms ease-out both;
@@ -43,7 +42,6 @@
} }
} }
/* The title between two rules. */
.title { .title {
align-items: center; align-items: center;
color: var(--color-text); color: var(--color-text);
@@ -86,7 +84,6 @@
margin: -4px 0 0; margin: -4px 0 0;
} }
/* One column with the fields; its border turns to the action color once the form is complete. */
.enter { .enter {
align-items: center; align-items: center;
background: var(--login-background); background: var(--login-background);
-2
View File
@@ -7,7 +7,6 @@ import { MatInputModule } from '@angular/material/input';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { Auth } from './auth'; import { Auth } from './auth';
/** "Inicio de sesión": the brand, two fields and one button. */
@Component({ @Component({
selector: 'app-login', selector: 'app-login',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule], imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
@@ -17,7 +16,6 @@ import { Auth } from './auth';
export class Login { export class Login {
private readonly auth = inject(Auth); private readonly auth = inject(Auth);
private readonly router = inject(Router); private readonly router = inject(Router);
/** Where to go once signed in (the page that asked for it). */
readonly next = input<string>(''); readonly next = input<string>('');
protected email = ''; protected email = '';
protected password = ''; protected password = '';
-53
View File
@@ -1,53 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { MatDialog } from '@angular/material/dialog';
import { describe, expect, it, vi } from 'vitest';
import { CardActions } from './card-actions';
describe('CardActions', () => {
it('opens the published definition and emits back only through the filtered action', async () => {
const fixture = TestBed.createComponent(CardActions);
fixture.componentRef.setInput('measures', [
{
resourceType: 'Measure',
status: 'active',
title: 'Oportunidad',
description: 'Definición publicada',
group: [
{
population: [
{
code: { text: 'Numerador' },
criteria: { language: 'text/plain', description: 'Casos oportunos' },
},
{ criteria: { language: 'text/plain' } },
],
},
],
},
]);
const back = vi.fn();
fixture.componentInstance.back.subscribe(back);
fixture.detectChanges();
const host: HTMLElement = fixture.nativeElement;
expect(host.textContent).not.toContain('Volver');
host.querySelector<HTMLButtonElement>('[aria-label="Ver definición"]')!.click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(dialog.textContent).toContain('Oportunidad');
expect(dialog.textContent).toContain('Definición publicada');
expect(dialog.textContent).toContain('Numerador');
expect(dialog.textContent).toContain('Casos oportunos');
expect(dialog.textContent).toContain('Sin definición publicada');
TestBed.inject(MatDialog).closeAll();
fixture.componentRef.setInput('filtered', true);
fixture.detectChanges();
[...host.querySelectorAll('button')]
.find((button) => button.textContent?.trim() === 'Volver')!
.click();
expect(back).toHaveBeenCalledOnce();
});
});
-72
View File
@@ -1,72 +0,0 @@
import { Component, inject, input, output, TemplateRef } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatMenuModule } from '@angular/material/menu';
import type { Measure } from 'fhir/r4';
@Component({
selector: 'app-card-actions',
imports: [NgTemplateOutlet, MatButtonModule, MatDialogModule, MatMenuModule],
template: `
<button mat-icon-button type="button" aria-label="Ver definición" (click)="open(definition)">
?
</button>
@if (settings(); as content) {
<button mat-button type="button" [matMenuTriggerFor]="menu">Configuración</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
<ng-container [ngTemplateOutlet]="content" />
</ng-template>
</mat-menu>
}
@if (filtered()) {
<button mat-button type="button" (click)="back.emit()">Volver</button>
}
<ng-template #definition>
<h2 mat-dialog-title>Definición</h2>
<mat-dialog-content>
@for (measure of measures(); track $index) {
<h3>{{ measure.title }}</h3>
@if (measure.description) {
<p>{{ measure.description }}</p>
}
@for (group of measure.group ?? []; track $index) {
@for (population of group.population ?? []; track $index) {
<p>
@if (population.code?.text; as text) {
<strong>{{ text }}</strong>
}
@if (population.criteria.description; as description) {
{{ description }}
} @else if (!population.code?.text) {
Sin definición publicada
}
</p>
} @empty {
<p>Sin definición publicada</p>
}
} @empty {
<p>Sin definición publicada</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cerrar</button>
</mat-dialog-actions>
</ng-template>
`,
styles: ':host { display: inline-flex; align-items: center; gap: var(--space-1); }',
})
export class CardActions {
private readonly dialog = inject(MatDialog);
readonly measures = input.required<Measure[]>();
readonly settings = input<TemplateRef<unknown>>();
readonly filtered = input(false);
readonly back = output<void>();
protected open(template: TemplateRef<unknown>): void {
this.dialog.open(template);
}
}
+29 -16
View File
@@ -2,23 +2,30 @@ import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, output, signal } from '@angular/core'; import { Component, inject, input, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { getConceptMap } from '../api/fn/ingest/get-concept-map'; import { getConceptMap } from '../api/fn/ingest/get-concept-map';
import { saveConceptMap } from '../api/fn/ingest/save-concept-map'; import { saveConceptMap } from '../api/fn/ingest/save-concept-map';
/** One translation: a site's code onto a platform code of one target system. */
interface Row { interface Row {
target: string; target: string;
code: string; code: string;
platform: string; platform: string;
} }
/** A site's codes in platform terms (a FHIR ConceptMap), edited as a table: a new
* laboratory spelling is one more row. The API refuses a code no platform field allows. */
@Component({ @Component({
selector: 'app-concept-map-editor', selector: 'app-concept-map-editor',
imports: [FormsModule, MatButtonModule, MatIconModule], imports: [
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatSelectModule,
],
template: ` template: `
<h3> <h3>
Códigos del sitio · <span class="muted">{{ id() }}</span> Códigos del sitio · <span class="muted">{{ id() }}</span>
@@ -36,20 +43,31 @@ interface Row {
@for (row of rows(); track $index) { @for (row of rows(); track $index) {
<tr> <tr>
<td> <td>
<select [(ngModel)]="row.target" [attr.aria-label]="'Sistema destino ' + $index"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-select [(ngModel)]="row.target" [aria-label]="'Sistema destino ' + $index">
@for (t of targets(); track t) { @for (t of targets(); track t) {
<option [value]="t">{{ short(t) }}</option> <mat-option [value]="t">{{ short(t) }}</mat-option>
} }
</select> </mat-select>
</td> </mat-form-field>
<td>
<input [(ngModel)]="row.code" [attr.aria-label]="'Código del sitio ' + $index" />
</td> </td>
<td> <td>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<input <input
matInput
[(ngModel)]="row.code"
[attr.aria-label]="'Código del sitio ' + $index"
/>
</mat-form-field>
</td>
<td>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<input
matInput
[(ngModel)]="row.platform" [(ngModel)]="row.platform"
[attr.aria-label]="'Código de la plataforma ' + $index" [attr.aria-label]="'Código de la plataforma ' + $index"
/> />
</mat-form-field>
</td> </td>
<td> <td>
<button mat-icon-button (click)="remove($index)" aria-label="Quitar fila"> <button mat-icon-button (click)="remove($index)" aria-label="Quitar fila">
@@ -72,12 +90,8 @@ interface Row {
font-weight: 500; font-weight: 500;
margin: 16px 0 8px; margin: 16px 0 8px;
} }
input, mat-form-field {
select {
width: 100%; width: 100%;
box-sizing: border-box;
font: inherit;
padding: 4px;
} }
.actions { .actions {
display: flex; display: flex;
@@ -134,7 +148,6 @@ export class ConceptMapEditor {
this.rows.update((r) => r.filter((_, j) => j !== i)); this.rows.update((r) => r.filter((_, j) => j !== i));
} }
/** The rows as a ConceptMap: one group per target system. */
protected async save(): Promise<void> { protected async save(): Promise<void> {
const groups = new Map<string, Row[]>(); const groups = new Map<string, Row[]>();
for (const r of this.rows().filter((r) => r.target && r.code && r.platform)) { for (const r of this.rows().filter((r) => r.target && r.code && r.platform)) {
-2
View File
@@ -141,7 +141,6 @@ h2 {
} }
} }
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node { :host ::ng-deep default-node {
box-sizing: border-box; box-sizing: border-box;
overflow: hidden; overflow: hidden;
@@ -188,7 +187,6 @@ h2 {
font-size: 13px; font-size: 13px;
} }
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field { :host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3); margin-bottom: var(--space-3);
} }
+13 -32
View File
@@ -71,7 +71,7 @@ export const KINDS: Record<Kind, string> = {
link: 'Identificar a la persona', link: 'Identificar a la persona',
target: 'Guardar en la plataforma', target: 'Guardar en la plataforma',
}; };
export const HELP: Record<Kind, string> = { const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.', source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).', read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route: route:
@@ -86,8 +86,6 @@ export const HELP: Record<Kind, string> = {
}; };
const ID = /^[a-z][a-z0-9_]*$/; const ID = /^[a-z][a-z0-9_]*$/;
/** /conectar: an operator draws a site's pipeline on a canvas (nodes and the edges between
* them), fills each node's form, previews what it gives, saves a version and runs it. */
@Component({ @Component({
selector: 'app-conectar', selector: 'app-conectar',
imports: [ imports: [
@@ -105,7 +103,6 @@ const ID = /^[a-z][a-z0-9_]*$/;
Vflow, Vflow,
ConceptMapEditor, ConceptMapEditor,
], ],
// Forms are this page's only: Formly loads with it, not with the app.
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])], providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
templateUrl: './conectar.html', templateUrl: './conectar.html',
styleUrl: './conectar.scss', styleUrl: './conectar.scss',
@@ -116,7 +113,6 @@ export class Conectar {
private readonly dialog = inject(MatDialog); private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][]; protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP; protected readonly help = HELP;
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly rawDraft = signal<string | undefined>(undefined); protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal(''); protected readonly rawError = signal('');
@@ -125,7 +121,6 @@ export class Conectar {
protected readonly pipelineId = signal<string | undefined>(undefined); protected readonly pipelineId = signal<string | undefined>(undefined);
protected readonly version = signal<number | undefined>(undefined); protected readonly version = signal<number | undefined>(undefined);
/** The drawn pipeline: node configs (positions live on the canvas nodes). */
protected readonly docs = signal<Doc[]>([]); protected readonly docs = signal<Doc[]>([]);
protected readonly nodes = signal<CanvasNode[]>([]); protected readonly nodes = signal<CanvasNode[]>([]);
protected readonly edges = computed(() => protected readonly edges = computed(() =>
@@ -142,9 +137,18 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
}); });
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } }; protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => { protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {};
protected readonly fields = computed<FormlyFieldConfig[]>(() => {
const kind = this.doc()?.kind;
const pipeline = this.schema.value()?.['pipeline'];
if (!kind || !pipeline) return [];
return [this.jsonschema.toFieldConfig(nodeSchema(pipeline as never, kind))];
});
constructor() {
effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record< const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string, string,
{ properties?: Record<string, { title?: string }> } { properties?: Record<string, { title?: string }> }
@@ -156,15 +160,7 @@ export class Conectar {
]), ]),
); );
}); });
protected form = new UntypedFormGroup({}); }
protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */
protected readonly fields = computed<FormlyFieldConfig[]>(() => {
const kind = this.doc()?.kind;
const pipeline = this.schema.value()?.['pipeline'];
if (!kind || !pipeline) return [];
return [this.jsonschema.toFieldConfig(nodeSchema(pipeline as never, kind))];
});
protected readonly preview = signal<Record<string, unknown>[] | undefined>(undefined); protected readonly preview = signal<Record<string, unknown>[] | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.preview()?.[0] ?? {})); protected readonly columns = computed(() => Object.keys(this.preview()?.[0] ?? {}));
@@ -212,7 +208,6 @@ export class Conectar {
this.place(kind, {}); this.place(kind, {});
} }
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
protected async connectSource(id?: string): Promise<void> { protected async connectSource(id?: string): Promise<void> {
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined; const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
const data: SourceDialogData = { const data: SourceDialogData = {
@@ -292,12 +287,10 @@ export class Conectar {
this.rawError.set(''); this.rawError.set('');
} }
/** A source the dialog drew (its answers make its dlt fields). */
protected guided(d: Doc): Source['guided'] { protected guided(d: Doc): Source['guided'] {
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined; return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
} }
/** The form's values into the selected node. */
protected edited(model: Record<string, unknown>): void { protected edited(model: Record<string, unknown>): void {
const id = this.selected(); const id = this.selected();
if (!id) return; if (!id) return;
@@ -310,15 +303,11 @@ export class Conectar {
); );
} }
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string { protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown }; const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2); return JSON.stringify(rest, null, 2);
} }
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void { protected applyRaw(): void {
const d = this.doc(); const d = this.doc();
const text = this.rawDraft(); const text = this.rawDraft();
@@ -367,7 +356,6 @@ export class Conectar {
?.text.set(text(doc)); ?.text.set(text(doc));
} }
/** The drawn pipeline, each node where it sits on the canvas. */
private drawn(): Pipeline { private drawn(): Pipeline {
const at = new Map(this.nodes().map((n) => [n.id, n.point()])); const at = new Map(this.nodes().map((n) => [n.id, n.point()]));
return { nodes: this.docs().map((d) => ({ ...d, position: at.get(d.id) })) } as Pipeline; return { nodes: this.docs().map((d) => ({ ...d, position: at.get(d.id) })) } as Pipeline;
@@ -391,7 +379,6 @@ export class Conectar {
} }
} }
/** Saves, starts the `ingest` job and follows it to its end. */
protected async start(): Promise<void> { protected async start(): Promise<void> {
const id = this.pipelineId(); const id = this.pipelineId();
if (!id || !(await this.save())) return; if (!id || !(await this.save())) return;
@@ -410,7 +397,6 @@ export class Conectar {
} }
} }
/** What the node gives: a source's first rows, or what any other node gave in the last run. */
protected async show(): Promise<void> { protected async show(): Promise<void> {
const doc = this.doc(); const doc = this.doc();
const id = this.pipelineId(); const id = this.pipelineId();
@@ -427,12 +413,10 @@ export class Conectar {
} }
} }
/** The run in Dagster's own UI (its port beside this app's). */
protected readonly dagster = computed(() => { protected readonly dagster = computed(() => {
const run = this.run(); const run = this.run();
return run ? `${location.protocol}//${location.hostname}:5712/runs/${run.id}` : ''; return run ? `${location.protocol}//${location.hostname}:5712/runs/${run.id}` : '';
}); });
/** The ConceptMap a node names, if its kind takes one. */
protected conceptMap(d: Doc): string | undefined { protected conceptMap(d: Doc): string | undefined {
return 'concept_map' in d ? (d.concept_map ?? undefined) : undefined; return 'concept_map' in d ? (d.concept_map ?? undefined) : undefined;
} }
@@ -447,8 +431,6 @@ export class Conectar {
} }
function text(d: Doc): string { function text(d: Doc): string {
// ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source']; const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id); const name = escape(d.label || d.id);
return ( return (
@@ -457,7 +439,6 @@ function text(d: Doc): string {
); );
} }
/** Each node's distance from the sources: its column when it has no saved position. */
function depths(docs: Doc[]): Map<string, number> { function depths(docs: Doc[]): Map<string, number> {
const by = new Map(docs.map((d) => [d.id, d])); const by = new Map(docs.map((d) => [d.id, d]));
const found = new Map<string, number>(); const found = new Map<string, number>();
+5 -19
View File
@@ -16,11 +16,8 @@ import type { JSONSchema7 } from 'json-schema';
type Schema = JSONSchema7 & { $defs?: Record<string, Schema>; prefixItems?: unknown }; type Schema = JSONSchema7 & { $defs?: Record<string, Schema>; prefixItems?: unknown };
/** The canvas edits these itself; the form leaves them out. */
const CANVAS_FIELDS = ['id', 'kind', 'inputs', 'position']; const CANVAS_FIELDS = ['id', 'kind', 'inputs', 'position'];
/** A node kind's form schema from the pipeline's JSON Schema (pydantic's): `$ref`s inlined,
* optional values as their type, and maps or tuples (which forms don't draw) as JSON. */
export function nodeSchema(pipeline: Schema, kind: string): Schema { export function nodeSchema(pipeline: Schema, kind: string): Schema {
const defs = pipeline.$defs ?? {}; const defs = pipeline.$defs ?? {};
const name = Object.keys(defs).find( const name = Object.keys(defs).find(
@@ -28,10 +25,8 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!; )!;
const node = structuredClone(defs[name]); const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field]; for (const field of CANVAS_FIELDS) delete node.properties?.[field];
// The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title; delete node.title;
delete node.description; delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) { for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown }; const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple)) if ((value as { advanced?: boolean }).advanced || isJson(simple))
@@ -115,7 +110,6 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return out; return out;
} }
/** An object's fields, one after another. */
@Component({ @Component({
selector: 'app-formly-object', selector: 'app-formly-object',
imports: [FormlyField], imports: [FormlyField],
@@ -133,9 +127,8 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
styles: styles:
'.legend { font-weight: 500; margin: 8px 0 4px; } .hint { color: var(--color-text-secondary); font-size: 12px; margin: 0 0 8px; }', '.legend { font-weight: 500; margin: 8px 0 4px; } .hint { color: var(--color-text-secondary); font-size: 12px; margin: 0 0 8px; }',
}) })
export class ObjectType extends FieldType {} class ObjectType extends FieldType {}
/** A list: each item with a remove button, and an add button. */
@Component({ @Component({
selector: 'app-formly-array', selector: 'app-formly-array',
imports: [FormlyField, MatButtonModule, MatIconModule], imports: [FormlyField, MatButtonModule, MatIconModule],
@@ -156,9 +149,8 @@ export class ObjectType extends FieldType {}
styles: styles:
'.legend { font-weight: 500; margin: 8px 0 4px; } .item { display: flex; align-items: flex-start; gap: 4px; } .item formly-field { flex: 1; }', '.legend { font-weight: 500; margin: 8px 0 4px; } .item { display: flex; align-items: flex-start; gap: 4px; } .item formly-field { flex: 1; }',
}) })
export class ArrayType extends FieldArrayType {} class ArrayType extends FieldArrayType {}
/** A value forms don't draw (a map, a pair, anything), edited as JSON. */
@Component({ @Component({
selector: 'app-formly-json', selector: 'app-formly-json',
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule], imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
@@ -181,7 +173,7 @@ export class ArrayType extends FieldArrayType {}
`, `,
styles: '.json { width: 100%; } textarea { font-family: monospace; font-size: 12px; }', styles: '.json { width: 100%; } textarea { font-family: monospace; font-size: 12px; }',
}) })
export class JsonType extends FieldType<FormlyFieldConfig> { class JsonType extends FieldType<FormlyFieldConfig> {
protected error = ''; protected error = '';
protected text(): string { protected text(): string {
return this.formControl.value === undefined return this.formControl.value === undefined
@@ -199,8 +191,6 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
} }
} }
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({ @Component({
selector: 'app-formly-map', selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule], imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
@@ -270,9 +260,7 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
} }
`, `,
}) })
export class MapType extends FieldType<FormlyFieldConfig> { class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] { protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>; const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
@@ -297,7 +285,6 @@ export class MapType extends FieldType<FormlyFieldConfig> {
this.save(rows); this.save(rows);
} }
protected add(): void { protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows(); const rows = this.rows();
const used = new Set(rows.map(([k]) => k)); const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys'] const free = this.props['fieldKeys']
@@ -312,7 +299,6 @@ export class MapType extends FieldType<FormlyFieldConfig> {
} }
} }
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({ @Component({
selector: 'app-formly-pairs', selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule], imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
@@ -363,7 +349,7 @@ export class MapType extends FieldType<FormlyFieldConfig> {
} }
`, `,
}) })
export class PairsType extends FieldType<FormlyFieldConfig> { class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] { protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]); return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
} }
+2 -19
View File
@@ -26,7 +26,6 @@ import type { SourceType } from '../api/models/source-type';
import type { Tested } from '../api/models/tested'; import type { Tested } from '../api/models/tested';
import type { Uploaded } from '../api/models/uploaded'; import type { Uploaded } from '../api/models/uploaded';
/** What the dialog is opened with: the source being edited, if any. */
export interface SourceDialogData { export interface SourceDialogData {
pipeline?: string; pipeline?: string;
node?: string; node?: string;
@@ -35,13 +34,11 @@ export interface SourceDialogData {
} }
const NONE: string[] = []; const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult { export interface SourceDialogResult {
guided: Guided; guided: Guided;
label: string; label: string;
} }
/** The catalog's generic icon words, as Material Symbols. */
const ICONS: Record<string, string> = { const ICONS: Record<string, string> = {
database: 'database', database: 'database',
upload: 'upload_file', upload: 'upload_file',
@@ -58,9 +55,6 @@ const ICONS: Record<string, string> = {
}; };
const MASK = '********'; const MASK = '********';
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
@Component({ @Component({
selector: 'app-source-dialog', selector: 'app-source-dialog',
imports: [ imports: [
@@ -115,7 +109,6 @@ export class SourceDialog {
protected readonly showPassword = signal<Record<string, boolean>>({}); protected readonly showPassword = signal<Record<string, boolean>>({});
protected readonly testing = signal(false); protected readonly testing = signal(false);
/** The tables the last listing found: kept while one is picked and its rows shown. */
protected readonly tableList = signal<string[]>([]); protected readonly tableList = signal<string[]>([]);
protected readonly tested = signal<Tested | undefined>(undefined); protected readonly tested = signal<Tested | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {})); protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
@@ -160,7 +153,7 @@ export class SourceDialog {
protected set(name: string, value: unknown): void { protected set(name: string, value: unknown): void {
this.answers.update((a) => ({ ...a, [name]: value })); this.answers.update((a) => ({ ...a, [name]: value }));
if (this.type()?.fields[name]?.type === 'table') return; if (this.type()?.fields[name]?.type === 'table') return;
this.tested.set(undefined); // another connection: test again this.tested.set(undefined);
this.tableList.set([]); this.tableList.set([]);
} }
protected setNumber(name: string, value: string): void { protected setNumber(name: string, value: string): void {
@@ -180,7 +173,6 @@ export class SourceDialog {
return a ? (a.user ?? 'cuenta conectada') : undefined; return a ? (a.user ?? 'cuenta conectada') : undefined;
} }
/** "Probar conexión": what the source holds, in plain words. */
protected async test(): Promise<void> { protected async test(): Promise<void> {
const type = this.typeId(); const type = this.typeId();
if (!type) return; if (!type) return;
@@ -205,22 +197,18 @@ export class SourceDialog {
} }
} }
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] { protected listed(name: string): string[] {
const v = this.value(name); const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever return Array.isArray(v) ? (v as string[]) : NONE;
} }
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] { protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])]; return [...new Set([...this.columns(), ...this.listed(name)])];
} }
/** The tables a database listed, for its table field. */
protected tables(): string[] { protected tables(): string[] {
return this.tableList(); return this.tableList();
} }
/** Server folders, under the roots the operator mounted. */
protected async openFolder(field: string, path?: string | null): Promise<void> { protected async openFolder(field: string, path?: string | null): Promise<void> {
try { try {
const at = await this.api.invoke(browse, path ? { path } : {}); const at = await this.api.invoke(browse, path ? { path } : {});
@@ -239,14 +227,11 @@ export class SourceDialog {
if (b) this.set(b.field, path); if (b) this.set(b.field, path);
this.browsing.set(undefined); this.browsing.set(undefined);
} }
/** Whether the field being browsed takes a file (else a folder). */
protected readonly browsingFiles = computed(() => { protected readonly browsingFiles = computed(() => {
const b = this.browsing(); const b = this.browsing();
return !!b && this.type()?.fields[b.field]?.type === 'server_file'; return !!b && this.type()?.fields[b.field]?.type === 'server_file';
}); });
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
* subfolders. More files can be added to the same set. */
protected upload(field: string, list: FileList | null): void { protected upload(field: string, list: FileList | null): void {
if (!list?.length) return; if (!list?.length) return;
const body = new FormData(); const body = new FormData();
@@ -286,7 +271,6 @@ export class SourceDialog {
this.upload(field, event.dataTransfer?.files ?? null); this.upload(field, event.dataTransfer?.files ?? null);
} }
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
protected async signIn(field: string, provider: string): Promise<void> { protected async signIn(field: string, provider: string): Promise<void> {
this.problem.set(''); this.problem.set('');
let started; let started;
@@ -313,7 +297,6 @@ export class SourceDialog {
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? ''); return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
} }
/** Answers without empty ones (a default takes their place on the server). */
private cleaned(): Record<string, unknown> { private cleaned(): Record<string, unknown> {
return Object.fromEntries( return Object.fromEntries(
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined), Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
-3
View File
@@ -1,4 +1,3 @@
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = { export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda', frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha', frontal_right: 'Frontal derecha',
@@ -12,7 +11,6 @@ export const ZONE_NAMES: Record<string, string> = {
global: 'Global', global: 'Global',
}; };
/** The association's biomarkers (core.tea.association.BIOMARKERS). */
export const BIOMARKER_NAMES: Record<string, string> = { export const BIOMARKER_NAMES: Record<string, string> = {
spikes: 'Picos paroxísticos', spikes: 'Picos paroxísticos',
spindles: 'Husos de sueño N2', spindles: 'Husos de sueño N2',
@@ -20,7 +18,6 @@ export const BIOMARKER_NAMES: Record<string, string> = {
gradient: 'Gradiente anteroposterior', gradient: 'Gradiente anteroposterior',
}; };
/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */
export const OUTCOME_NAMES: Record<string, string> = { export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_01: 'Vocalización espontánea dirigida a otros', ados2_item_01: 'Vocalización espontánea dirigida a otros',
ados2_item_02: 'Señalar', ados2_item_02: 'Señalar',
+8
View File
@@ -0,0 +1,8 @@
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);
}
+1 -22
View File
@@ -1,6 +1,5 @@
import type { Bundle, Patient } from 'fhir/r4';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import { allRows, downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index'; import { downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index';
const mocks = vi.hoisted(() => { const mocks = vi.hoisted(() => {
const toFile = vi.fn(); const toFile = vi.fn();
@@ -61,26 +60,6 @@ describe('export', () => {
await expect(downloadPdf('tea-patient-4821-2026-11-30', [])).rejects.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 () => { it('passes the institutional header and generated timestamp footer to pdfmake', async () => {
const content = [{ text: 'Indicadores' }]; const content = [{ text: 'Indicadores' }];
await downloadPdf(name, content); await downloadPdf(name, content);
-20
View File
@@ -1,20 +0,0 @@
import type { Bundle } from 'fhir/r4';
import { MAX_ROWS } from './xlsx';
export async function allRows<T>(
first: string,
getPage: (url: string) => Promise<Bundle>,
max = MAX_ROWS,
): Promise<T[]> {
const rows: T[] = [];
let next: string | undefined = first;
while (next && rows.length < max) {
const page = await getPage(next);
for (const { resource } of page.entry ?? []) {
if (resource) rows.push(resource as T);
if (rows.length >= max) return rows;
}
next = page.link?.find(({ relation }) => relation === 'next')?.url;
}
return rows;
}
+1 -1
View File
@@ -1,4 +1,4 @@
export { allRows } from './fetch-all';
export { downloadPdf, type PdfContent } from './pdf'; export { downloadPdf, type PdfContent } from './pdf';
export { safeName } from './safe-name'; export { safeName } from './safe-name';
export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx'; export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx';
export { download } from './blob';
+14 -7
View File
@@ -1,15 +1,14 @@
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import type { Bundle, CodeableConcept, Extension, FhirResource } from 'fhir/r4'; import type { Bundle, CodeableConcept, Extension, FhirResource, Patient } from 'fhir/r4';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from './api/api-configuration'; import { ApiConfiguration } from './api/api-configuration';
/** Our extensions and code systems (core.fhir). */ export const CURP = 'https://isssteleon.org/fhir/sid/curp';
export const EXT = 'https://isssteleon.org/fhir/StructureDefinition/'; export const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
export type Params = Record<string, string | number | readonly (string | number)[] | undefined>; export type Params = Record<string, string | number | readonly (string | number)[] | undefined>;
/** The domain's FHIR base (`/{domain}/fhir`): reads and searches, typed as R4. */
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class Fhir { export class Fhir {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
@@ -19,7 +18,6 @@ export class Fhir {
return firstValueFrom(this.http.get<T>(`${this.root}/${domain}/fhir/${type}/${id}`)); return firstValueFrom(this.http.get<T>(`${this.root}/${domain}/fhir/${type}/${id}`));
} }
/** One page of a search. */
search(domain: string, type: string, params: Params = {}): Promise<Bundle> { search(domain: string, type: string, params: Params = {}): Promise<Bundle> {
const query = Object.fromEntries( const query = Object.fromEntries(
Object.entries(params).filter(([, v]) => v !== undefined), Object.entries(params).filter(([, v]) => v !== undefined),
@@ -29,7 +27,6 @@ export class Fhir {
); );
} }
/** The page a bundle's `next` (or `previous`) link points to, through our own base. */
follow(domain: string, bundle: Bundle, relation: 'next' | 'previous'): Promise<Bundle> | null { follow(domain: string, bundle: Bundle, relation: 'next' | 'previous'): Promise<Bundle> | null {
const link = bundle.link?.find((l) => l.relation === relation)?.url; const link = bundle.link?.find((l) => l.relation === relation)?.url;
if (!link) return null; if (!link) return null;
@@ -40,7 +37,6 @@ export class Fhir {
); );
} }
/** Every page of a search. */
async all(domain: string, type: string, params: Params = {}): Promise<Bundle[]> { async all(domain: string, type: string, params: Params = {}): Promise<Bundle[]> {
const pages = [await this.search(domain, type, params)]; const pages = [await this.search(domain, type, params)];
for (let next = this.follow(domain, pages[0], 'next'); next;) { for (let next = this.follow(domain, pages[0], 'next'); next;) {
@@ -52,7 +48,6 @@ export class Fhir {
} }
} }
/** The resources of a bundle (or of several pages), by search mode. */
export function resources<T extends FhirResource>( export function resources<T extends FhirResource>(
bundles: Bundle | Bundle[], bundles: Bundle | Bundle[],
type: T['resourceType'], type: T['resourceType'],
@@ -79,3 +74,15 @@ export function code(concept: CodeableConcept | undefined): string | undefined {
export function label(concept: CodeableConcept | undefined): string { export function label(concept: CodeableConcept | undefined): string {
return concept?.text ?? concept?.coding?.[0]?.display ?? concept?.coding?.[0]?.code ?? ''; return concept?.text ?? concept?.coding?.[0]?.display ?? concept?.coding?.[0]?.code ?? '';
} }
export function patientName(patient: Patient | undefined): string | undefined {
return patient?.name?.[0]?.text;
}
export function patientCurp(patient: Patient | undefined): string | undefined {
return patient?.identifier?.find((i) => i.system === CURP)?.value;
}
export function extensions(element: { extension?: Extension[] }, name: string): Extension[] {
return (element.extension ?? []).filter((e) => e.url === EXT + name);
}
+41 -25
View File
@@ -1,7 +1,11 @@
import { download } from '../export';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { Component, inject, input, model, output, signal } from '@angular/core'; import { Component, inject, input, model, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { exportModels, type ExportModels$Params } from '../api/fn/models/export-models'; import { exportModels, type ExportModels$Params } from '../api/fn/models/export-models';
import { importModels } from '../api/fn/models/import-models'; import { importModels } from '../api/fn/models/import-models';
@@ -34,30 +38,21 @@ export async function exportErrorText(error: unknown): Promise<string> {
} }
} }
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({ @Component({
selector: 'app-governance-bundles', selector: 'app-governance-bundles',
imports: [FormsModule, MatButtonModule], imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
template: ` template: `
<section class="card"> <section class="card" aria-labelledby="bundles-heading">
<h3>Bundles</h3> <h2 id="bundles-heading">Bundles</h2>
<form (ngSubmit)="export()"> <form class="button-row" (ngSubmit)="export()">
<label <mat-form-field appearance="outline">
>Versiones <mat-label>Versiones</mat-label>
<select name="versions" [(ngModel)]="selection"> <mat-select name="versions" [(ngModel)]="selection">
<option value="champion">En producción</option> <mat-option value="champion">En producción</mat-option>
<option value="latest">Últimas</option> <mat-option value="latest">Últimas</mat-option>
<option value="all">Todas</option> <mat-option value="all">Todas</mat-option>
</select> </mat-select>
</label> </mat-form-field>
<button mat-stroked-button type="submit" [disabled]="exporting()">Exportar bundle</button> <button mat-stroked-button type="submit" [disabled]="exporting()">Exportar bundle</button>
</form> </form>
@if (exportedHash()) { @if (exportedHash()) {
@@ -65,10 +60,29 @@ export function download(blob: Blob, filename: string): void {
SHA-256 <code>{{ exportedHash() }}</code> SHA-256 <code>{{ exportedHash() }}</code>
</p> </p>
} }
<form (ngSubmit)="import(file)"> <form class="button-row" (ngSubmit)="import(file)">
<label>Archivo ZIP <input #file type="file" accept=".zip" required /></label> <input
<label>SHA-256 esperado <input name="hash" [(ngModel)]="hash" required /></label> #file
<button mat-stroked-button type="submit" [disabled]="importing() || disabled()"> type="file"
accept=".zip"
required
hidden
aria-label="Archivo ZIP"
(change)="zipFiles.set(file.files)"
/>
<button mat-stroked-button type="button" (click)="file.click()">Archivo ZIP</button>
@for (file of zipFiles(); track $index) {
<span>{{ file.name }}</span>
}
<mat-form-field appearance="outline">
<mat-label>SHA-256 esperado</mat-label>
<input matInput name="hash" [(ngModel)]="hash" required />
</mat-form-field>
<button
mat-stroked-button
type="submit"
[disabled]="importing() || disabled() || !zipFiles()?.length"
>
Importar bundle Importar bundle
</button> </button>
</form> </form>
@@ -85,6 +99,7 @@ export class Bundles {
readonly started = output<string>(); readonly started = output<string>();
protected readonly selection = signal<NonNullable<ExportModels$Params['versions']>>('champion'); protected readonly selection = signal<NonNullable<ExportModels$Params['versions']>>('champion');
protected readonly exportedHash = signal(''); protected readonly exportedHash = signal('');
protected readonly zipFiles = signal<FileList | null>(null);
protected readonly hash = signal(''); protected readonly hash = signal('');
protected readonly message = signal(''); protected readonly message = signal('');
protected readonly exporting = signal(false); protected readonly exporting = signal(false);
@@ -125,6 +140,7 @@ export class Bundles {
}), }),
); );
input.value = ''; input.value = '';
this.zipFiles.set(null);
if (domain === this.domain()) this.started.emit(run_id); if (domain === this.domain()) this.started.emit(run_id);
} catch (error) { } catch (error) {
this.message.set(errorText(error)); this.message.set(errorText(error));
+7 -3
View File
@@ -29,9 +29,13 @@ describe('execution', () => {
expect(fixture.componentInstance.execution()).toEqual({ mode: 'local', scheduler: null }); expect(fixture.componentInstance.execution()).toEqual({ mode: 'local', scheduler: null });
expect(invoke).toHaveBeenCalledWith(executionHealth, { mode: 'local', scheduler: null }); expect(invoke).toHaveBeenCalledWith(executionHealth, { mode: 'local', scheduler: null });
const mode: HTMLSelectElement = fixture.nativeElement.querySelector('select'); const trigger: HTMLElement = fixture.nativeElement.querySelector('.mat-mdc-select-trigger');
mode.value = 'remote'; trigger.click();
mode.dispatchEvent(new Event('change')); fixture.detectChanges();
const remote = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(option) => option.textContent?.trim() === 'Remoto',
);
remote!.click();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
fixture.detectChanges(); fixture.detectChanges();
+24 -14
View File
@@ -1,5 +1,9 @@
import { DOCUMENT } from '@angular/common'; import { DOCUMENT } from '@angular/common';
import { Component, computed, effect, inject, model, resource, signal } from '@angular/core'; import { Component, computed, effect, inject, model, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { executionHealth } from '../api/fn/execution/execution-health'; import { executionHealth } from '../api/fn/execution/execution-health';
import { executionOptions } from '../api/fn/execution/execution-options'; import { executionOptions } from '../api/fn/execution/execution-options';
@@ -8,28 +12,30 @@ import type { Health } from '../api/models/health';
@Component({ @Component({
selector: 'app-execution', selector: 'app-execution',
imports: [MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
template: ` template: `
<section class="card"> <section class="card" aria-labelledby="execution-heading">
<h2>Ejecución</h2> <h2 id="execution-heading">Ejecución</h2>
@if (options.hasValue()) { @if (options.hasValue()) {
<label <mat-form-field appearance="outline">
>Modo <mat-label>Modo</mat-label>
<select #mode [value]="choice().mode ?? ''" (change)="select($any(mode.value))"> <mat-select [value]="choice().mode ?? ''" (selectionChange)="select($event.value)">
<option value="sync">Sync</option> <mat-option value="sync">Sync</mat-option>
<option value="local">Local</option> <mat-option value="local">Local</mat-option>
<option value="remote">Remoto</option> <mat-option value="remote">Remoto</mat-option>
</select> </mat-select>
</label> </mat-form-field>
@if (choice().mode === 'remote') { @if (choice().mode === 'remote') {
<label <mat-form-field appearance="outline">
>Scheduler <mat-label>Scheduler</mat-label>
<input <input
matInput
#scheduler #scheduler
list="execution-schedulers" list="execution-schedulers"
[value]="choice().scheduler ?? ''" [value]="choice().scheduler ?? ''"
(change)="address.set(scheduler.value)" (change)="address.set(scheduler.value)"
/> />
</label> </mat-form-field>
<datalist id="execution-schedulers"> <datalist id="execution-schedulers">
@for (host of options.value().schedulers; track host) { @for (host of options.value().schedulers; track host) {
<option [value]="host"></option> <option [value]="host"></option>
@@ -52,7 +58,11 @@ import type { Health } from '../api/models/health';
} }
</p> </p>
@if (h.dashboard_url && h.dashboard_ok !== false) { @if (h.dashboard_url && h.dashboard_ok !== false) {
<a [href]="h.dashboard_url" target="_blank" rel="noopener">Panel de Dask</a> <div class="button-row">
<a mat-stroked-button [href]="h.dashboard_url" target="_blank" rel="noopener"
>Panel de Dask</a
>
</div>
} }
} @else if (health.error() || options.error()) { } @else if (health.error() || options.error()) {
<p role="alert">No se pudo consultar la ejecución.</p> <p role="alert">No se pudo consultar la ejecución.</p>
+30 -11
View File
@@ -10,20 +10,39 @@ interface Band {
high?: (number | null)[]; high?: (number | null)[];
} }
export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] { export function bandFill(
const lines: Partial<Plotly.Data>[] = []; x: number[],
if (b.low && b.high) { low: (number | null)[],
lines.push({ high: (number | null)[],
x: [...b.x, ...[...b.x].reverse()], colour: string,
y: [...b.high, ...[...b.low].reverse()] as number[], alpha: string,
): Partial<Plotly.Data> {
const rows = x.flatMap((age, i) =>
low[i] != null && high[i] != null
? [{ age, low: low[i] as number, high: high[i] as number }]
: [],
);
return {
type: 'scatter',
mode: 'lines',
x: [...rows.map((r) => r.age), ...rows.map((r) => r.age).reverse()],
y: [...rows.map((r) => r.high), ...rows.map((r) => r.low).reverse()],
fill: 'toself', fill: 'toself',
fillcolor: `${colour}33`, fillcolor: `${colour}${alpha}`,
line: { width: 0 }, line: { width: 0 },
hoverinfo: 'skip', hoverinfo: 'skip',
showlegend: false, showlegend: false,
type: 'scatter', };
});
} }
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(bandFill(b.x, b.low, b.high, colour, '33'));
lines.push({ lines.push({
x: b.x, x: b.x,
y: b.y, y: b.y,
@@ -38,7 +57,9 @@ export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Par
export interface Centile { export interface Centile {
age_months: number; age_months: number;
p5: number | null; p5: number | null;
p25?: number | null;
median: number | null; median: number | null;
p75?: number | null;
p95: number | null; p95: number | null;
} }
@@ -302,7 +323,6 @@ export function interpretabilityFigures(
]; ];
} }
case 'associations': { case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[]) const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null) .filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1)); .sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
@@ -396,7 +416,6 @@ export function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB), points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
], ],
layout: { layout: {
// One label per month with every curve's survival there, as percentages.
hovermode: 'x unified', hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' }, xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' }, yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
+29 -291
View File
@@ -1,305 +1,43 @@
<section class="page"> <section class="page">
<h1>Gobernanza de modelos</h1> <h1>Gobernanza de modelos</h1>
<nav class="domains" aria-label="Dominios"> <p class="subtitle">Administra la ejecución, las versiones y el entrenamiento por dominio.</p>
<nav class="domains button-row" aria-label="Dominios">
@for (d of domains.hasValue() ? domains.value() : []; track d) { @for (d of domains.hasValue() ? domains.value() : []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a> <a mat-stroked-button [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">
{{ labels[d] ?? d }}
</a>
} }
</nav> </nav>
<app-execution [(execution)]="execution" /> <div class="sections">
<app-execution #execution />
<section> <app-governance-models
<h2>Modelos</h2> #models
<div class="card actions">
<button mat-flat-button type="button" (click)="training.set('all')">Entrenar modelos</button>
<button
mat-stroked-button
type="button"
[disabled]="starting() || running()"
(click)="start('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<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()" [domain]="domainKey()"
[name]="name" (trainingRequested)="training.focus()"
[execution]="execution()" (analysisRequested)="studies()?.focus()"
[(busy)]="starting" />
[disabled]="running() || !execution()" <app-governance-training
(started)="follow($event.id, 'Entrenamiento', $event.autoPromote)" #training
[domain]="domainKey()"
[name]="models.training()"
[execution]="execution.execution()"
[(busy)]="models.starting"
[disabled]="models.running() || !execution.execution()"
(started)="models.follow($event.id, 'Entrenamiento', $event.autoPromote)"
/> />
}
<app-governance-bundles <app-governance-bundles
[domain]="domainKey()" [domain]="domainKey()"
[(importing)]="starting" [(importing)]="models.starting"
[disabled]="running()" [disabled]="models.running()"
(started)="follow($event, 'Importación')" (started)="models.follow($event, 'Importación')"
/> />
@if (run(); as current) {
<section class="card">
<h3>{{ current.label }}</h3>
<app-run-monitor [runId]="current.id" (finished)="finish($event)" />
</section>
}
@if (message()) {
<p class="message" role="status">{{ message() }}</p>
}
@if (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>
<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)="chooseReport({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
} @else {
Agregada
}
</td>
<td>
<button
mat-stroked-button
type="button"
(click)="
showVersion('checks', { name: m.name, version: v.version }, checksDialog)
"
>
Comprobaciones
</button>
<button
mat-stroked-button
type="button"
(click)="
showVersion('lineage', { name: m.name, version: v.version }, lineageDialog)
"
>
Linaje
</button>
</td>
</tr>
}
</tbody>
</table>
</section>
}
@if (chosen(); as version) {
<section class="card">
<h3>Interpretabilidad · {{ version.name }} v{{ version.version }}</h3>
@if (feature(); as current) {
@if (ageFeatures().length > 1) {
<label
>Característica
<select [ngModel]="current" (ngModelChange)="selectedFeature.set($event)">
@for (feature of ageFeatures(); track feature) {
<option [value]="feature">{{ feature }}</option>
}
</select>
</label>
}
<label><input type="checkbox" [(ngModel)]="overlay" /> Superponer estudios</label>
}
@if (report.error() || band.error() || analysed.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@for (f of figures(); track f.title) {
<h4>{{ f.title }}</h4>
<app-plot
[figure]="f.figure"
[height]="
report.hasValue() && report.value()['kind'] === 'forest'
? forestHeight(f.figure.data.length)
: 360
"
/>
} @empty {
@if (report.isLoading() || band.isLoading()) {
<p class="muted">Cargando…</p>
} @else if (!report.error() && !band.error()) {
<p class="muted">Este informe no tiene gráficas.</p>
}
}
</section>
}
</section>
@if (domain() === 'tea') { @if (domain() === 'tea') {
<app-eeg-studies [execution]="execution()" [refresh]="refreshed()" (changed)="refresh()" /> <app-eeg-studies
[execution]="execution.execution()"
[refresh]="models.refreshed()"
(changed)="models.refresh()"
/>
} }
</div>
<dialog #checksDialog aria-label="Comprobaciones" (close)="checksFor.set(undefined)">
@if (checksFor(); as key) {
<h3>Comprobaciones · {{ key.name }} v{{ key.version }}</h3>
@if (checks.hasValue()) {
@let details = checks.value();
@let actions = checkActions(details);
<ul>
@for (check of details.checks; track check.report) {
<li>
{{ reportNames[check.report] ?? check.report }} ·
{{ check.present ? 'Presente' : 'Falta' }}
</li>
}
</ul>
<button
mat-stroked-button
type="button"
[disabled]="editing() || !actions.promote"
(click)="changeVersion(key, 'promote')"
>
Promover
</button>
<button
mat-stroked-button
type="button"
[disabled]="editing() || !actions.retire"
(click)="changeVersion(key, 'retire')"
>
Retirar
</button>
} @else if (checks.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else {
<p>Cargando…</p>
}
@if (message()) {
<p role="status">{{ message() }}</p>
}
}
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
</dialog>
<dialog #lineageDialog aria-label="Linaje" (close)="lineageFor.set(undefined)">
@if (lineageFor(); as key) {
<h3>Linaje · {{ key.name }} v{{ key.version }}</h3>
@if (lineage.hasValue()) {
@let details = lineage.value();
<h4>Parámetros</h4>
<dl>
@for (entry of details.params | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
<h4>Métricas</h4>
<dl>
@for (entry of details.metrics | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
<h4>Etiquetas</h4>
<dl>
@for (entry of details.tags | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
@if (details.imported; as imported) {
<h4>Importado de</h4>
<dl>
@for (entry of imported | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
}
} @else if (lineage.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else {
<p>Cargando…</p>
}
}
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
</dialog>
<dialog #bulkDialog aria-label="Promover candidatas">
<h3>Promover candidatas</h3>
<ul>
@for (candidate of candidates(); track candidate.name) {
<li>{{ candidate.name }} v{{ candidate.version }}</li>
}
</ul>
<button
mat-flat-button
type="button"
[disabled]="editing()"
(click)="promoteCandidates(bulkDialog)"
>
Promover
</button>
<form method="dialog"><button mat-stroked-button>Cancelar</button></form>
</dialog>
</section> </section>
+5 -44
View File
@@ -1,56 +1,17 @@
:host { :host {
display: block; display: block;
} }
h1 {
text-align: center;
}
.domains { .domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4); margin-bottom: var(--space-4);
} }
.domains a.active { .domains a.active {
font-weight: 600; font-weight: 600;
text-decoration: underline; text-decoration: underline;
} }
.actions { .sections {
display: flex; display: grid;
flex-wrap: wrap; gap: var(--space-4);
align-items: center;
gap: var(--space-3);
margin-bottom: var(--space-4);
} }
.model { .sections > * {
margin-bottom: var(--space-4); min-width: 0;
overflow-x: auto;
}
.num {
text-align: right;
white-space: nowrap;
}
.badge {
margin-left: var(--space-2);
padding: 2px 8px;
border-radius: 999px;
background: var(--color-primary);
color: #fff;
font-size: 12px;
}
td a {
margin-right: var(--space-3);
color: var(--color-action);
}
.empty {
padding: 48px 0;
text-align: center;
}
.message {
white-space: pre-line;
}
dialog {
max-width: min(90vw, 64rem);
}
dialog form {
margin-top: var(--space-3);
} }
+5 -381
View File
@@ -1,80 +1,19 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common'; import { Component, computed, inject, input, resource, viewChild } from '@angular/core';
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
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 { domains } from '../api/fn/operations/domains';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import type { Execution as Choice } from '../api/models/execution';
import type { Run } from '../api/models/run';
import { DOMAINS } from '../app'; import { DOMAINS } from '../app';
import { Plot } from '../plot'; import { Bundles } from './bundles';
import { Bundles, download } from './bundles';
import { Execution } from './execution'; import { Execution } from './execution';
import { interpretabilityFigures, studyPoints, type Centile } from './figures'; import { Models } from './models';
import { errorText, RunMonitor } from './run-monitor';
import { EegStudies } from './tea/studies'; import { EegStudies } from './tea/studies';
import { Training } from './training'; import { Training } from './training';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
interpretability: 'Interpretabilidad',
clinical_validation: 'Validación clínica',
};
interface VersionKey {
name: string;
version: number;
}
interface Checks {
status: 'candidate' | 'champion' | 'retired';
promotable: boolean;
checks: { report: string; present: boolean }[];
}
interface Lineage {
params: Record<string, string>;
metrics: Record<string, number>;
tags: Record<string, string>;
imported: Record<string, string> | null;
}
export function checkActions(checks: Checks) {
return { promote: checks.promotable, retire: checks.status !== 'champion' };
}
@Component({ @Component({
selector: 'app-gobernanza', selector: 'app-gobernanza',
imports: [ imports: [MatButtonModule, RouterLink, Execution, Models, Training, Bundles, EegStudies],
DatePipe,
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
RouterLink,
Plot,
Bundles,
Execution,
RunMonitor,
EegStudies,
Training,
],
templateUrl: './gobernanza.html', templateUrl: './gobernanza.html',
styleUrl: './gobernanza.scss', styleUrl: './gobernanza.scss',
}) })
@@ -82,322 +21,7 @@ export class Gobernanza {
private readonly api = inject(Api); private readonly api = inject(Api);
readonly domain = input.required<string>(); readonly domain = input.required<string>();
protected readonly domainKey = computed(() => this.domain() as Domain); protected readonly domainKey = computed(() => this.domain() as Domain);
protected readonly execution = signal<Choice | undefined>(undefined);
protected readonly labels = DOMAINS as Record<string, string>; protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS;
protected readonly errorText = errorText;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
protected readonly refreshed = signal(0); protected readonly studies = viewChild(EegStudies);
protected refresh(): void {
this.refreshed.update((value) => value + 1);
}
protected readonly models = resource({
params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
loader: async ({ params: { domain } }) => {
const found = await this.api.invoke(models, { domain });
return Promise.all(
found.map(async ({ name, title }) => ({
name,
title,
versions: await this.api.invoke(versions, { domain, name }),
})),
);
},
});
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: () => {
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(() => {
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',
});
});
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 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 input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
const domain = this.domainKey();
try {
await this.api.invoke(addClinicalValidation, {
domain,
name,
version,
body: { file: file as unknown as string },
});
input.value = '';
if (domain !== this.domainKey()) return;
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
this.refresh();
} catch (error) {
this.message.set(errorText(error));
}
}
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(
`${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 prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
if (!this.models.hasValue()) return;
const domain = this.domainKey();
this.editing.set(true);
this.message.set('');
try {
const latest = this.models.value().flatMap(({ name, versions }) => {
const newest = versions.reduce<(typeof versions)[number] | undefined>(
(current, version) => (!current || version.version > current.version ? version : current),
undefined,
);
return newest?.status === 'candidate' ? [{ name, version: newest.version }] : [];
});
const allowed = await Promise.all(
latest.map(async (key) => (await this.getChecks(domain, key)).promotable),
);
if (domain !== this.domainKey()) return;
const found = latest.filter((_, index) => allowed[index]);
this.candidates.set(found);
if (found.length) dialog.showModal();
else this.message.set('No hay candidatas que se puedan promover.');
} catch (error) {
this.message.set(errorText(error));
} finally {
this.editing.set(false);
}
}
protected async 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 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();
}
} }
+287
View File
@@ -0,0 +1,287 @@
<section class="card" aria-labelledby="models-heading">
<h2 id="models-heading">Modelos</h2>
<div class="button-row">
<button mat-flat-button type="button" (click)="selectTraining('all')">Entrenar modelos</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" (click)="analysisRequested.emit()">
Analizar EEG
</button>
} @else {
<button
mat-stroked-button
type="button"
[disabled]="starting() || running()"
(click)="scoreRisks()"
>
Calcular riesgos
</button>
}
<button
mat-stroked-button
type="button"
[disabled]="editing() || !models.hasValue()"
(click)="prepareCandidates(bulkDialog)"
>
Promover candidatas
</button>
</div>
@if (run(); as current) {
<section>
<h3>{{ current.label }}</h3>
<app-run-monitor [runId]="current.id" (finished)="finish($event)" />
</section>
}
@if (message()) {
<p class="message" role="status">{{ message() }}</p>
}
@if (models.isLoading()) {
<p class="muted">Cargando modelos…</p>
} @else if (models.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else if (!models.hasValue() || !models.value().length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
}
@for (m of models.hasValue() ? models.value() : []; track m.name) {
<section class="model">
<h3>{{ m.title }}</h3>
<div class="button-row">
<button mat-stroked-button type="button" (click)="selectTraining(m.name)">
Reentrenar
</button>
</div>
<table class="plain">
<thead>
<tr>
<th>Versión</th>
<th>Creada</th>
<th>Entrenamiento / prueba</th>
<th>Informes</th>
<th>Validación clínica</th>
<th>Comprobaciones y linaje</th>
</tr>
</thead>
<tbody>
@for (v of m.versions; track v.version) {
<tr>
<td>
v{{ v.version }} <span class="badge">{{ v.status }}</span>
</td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num">
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td>
<div class="button-row">
@for (report of v.reports; track report) {
<button
mat-stroked-button
type="button"
(click)="reportDownload(m.name, v.version, report)"
>
{{ reportNames[report] ?? report }}
</button>
}
@if (v.reports.includes('interpretability')) {
<button
mat-stroked-button
type="button"
(click)="chooseReport({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</div>
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
#validation
type="file"
hidden
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
<button mat-stroked-button type="button" (click)="validation.click()">
Validación clínica
</button>
} @else {
Agregada
}
</td>
<td>
<div class="button-row">
<button
mat-stroked-button
type="button"
(click)="
showVersion('checks', { name: m.name, version: v.version }, checksDialog)
"
>
Comprobaciones
</button>
<button
mat-stroked-button
type="button"
(click)="
showVersion('lineage', { name: m.name, version: v.version }, lineageDialog)
"
>
Linaje
</button>
</div>
</td>
</tr>
}
</tbody>
</table>
</section>
}
@if (chosen(); as version) {
<section>
<h3>Interpretabilidad · {{ version.name }} v{{ version.version }}</h3>
@if (feature(); as current) {
@if (ageFeatures().length > 1) {
<mat-form-field appearance="outline">
<mat-label>Característica</mat-label>
<mat-select [ngModel]="current" (ngModelChange)="selectedFeature.set($event)">
@for (feature of ageFeatures(); track feature) {
<mat-option [value]="feature">{{ feature }}</mat-option>
}
</mat-select>
</mat-form-field>
}
<mat-checkbox [(ngModel)]="overlay">Superponer estudios</mat-checkbox>
}
@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>
}
<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>
<div class="button-row">
<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>
</div>
} @else if (checks.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else {
<p>Cargando…</p>
}
@if (message()) {
<p role="status">{{ message() }}</p>
}
}
<form class="button-row" 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 class="button-row" 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>
<div class="button-row">
<button
mat-flat-button
type="button"
[disabled]="editing()"
(click)="promoteCandidates(bulkDialog)"
>
Promover
</button>
<form method="dialog"><button mat-stroked-button>Cancelar</button></form>
</div>
</dialog>
</section>
+26
View File
@@ -0,0 +1,26 @@
.model {
margin-bottom: var(--space-4);
overflow-x: auto;
}
.num {
text-align: right;
white-space: nowrap;
}
.badge {
margin-left: var(--space-2);
padding: 2px 8px;
border-radius: 999px;
background: var(--color-primary);
color: #fff;
font-size: 12px;
}
.empty {
padding: 48px 0;
text-align: center;
}
.message {
white-space: pre-line;
}
dialog {
max-width: min(90vw, 64rem);
}
@@ -1,4 +1,4 @@
import { checkActions } from './gobernanza'; import { checkActions } from './models';
describe('version checks', () => { describe('version checks', () => {
it('enables promotion only when the API says the version is promotable', () => { it('enables promotion only when the API says the version is promotable', () => {
+404
View File
@@ -0,0 +1,404 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import {
Component,
computed,
effect,
inject,
input,
output,
resource,
signal,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { Api } from '../api/api';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
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 type { Domain } from '../api/models/domain';
import type { Run } from '../api/models/run';
import { Plot } from '../plot';
import { download } from '../export';
import { interpretabilityFigures, studyPoints, type Centile } from './figures';
import { errorText, RunMonitor } from './run-monitor';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
interpretability: 'Interpretabilidad',
clinical_validation: 'Validación clínica',
};
interface VersionKey {
name: string;
version: number;
}
interface Checks {
status: 'candidate' | 'champion' | 'retired';
promotable: boolean;
checks: { report: string; present: boolean }[];
}
interface Lineage {
params: Record<string, string>;
metrics: Record<string, number>;
tags: Record<string, string>;
imported: Record<string, string> | null;
}
export function checkActions(checks: Checks) {
return { promote: checks.promotable, retire: checks.status !== 'champion' };
}
@Component({
selector: 'app-governance-models',
imports: [
DatePipe,
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatSelectModule,
Plot,
RunMonitor,
],
templateUrl: './models.html',
styleUrl: './models.scss',
})
export class Models {
private readonly api = inject(Api);
readonly domain = input.required<Domain>();
readonly trainingRequested = output<void>();
readonly analysisRequested = output<void>();
protected readonly reportNames = REPORTS;
protected readonly errorText = errorText;
readonly refreshed = signal(0);
refresh(): void {
this.refreshed.update((value) => value + 1);
}
protected readonly models = resource({
params: () => ({ domain: this.domain(), at: this.refreshed() }),
loader: async ({ params: { domain } }) => {
const found = await this.api.invoke(models, { domain });
return Promise.all(
found.map(async ({ name, title }) => ({
name,
title,
versions: await this.api.invoke(versions, { domain, name }),
})),
);
},
});
readonly training = signal('all');
protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>(
undefined,
);
readonly starting = signal(false);
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.domain(), 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.domain() } : undefined;
},
loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage,
});
protected readonly candidates = signal<VersionKey[]>([]);
protected readonly report = resource({
params: () => {
const key = this.chosen();
return key ? { ...key, domain: this.domain() } : 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.domain(), 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.domain() === 'tea' && this.feature()
? this.refreshed() + 1
: undefined,
loader: async () => {
const found = await this.api.invoke(studies);
return Promise.all(
found
.filter((entry) => entry.analysed)
.map(({ id }) => this.api.invoke(study, { eeg_id: id })),
);
},
});
protected readonly figures = computed(() => {
if (!this.report.hasValue()) return [];
const report = this.report.value();
const feature = this.feature();
const points =
this.analysed.hasValue() && feature
? studyPoints(this.analysed.value(), report['model'], feature)
: [];
return interpretabilityFigures(report, {
feature,
centiles: this.band.hasValue() ? this.band.value() : undefined,
points,
waitForCentiles: report['kind'] === 'age_curves',
});
});
constructor() {
effect(() => {
this.domain();
this.training.set('all');
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 selectTraining(name: string): void {
this.training.set(name);
this.trainingRequested.emit();
}
protected async reportDownload(name: string, version: number, report: string): Promise<void> {
try {
const response = await this.api.invoke$Response(readReport$Any, {
domain: this.domain(),
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 input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
const domain = this.domain();
try {
await this.api.invoke(addClinicalValidation, {
domain,
name,
version,
body: { file: file as unknown as string },
});
input.value = '';
if (domain !== this.domain()) 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.domain();
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(
`${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 prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
if (!this.models.hasValue()) return;
const domain = this.domain();
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.domain()) return;
const found = latest.filter((_, index) => allowed[index]);
this.candidates.set(found);
if (found.length) dialog.showModal();
else this.message.set('No hay candidatas que se puedan promover.');
} catch (error) {
this.message.set(errorText(error));
} finally {
this.editing.set(false);
}
}
protected async promoteCandidates(dialog: HTMLDialogElement): Promise<void> {
this.editing.set(true);
this.message.set('');
try {
await this.promoteVersions(this.domain(), this.candidates());
dialog.close();
} finally {
this.editing.set(false);
}
}
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);
}
follow(id: string, label: string, autoPromote = false): void {
this.message.set('');
this.run.set({ id, label, autoPromote });
this.running.set(true);
}
protected async scoreRisks(): Promise<void> {
const domain = this.domain();
this.starting.set(true);
this.message.set('');
try {
const { run_id } = await this.api.invoke(score, { domain });
if (domain === this.domain()) this.follow(run_id, 'Cálculo de riesgos');
} catch (error) {
this.message.set(errorText(error));
} finally {
this.starting.set(false);
}
}
protected async finish(run: Run): Promise<void> {
const domain = this.domain();
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.domain() && 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.domain()) return;
this.message.set(messages.join('\n'));
this.refresh();
}
}
+2
View File
@@ -77,6 +77,7 @@ export function eta(progress: Progress): number | null {
<p role="alert">{{ r.error }}</p> <p role="alert">{{ r.error }}</p>
} }
@if (!terminal.has(r.state)) { @if (!terminal.has(r.state)) {
<div class="button-row">
<button <button
mat-stroked-button mat-stroked-button
type="button" type="button"
@@ -85,6 +86,7 @@ export function eta(progress: Progress): number | null {
> >
Cancelar Cancelar
</button> </button>
</div>
} }
} @else { } @else {
<p role="status">Consultando ejecución…</p> <p role="status">Consultando ejecución…</p>
+1 -2
View File
@@ -1,5 +1,4 @@
import { downloadPdf, type PdfContent } from '../../export/pdf'; import { downloadPdf, safeName, type PdfContent } from '../../export';
import { safeName } from '../../export/safe-name';
import type { PreviewResult } from '../../api/models/preview-result'; import type { PreviewResult } from '../../api/models/preview-result';
import type { Score } from '../../api/models/score'; import type { Score } from '../../api/models/score';
+53 -14
View File
@@ -1,7 +1,9 @@
import { KeyValuePipe } from '@angular/common'; import { KeyValuePipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core'; import { Component, inject, input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { Api } from '../../api/api'; import { Api } from '../../api/api';
import { previewStatus } from '../../api/fn/preview/preview-status'; import { previewStatus } from '../../api/fn/preview/preview-status';
import { startPreview } from '../../api/fn/preview/start-preview'; import { startPreview } from '../../api/fn/preview/start-preview';
@@ -12,15 +14,52 @@ import { downloadPreviewPdf } from './preview-pdf';
@Component({ @Component({
selector: 'app-eeg-preview', selector: 'app-eeg-preview',
imports: [FormsModule, KeyValuePipe, MatButtonModule, RunMonitor], imports: [
FormsModule,
KeyValuePipe,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
RunMonitor,
],
template: ` template: `
<section> <form
<h3>Vista previa</h3> class="button-row"
<form (ngSubmit)="start(edf.files?.[0], ados.files?.[0], birth.value)"> [hidden]="!active()"
<label>EDF <input #edf type="file" accept=".edf" required /></label> (ngSubmit)="start(edf.files?.[0], ados.files?.[0], birth.value)"
<label>ADOS-2 (PDF) <input #ados type="file" accept=".pdf" /></label> >
<label>Fecha de nacimiento <input #birth type="date" /></label> <input
<button mat-stroked-button type="submit" [disabled]="busy()">Vista previa</button> #edf
type="file"
accept=".edf"
required
hidden
aria-label="EDF"
(change)="edfFiles.set(edf.files)"
/>
<button mat-stroked-button type="button" (click)="edf.click()">EDF</button>
@for (file of edfFiles(); track $index) {
<span>{{ file.name }}</span>
}
<input
#ados
type="file"
accept=".pdf"
hidden
aria-label="ADOS-2 (PDF)"
(change)="adosFiles.set(ados.files)"
/>
<button mat-stroked-button type="button" (click)="ados.click()">ADOS-2 (PDF)</button>
@for (file of adosFiles(); track $index) {
<span>{{ file.name }}</span>
}
<mat-form-field appearance="outline">
<mat-label>Fecha de nacimiento</mat-label>
<input matInput #birth type="date" />
</mat-form-field>
<button mat-stroked-button type="submit" [disabled]="busy() || !edfFiles()?.length">
Vista previa
</button>
</form> </form>
@if (error()) { @if (error()) {
<p role="alert">{{ error() }}</p> <p role="alert">{{ error() }}</p>
@@ -57,9 +96,7 @@ import { downloadPreviewPdf } from './preview-pdf';
<td>{{ check['value'] ?? check['text'] ?? '—' }} {{ check['unit'] }}</td> <td>{{ check['value'] ?? check['text'] ?? '—' }} {{ check['unit'] }}</td>
<td>{{ check['low'] ?? '—' }} / {{ check['high'] ?? '—' }}</td> <td>{{ check['low'] ?? '—' }} / {{ check['high'] ?? '—' }}</td>
<td> <td>
{{ {{ check['abnormal'] === true ? 'Sí' : check['abnormal'] === false ? 'No' : '—' }}
check['abnormal'] === true ? 'Sí' : check['abnormal'] === false ? 'No' : '—'
}}
</td> </td>
</tr> </tr>
} }
@@ -137,7 +174,7 @@ import { downloadPreviewPdf } from './preview-pdf';
@if (pdfError()) { @if (pdfError()) {
<p role="alert">{{ pdfError() }}</p> <p role="alert">{{ pdfError() }}</p>
} }
<form method="dialog"> <form class="button-row" method="dialog">
@if (result(); as r) { @if (result(); as r) {
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="pdf(r)"> <button mat-stroked-button type="button" [disabled]="exporting()" (click)="pdf(r)">
Guardar como PDF Guardar como PDF
@@ -146,11 +183,13 @@ import { downloadPreviewPdf } from './preview-pdf';
<button mat-stroked-button>Cerrar</button> <button mat-stroked-button>Cerrar</button>
</form> </form>
</dialog> </dialog>
</section>
`, `,
}) })
export class EegPreview { export class EegPreview {
readonly active = input.required<boolean>();
private readonly api = inject(Api); private readonly api = inject(Api);
protected readonly edfFiles = signal<FileList | null>(null);
protected readonly adosFiles = signal<FileList | null>(null);
protected readonly busy = signal(false); protected readonly busy = signal(false);
protected readonly error = signal(''); protected readonly error = signal('');
protected readonly runId = signal(''); protected readonly runId = signal('');
+34 -23
View File
@@ -1,37 +1,43 @@
<section class="card model"> <section class="card" aria-labelledby="studies-heading">
<h2>Estudios EEG</h2> <h2 #heading id="studies-heading" tabindex="-1">Estudios EEG</h2>
<form (ngSubmit)="analyze()"> <form class="button-row" (ngSubmit)="analyze()">
<label <mat-form-field appearance="outline">
>Alcance <mat-label>Alcance</mat-label>
<select name="scope" [(ngModel)]="mode"> <mat-select name="scope" [(ngModel)]="mode">
<option value="pending">Pendientes</option> <mat-option value="pending">Pendientes</mat-option>
<option value="first_n">Primeros N</option> <mat-option value="first_n">Primeros N</mat-option>
<option value="ids">Por ID</option> <mat-option value="ids">Por ID</mat-option>
</select> </mat-select>
</label> </mat-form-field>
@if (mode() === 'first_n') { @if (mode() === 'first_n') {
<label <mat-form-field appearance="outline">
>Número de estudios <input type="number" name="count" min="1" required [(ngModel)]="count" <mat-label>Número de estudios</mat-label>
/></label> <input matInput type="number" name="count" min="1" required [(ngModel)]="count" />
</mat-form-field>
} }
@if (mode() === 'ids') { @if (mode() === 'ids') {
<label <mat-form-field appearance="outline">
>ID de estudios (uno por línea) <textarea name="ids" required [(ngModel)]="ids"></textarea> <mat-label>ID de estudios (uno por línea)</mat-label>
</label> <textarea matInput name="ids" required [(ngModel)]="ids"></textarea>
</mat-form-field>
} }
<button mat-flat-button type="submit" [disabled]="busy() || !execution()">Analizar</button> <button mat-flat-button type="submit" [disabled]="busy() || !execution()">Analizar</button>
<button
mat-stroked-button
type="button"
[attr.aria-pressed]="showPreview()"
(click)="showPreview.set(!showPreview())"
>
Evaluar un solo estudio
</button>
</form> </form>
<form (ngSubmit)="upload(files)"> <app-eeg-preview [active]="showPreview()" />
<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()) { @if (error()) {
<p role="alert">{{ error() }}</p> <p role="alert">{{ error() }}</p>
} }
@if (runId(); as id) { @if (runId(); as id) {
<app-run-monitor [runId]="id" (finished)="finish()" /> <app-run-monitor [runId]="id" (finished)="finish()" />
} }
<app-eeg-preview />
<h3>Resumen</h3> <h3>Resumen</h3>
@if (summary.hasValue()) { @if (summary.hasValue()) {
<dl> <dl>
@@ -81,7 +87,12 @@
@for (e of eegs.hasValue() ? eegs.value() : []; track e.id) { @for (e of eegs.hasValue() ? eegs.value() : []; track e.id) {
<tr> <tr>
<td> <td>
<button mat-button type="button" [disabled]="!e.analysed" (click)="eeg.set(e.id)"> <button
mat-stroked-button
type="button"
[disabled]="!e.analysed"
(click)="eeg.set(e.id)"
>
{{ e.study_date }} {{ e.study_date }}
</button> </button>
</td> </td>
+29
View File
@@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { Api } from '../../api/api';
import { EegStudies } from './studies';
describe('single study evaluation', () => {
it('toggles the preview form below the Estudios EEG button row', async () => {
TestBed.overrideProvider(Api, { useValue: { invoke: vi.fn().mockResolvedValue([]) } });
const fixture = TestBed.createComponent(EegStudies);
fixture.detectChanges();
await fixture.whenStable();
const host: HTMLElement = fixture.nativeElement;
const toggle = host.querySelector<HTMLButtonElement>('button[aria-pressed]')!;
const form = host.querySelector<HTMLFormElement>('form.button-row + app-eeg-preview > form')!;
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(form.hidden).toBe(true);
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-pressed')).toBe('true');
expect(form.hidden).toBe(false);
expect(form.querySelectorAll('input')).toHaveLength(3);
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(form.hidden).toBe(true);
});
});
+29 -38
View File
@@ -1,16 +1,24 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common'; import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http'; import {
import { Component, inject, input, output, resource, signal } from '@angular/core'; Component,
ElementRef,
inject,
input,
output,
resource,
signal,
viewChild,
} from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { Api } from '../../api/api'; import { Api } from '../../api/api';
import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs'; import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs';
import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary'; import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary';
import { studies } from '../../api/fn/eeg/studies'; import { studies } from '../../api/fn/eeg/studies';
import { study } from '../../api/fn/eeg/study'; import { study } from '../../api/fn/eeg/study';
import { 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 { runHistory } from '../../api/fn/runs/run-history';
import type { Execution } from '../../api/models/execution'; import type { Execution } from '../../api/models/execution';
import type { Scope } from '../../api/models/scope'; import type { Scope } from '../../api/models/scope';
@@ -25,6 +33,9 @@ import { EegPreview } from './preview';
KeyValuePipe, KeyValuePipe,
FormsModule, FormsModule,
MatButtonModule, MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
RunMonitor, RunMonitor,
EegPreview, EegPreview,
], ],
@@ -32,9 +43,16 @@ import { EegPreview } from './preview';
}) })
export class EegStudies { export class EegStudies {
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly heading = viewChild.required<ElementRef<HTMLHeadingElement>>('heading');
protected readonly showPreview = signal(false);
readonly execution = input<Execution>(); readonly execution = input<Execution>();
readonly refresh = input(0); readonly refresh = input(0);
readonly changed = output<void>(); readonly changed = output<void>();
focus(): void {
this.heading().nativeElement.focus();
}
protected readonly eegs = resource({ protected readonly eegs = resource({
params: () => this.refresh(), params: () => this.refresh(),
loader: () => this.api.invoke(studies), loader: () => this.api.invoke(studies),
@@ -113,46 +131,19 @@ export class EegStudies {
scope.ids = this.ids().split(/\s+/).filter(Boolean); scope.ids = this.ids().split(/\s+/).filter(Boolean);
if (!scope.ids.length) return; 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.busy.set(true);
this.error.set(''); this.error.set('');
try { try {
const { run_id } = await submit(); const { run_id } = await this.api.invoke(analyzeEegs, { body: { scope, execution } });
this.runId.set(run_id); this.runId.set(run_id);
} catch (error) { } catch (error) {
this.error.set(errorText(error)); this.error.set(errorText(error));
this.busy.set(false); this.busy.set(false);
} }
} }
protected finish(): void {
this.busy.set(false);
this.changed.emit();
}
} }
+48 -11
View File
@@ -1,24 +1,41 @@
import { trainingForm } from './training'; import { sourcePayload, trainingForm } from './training';
describe('training form', () => { describe('training form', () => {
it('removes execution and resolves the TEA reference fields with their defaults', () => { it('flattens the source union into one selector whose variants own their fields', () => {
const { schema, model } = trainingForm({ const { schema, model, variants } = trainingForm({
name: 'all', name: 'all',
domain: 'tea', domain: 'tea',
defaults: { execution: { mode: 'local', scheduler: null }, reference: { line_hz: 50 } }, defaults: {
execution: { mode: 'local', scheduler: null },
source: { kind: 'site' },
},
json_schema: { json_schema: {
type: 'object', type: 'object',
properties: { properties: {
execution: { type: 'object' }, execution: { type: 'object' },
as_of: { anyOf: [{ type: 'string', format: 'date' }, { type: 'null' }] }, as_of: { anyOf: [{ type: 'string', format: 'date' }, { type: 'null' }] },
reference: { anyOf: [{ $ref: '#/$defs/Reference' }, { type: 'null' }] }, source: { anyOf: [{ $ref: '#/$defs/TrainingSource' }, { type: 'null' }] },
}, },
$defs: { $defs: {
Reference: { TrainingSource: {
discriminator: { propertyName: 'kind' },
oneOf: [
{ $ref: '#/$defs/SiteTrainingSource' },
{ $ref: '#/$defs/FolderTrainingSource' },
],
},
SiteTrainingSource: {
type: 'object', type: 'object',
required: ['name'], title: 'Sitio',
properties: { kind: { type: 'string', const: 'site', title: 'Origen' } },
},
FolderTrainingSource: {
type: 'object',
title: 'Carpeta',
required: ['kind', 'folder'],
properties: { properties: {
name: { type: 'string' }, kind: { type: 'string', const: 'folder', title: 'Origen' },
folder: { type: 'string' },
line_hz: { type: 'integer', enum: [50, 60], default: 50 }, line_hz: { type: 'integer', enum: [50, 60], default: 50 },
}, },
}, },
@@ -31,10 +48,30 @@ describe('training form', () => {
type: ['string', 'null'], type: ['string', 'null'],
format: 'date', format: 'date',
}); });
expect(schema.properties?.['reference']).toMatchObject({ expect(schema.properties?.['source']).toMatchObject({
type: ['object', 'null'], type: ['object', 'null'],
properties: { name: { type: 'string' }, line_hz: { enum: [50, 60] } }, required: ['kind', 'folder'],
properties: {
kind: {
title: 'Origen',
oneOf: [
{ const: 'site', title: 'Sitio' },
{ const: 'folder', title: 'Carpeta' },
],
},
folder: { type: 'string' },
line_hz: { enum: [50, 60] },
},
});
expect(model).toEqual({ source: { kind: 'site' } });
expect(variants.owners).toEqual({ folder: ['folder'], line_hz: ['folder'] });
expect(sourcePayload({ kind: 'site', folder: 'x', line_hz: 50 }, variants)).toEqual({
kind: 'site',
});
expect(sourcePayload({ kind: 'folder', folder: 'x', line_hz: 60 }, variants)).toEqual({
kind: 'folder',
folder: 'x',
line_hz: 60,
}); });
expect(model).toEqual({ reference: { line_hz: 50 } });
}); });
}); });
+92 -116
View File
@@ -1,7 +1,18 @@
import { HttpErrorResponse } from '@angular/common/http'; import {
import { Component, inject, input, model, output, resource, signal } from '@angular/core'; Component,
ElementRef,
inject,
input,
linkedSignal,
model,
output,
resource,
signal,
viewChild,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { FormlyForm, provideFormlyCore } from '@ngx-formly/core'; import { FormlyForm, provideFormlyCore } from '@ngx-formly/core';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema'; import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material'; import { withFormlyMaterial } from '@ngx-formly/material';
@@ -9,20 +20,21 @@ import type { JSONSchema7, JSONSchema7TypeName } from 'json-schema';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { train } from '../api/fn/models/train'; import { train } from '../api/fn/models/train';
import { trainingConfig } from '../api/fn/models/training-config'; 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 { Domain } from '../api/models/domain';
import type { Execution } from '../api/models/execution'; import type { Execution } from '../api/models/execution';
import type { TrainingConfig } from '../api/models/training-config'; import type { TrainingConfig } from '../api/models/training-config';
import type { TrainingSource } from '../api/models/training-source';
import { FORMLY_TYPES } from '../conectar/schema-form'; import { FORMLY_TYPES } from '../conectar/schema-form';
import { errorText } from './run-monitor'; import { errorText } from './run-monitor';
type Schema = JSONSchema7 & { $defs?: Record<string, Schema> }; type Schema = Omit<JSONSchema7, '$defs'> & {
$defs?: Record<string, Schema>;
discriminator?: { propertyName: string };
};
interface InputSets { export interface Variants {
allowed: string[]; discriminator: string;
description: string; owners: Record<string, string[]>;
sets: { name: string; edf_files: number; has_ages: boolean }[];
} }
export function trainingForm(config: TrainingConfig) { export function trainingForm(config: TrainingConfig) {
@@ -31,8 +43,9 @@ export function trainingForm(config: TrainingConfig) {
delete model['execution']; delete model['execution'];
delete raw.properties?.['execution']; delete raw.properties?.['execution'];
raw.required = raw.required?.filter((key) => key !== 'execution'); raw.required = raw.required?.filter((key) => key !== 'execution');
const variants: Variants = { discriminator: '', owners: {} };
const normalize = (schema: Schema): Schema => { const normalize = (schema: Schema): Schema => {
if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]); if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]!);
if (schema.anyOf) { if (schema.anyOf) {
const { anyOf, ...rest } = schema; const { anyOf, ...rest } = schema;
const selected = normalize( const selected = normalize(
@@ -40,6 +53,7 @@ export function trainingForm(config: TrainingConfig) {
); );
return { ...selected, ...rest, type: [selected.type as JSONSchema7TypeName, 'null'] }; return { ...selected, ...rest, type: [selected.type as JSONSchema7TypeName, 'null'] };
} }
if (schema.oneOf && schema.discriminator) return union(schema as Required<Schema>);
if (schema.properties) { if (schema.properties) {
return { return {
...schema, ...schema,
@@ -53,34 +67,64 @@ export function trainingForm(config: TrainingConfig) {
} }
return schema; return schema;
}; };
const schema = normalize(raw); const union = (schema: Required<Pick<Schema, 'oneOf' | 'discriminator'>> & Schema): Schema => {
const reference = schema.properties?.['reference'] as Schema | undefined; const key = schema.discriminator.propertyName;
if (reference) reference.required = reference.required?.filter((key) => key !== 'name'); const members = schema.oneOf.map((entry) => normalize(entry as Schema));
return { schema, model }; const kinds = members.map((member) => member.properties![key] as Schema);
variants.discriminator = key;
const properties: Record<string, Schema> = {
[key]: {
type: 'string',
title: kinds[0]!.title,
oneOf: members.map((member, index) => ({
const: kinds[index]!.const,
title: member.title,
})),
},
};
members.forEach((member, index) => {
for (const [name, property] of Object.entries(member.properties!)) {
if (name === key) continue;
properties[name] ??= property as Schema;
(variants.owners[name] ??= []).push(kinds[index]!.const as string);
}
});
return {
type: 'object',
required: [...new Set(members.flatMap((member) => member.required ?? []))],
properties,
};
};
return { schema: normalize(raw), model, variants };
} }
function allowedFile(file: File, allowed: string[]): boolean { export function sourcePayload<T extends object>(source: T, variants: Variants): T {
return allowed.some((pattern) => { const kind = (source as Record<string, unknown>)[variants.discriminator];
if (pattern === '*.edf') return file.name.toLowerCase().endsWith('.edf'); return Object.fromEntries(
return file.name === pattern; Object.entries(source).filter(
}); ([name]) => !variants.owners[name] || variants.owners[name].includes(kind as string),
),
) as T;
} }
@Component({ @Component({
selector: 'app-governance-training', selector: 'app-governance-training',
imports: [FormsModule, ReactiveFormsModule, FormlyForm, MatButtonModule], imports: [FormsModule, ReactiveFormsModule, FormlyForm, MatButtonModule, MatCheckboxModule],
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])], providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
template: ` template: `
<section class="card"> <section class="card" aria-labelledby="training-heading">
<h3>{{ name() === 'all' ? 'Entrenar modelos' : 'Reentrenar ' + name() }}</h3> <h2 #heading id="training-heading" tabindex="-1">Entrenamiento</h2>
@if (name() !== 'all') {
<p>Reentrenar {{ name() }}</p>
}
@if (config.hasValue()) { @if (config.hasValue()) {
@let form = config.value(); @let form = config.value();
<form (ngSubmit)="start(form.model)"> <form (ngSubmit)="start(form.model)">
<formly-form [form]="form.form" [fields]="form.fields" [model]="form.model" /> <formly-form [form]="form.form" [fields]="form.fields" [model]="form.model" />
<div class="button-row">
@if (domain() === 'tea') { @if (domain() === 'tea') {
<label <mat-checkbox name="promote" [(ngModel)]="autoPromote"
><input type="checkbox" name="promote" [(ngModel)]="autoPromote" /> Promover al >Promover al terminar</mat-checkbox
terminar</label
> >
} }
<button <button
@@ -90,40 +134,11 @@ function allowedFile(file: File, allowed: string[]): boolean {
> >
Entrenar Entrenar
</button> </button>
</div>
</form> </form>
} @else if (config.error(); as error) { } @else if (config.error(); as error) {
<p role="alert">{{ errorText(error) }}</p> <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()) { @if (message()) {
<p role="status">{{ message() }}</p> <p role="status">{{ message() }}</p>
} }
@@ -131,6 +146,7 @@ function allowedFile(file: File, allowed: string[]): boolean {
`, `,
}) })
export class Training { export class Training {
private readonly heading = viewChild.required<ElementRef<HTMLHeadingElement>>('heading');
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema); private readonly jsonschema = inject(FormlyJsonschema);
readonly domain = input.required<Domain>(); readonly domain = input.required<Domain>();
@@ -141,103 +157,63 @@ export class Training {
protected readonly config = resource({ protected readonly config = resource({
params: () => ({ domain: this.domain(), name: this.name() }), params: () => ({ domain: this.domain(), name: this.name() }),
loader: async ({ params }) => { loader: async ({ params }) => {
const { schema, model } = trainingForm(await this.api.invoke(trainingConfig, params)); const { schema, model, variants } = trainingForm(
await this.api.invoke(trainingConfig, params),
);
const fields = [ const fields = [
this.jsonschema.toFieldConfig(schema, { this.jsonschema.toFieldConfig(schema, {
map: (field, source) => { map: (field, source) => {
field.props = { ...field.props, appearance: 'outline' };
if (source.format === 'date') { if (source.format === 'date') {
field.props = { ...field.props, type: 'date' }; field.props = { ...field.props, type: 'date' };
} }
if (field.key === 'line_hz') { const owners = variants.owners[field.key as string];
field.type = 'select'; if (owners) {
field.props = { field.expressions = {
...field.props, hide: (field) => !owners.includes(field.model?.[variants.discriminator]),
options: [
{ value: 50, label: '50 Hz' },
{ value: 60, label: '60 Hz' },
],
}; };
field.resetOnHide = false;
} }
return field; return field;
}, },
}), }),
]; ];
return { fields, model, form: new UntypedFormGroup({}) }; return { fields, model, variants, 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); readonly busy = model(false);
protected readonly uploading = signal(false);
protected readonly message = signal(''); protected readonly message = signal('');
protected readonly autoPromote = signal(false); protected readonly autoPromote = linkedSignal({ source: this.domain, computation: () => false });
protected readonly errorText = errorText; protected readonly errorText = errorText;
focus(): void {
this.heading().nativeElement.focus();
}
protected async start(model: TrainingConfig['defaults']): Promise<void> { protected async start(model: TrainingConfig['defaults']): Promise<void> {
if (this.busy() || this.disabled()) return; if (this.busy() || this.disabled()) return;
this.busy.set(true); this.busy.set(true);
this.message.set(''); this.message.set('');
const domain = this.domain(); const domain = this.domain();
const name = this.name(); const name = this.name();
const variants = this.config.value()!.variants;
const source = model['source'] as TrainingSource | undefined;
const autoPromote = domain === 'tea' && this.autoPromote(); const autoPromote = domain === 'tea' && this.autoPromote();
const reference = model['reference'];
try { try {
const { run_id } = await this.api.invoke(train, { const { run_id } = await this.api.invoke(train, {
domain, domain,
body: { body: {
as_of: model['as_of'] || undefined, as_of: model['as_of'] || undefined,
reference: reference?.name ? reference : undefined, source: source && sourcePayload(source, variants),
execution: this.execution(), execution: this.execution(),
...(name === 'all' ? {} : { models: [name] }), ...(name === 'all' ? {} : { models: [name] }),
}, },
}); });
this.started.emit({ id: run_id, autoPromote }); if (domain === this.domain()) this.started.emit({ id: run_id, autoPromote });
} catch (error) { } catch (error) {
this.message.set(errorText(error)); if (domain === this.domain()) this.message.set(errorText(error));
} finally { } finally {
this.busy.set(false); if (domain === this.domain()) 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);
} }
} }
} }
+276 -91
View File
@@ -4,6 +4,14 @@ import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
export const SHORT = '.1~f';
const SIGNIFICANT = '.2~r';
export const percentAxis = {
type: 'linear' as const,
ticksuffix: ' %',
tickformat: '.0f',
hoverformat: SHORT,
};
const count = (n: number) => n.toLocaleString('es-MX'); const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX'); const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
@@ -12,7 +20,6 @@ function rgba(hex: string, alpha: number): string {
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`; return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
} }
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure { export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined); const shown = steps.filter((s) => s.r?.score !== undefined);
return { return {
@@ -33,23 +40,26 @@ export function routeFigure(steps: { label: string; r: Reading | undefined }[]):
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!), array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)), arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
}, },
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>', hovertemplate: `%{y}<br>mediana %{x:${SHORT}} días<extra></extra>`,
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { layout: {
showlegend: false, showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false }, xaxis: {
title: { text: 'Días' },
rangemode: 'tozero',
zeroline: false,
...valueAxis(shown.flatMap((s) => [s.r!.score, s.r!.high])),
},
yaxis: { autorange: 'reversed', type: 'category', automargin: true }, yaxis: { autorange: 'reversed', type: 'category', automargin: true },
}, },
}; };
} }
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number { function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0; return r.strata['category']?.[code]?.['initial-population'] ?? 0;
} }
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure { export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code)); const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0); const total = values.reduce((a, b) => a + b, 0);
@@ -99,7 +109,7 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
), ),
line: { color: '#FFFFFF', width: 2 }, line: { color: '#FFFFFF', width: 2 },
}, },
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>', hovertemplate: '%{label}<br>%{value:d} (%{percent:.1~%})<extra></extra>',
}, },
{ {
...common, ...common,
@@ -108,21 +118,19 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
labels: catalog.categories.map((c) => c.label), labels: catalog.categories.map((c) => c.label),
hole: 0.74, hole: 0.74,
domain: { x: [0, 1], y: [0, 1] }, domain: { x: [0, 1], y: [0, 1] },
// along the thin ring, so a label fits its slice
insidetextorientation: 'tangential', insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')), text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: { marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)), colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 }, line: { color: '#FFFFFF', width: 2 },
}, },
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>', hovertemplate: '%{label}<br>%{value:d} (%{percent:.1~%})<extra></extra>',
}, },
] as Partial<Plotly.Data>[], ] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } }, layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
}; };
} }
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars( export function scenarioBars(
r: Reading, r: Reading,
catalog: Catalog, catalog: Catalog,
@@ -145,13 +153,13 @@ export function scenarioBars(
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)), x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)), customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color }, marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`, hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1~f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[], })) as Partial<Plotly.Data>[],
layout: { layout: {
barmode: 'stack', barmode: 'stack',
xaxis: { xaxis: {
title: { text: '% de pacientes del escenario con resultado' }, title: { text: '% de pacientes del escenario con resultado' },
ticksuffix: ' %', ...percentAxis,
range: [0, 100.5], range: [0, 100.5],
dtick: 20, dtick: 20,
}, },
@@ -166,8 +174,7 @@ export function scenarioBars(
}; };
} }
/** Wilson score interval at 95 %, in percent. */ function wilson(k: number, n: number): [number, number] {
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054; const z = 1.959963984540054;
const p = k / n; const p = k / n;
const d = 1 + (z * z) / n; const d = 1 + (z * z) / n;
@@ -176,8 +183,6 @@ export function wilson(k: number, n: number): [number, number] {
return [100 * (c - h), 100 * (c + h)]; return [100 * (c - h), 100 * (c + h)];
} }
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots( export function rateDots(
r: Reading, r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean }, spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
@@ -214,7 +219,7 @@ export function rateDots(
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)), array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)), arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
}, },
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>', hovertemplate: '%{y}: %{x:.1~f} %<extra></extra>',
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { layout: {
@@ -226,7 +231,7 @@ export function rateDots(
categoryarray: [...y].reverse(), categoryarray: [...y].reverse(),
automargin: true, automargin: true,
}, },
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } }, xaxis: { range: [0, 100], ...percentAxis, zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({ annotations: rows.map((x) => ({
x: 1, x: 1,
xref: 'paper', xref: 'paper',
@@ -248,8 +253,6 @@ export function rateDots(
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 }); const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
export function fill(template: string, r: Reading): string { export function fill(template: string, r: Reading): string {
const p = r.populations; const p = r.populations;
const values: Record<string, string> = { const values: Record<string, string> = {
@@ -265,7 +268,6 @@ export function fill(template: string, r: Reading): string {
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? ''); return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
} }
/** A duration's quartile box in the period. */
export function boxFigure(r: Reading, period: string): Figure { export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!; const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!; const q3 = r.high ?? r.score!;
@@ -285,11 +287,13 @@ export function boxFigure(r: Reading, period: string): Figure {
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`, hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } }, layout: {
showlegend: false,
yaxis: { title: { text: 'días' }, rangemode: 'tozero', ...valueAxis([q1, r.score!, q3]) },
},
}; };
} }
/** One ring: the categories' shares, the total in the centre. */
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure { export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code)); const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0); const total = values.reduce((a, b) => a + b, 0);
@@ -306,10 +310,9 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
colors: catalog.categories.map((c) => c.color), colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 }, line: { color: '#FFFFFF', width: 2 },
}, },
// an empty slice says nothing (its label would sit on its neighbours') texttemplate: values.map((v) => (v ? '%{label}<br>%{percent:.1~%}' : '')),
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
textposition: 'outside', textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>', hovertemplate: '%{label}<br>%{value:d} (%{percent:.1~%})<extra></extra>',
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { layout: {
@@ -329,7 +332,6 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
}; };
} }
/** A category's count per bar, one bar each, in the period. */
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure { export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label); const y = catalog.categories.map((c) => c.label);
return { return {
@@ -341,86 +343,113 @@ export function countBars(r: Reading, catalog: Catalog, axis: string, period: st
y, y,
x: catalog.categories.map((c) => counted(r, c.code)), x: catalog.categories.map((c) => counted(r, c.code)),
marker: { color: catalog.categories.map((c) => c.color) }, marker: { color: catalog.categories.map((c) => c.color) },
texttemplate: '%{x}', texttemplate: '%{x:d}',
textposition: 'outside', textposition: 'outside',
hovertemplate: '%{y}: %{x}<extra></extra>', hovertemplate: '%{y}: %{x:d}<extra></extra>',
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { layout: {
showlegend: false, showlegend: false,
xaxis: { title: { text: axis }, rangemode: 'tozero' }, xaxis: {
title: { text: axis },
rangemode: 'tozero',
...valueAxis(catalog.categories.map((c) => counted(r, c.code))),
},
yaxis: { type: 'category', autorange: 'reversed', automargin: true }, yaxis: { type: 'category', autorange: 'reversed', automargin: true },
}, },
}; };
} }
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2']; const TEA_SEXES = [
/** "16-23" as the screens say it: "16 a 23 meses". */ { code: 'male', color: '#4269C2' },
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses'); { code: 'female', color: ROSE },
];
function ages(r: Reading): [string, Record<string, number>][] { const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
return Object.entries(r.strata['age_group'] ?? {}).sort(
([a], [b]) => parseInt(a, 10) - parseInt(b, 10), function ageBands(cells: Reading['strata'][string]): string[] {
); const bands = Object.keys(cells)
.map((key) => key.split('|'))
.filter(([, code]) => TEA_SEXES.some((sex) => sex.code === code))
.map(([band]) => band);
return [...new Set(bands)].sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
} }
/** By age group: the numerator and the rest of the denominator, stacked. */
export function ageStack(r: Reading, names: [string, string]): Figure { export function ageStack(r: Reading, names: [string, string]): Figure {
const rows = ages(r); const cells = r.strata['age_sex'] ?? {};
const x = rows.map(([a]) => ageLabel(a)); const bands = ageBands(cells);
const x = bands.map(ageLabel);
return { return {
data: [ data: TEA_SEXES.flatMap(({ code, color }) => {
{ const rows = bands.map((band) => cells[`${band}|${code}`]);
const confirmed = rows.map((row) => row?.['numerator'] ?? 0);
const totals = rows.map((row) => row?.['denominator'] ?? 0);
return [confirmed, totals.map((n, i) => n - confirmed[i])].map((y, i) => ({
type: 'bar', type: 'bar',
name: names[0], name: `${name(code)} · ${names[i]}`,
offsetgroup: code,
x, x,
y: rows.map(([, c]) => c['numerator'] ?? 0), y,
marker: { color: AGE_COLORS[0] }, marker: { color: i ? rgba(color, 0.25) : color },
}, text: y.map((n, j) => (n ? `${n} (${percent((100 * n) / totals[j])} %)` : '')),
{ textposition: 'inside',
type: 'bar', hovertemplate: '%{x}<br>%{fullData.name}: %{y:d} pacientes<extra></extra>',
name: names[1], })) as Partial<Plotly.Data>[];
x, }),
y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)),
marker: { color: AGE_COLORS[1] },
},
] as Partial<Plotly.Data>[],
layout: { layout: {
barmode: 'stack', barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' }, yaxis: {
}, title: { text: 'Pacientes' },
}; rangemode: 'tozero',
} ...valueAxis(
bands.flatMap((band) =>
/** By age group: the numerator's share of the denominator, one bar each. */ TEA_SEXES.map(({ code }) => cells[`${band}|${code}`]?.['denominator'] ?? 0),
export function ageShare(r: Reading, axis: string): Figure {
const rows = ages(r);
return {
data: [
{
type: 'bar',
x: rows.map(([a]) => ageLabel(a)),
y: rows.map(([, c]) =>
c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0,
), ),
marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) }, ),
texttemplate: '%{y:.1f} %', },
textposition: 'outside',
hovertemplate: '%{x}: %{y:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
}, },
}; };
} }
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by export function ageShare(r: Reading, axis: string): Figure {
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one const cells = r.strata['age_sex'] ?? {};
* closed shape. */ const bands = ageBands(cells);
const x = bands.map(ageLabel);
return {
data: TEA_SEXES.map(({ code, color }) => ({
type: 'bar',
name: name(code),
x,
y: bands.map((band) => {
const row = cells[`${band}|${code}`];
return row?.['denominator'] ? (100 * (row['numerator'] ?? 0)) / row['denominator'] : null;
}),
marker: { color },
texttemplate: '%{y:.1~f} %',
textposition: 'outside',
hovertemplate: '%{x}: %{y:.1~f} %<extra>%{fullData.name}</extra>',
})),
layout: {
barmode: 'group',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ...percentAxis },
},
};
}
export function valueAxis(values: Iterable<number | null | undefined>) {
const found = [...values].filter((v): v is number => v != null && Number.isFinite(v));
const counts = found.every(Number.isInteger);
const narrow = found.length > 0 && Math.max(...found) - Math.min(0, ...found) <= 5;
return {
type: 'linear' as const,
tickformat: counts ? 'd' : SIGNIFICANT,
hoverformat: counts ? 'd' : '.3~r',
...(counts && narrow ? { dtick: 1 } : {}),
};
}
export function historyFigure( export function historyFigure(
panel: HistoryPanel, panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[], series: { label: string; r: Reading | undefined }[],
@@ -428,9 +457,9 @@ export function historyFigure(
xTitle: string, xTitle: string,
): Figure { ): Figure {
const x = series.map((s) => s.label); const x = series.map((s) => s.label);
const layout = (y: string) => ({ const layout = (y: string, values: (number | null)[]) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const }, xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } }, yaxis: { title: { text: y }, ...valueAxis(values) },
}); });
if (panel.kind === 'stack') { if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))]; const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
@@ -441,24 +470,31 @@ export function historyFigure(
.filter((c) => !declared.some((d) => d.code === c)) .filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })), .map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
]; ];
return { const data = named.map((c) => ({
data: named.map((c) => ({ type: 'bar' as const,
type: 'bar',
name: c.label, name: c.label,
x, x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0), y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color }, marker: { color: c.color },
})), }));
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' }, const totals = x.map((_, i) => data.reduce((sum, trace) => sum + trace.y[i], 0));
return {
data,
layout: { ...layout(panel.axis ?? 'Pacientes', [0, ...totals]), barmode: 'stack' },
}; };
} }
const k = panel.kind === 'percent' ? 100 : 1; const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k); const at = (v?: number) => (v === undefined ? null : v * k);
const band = [
...series.map((s) => at(s.r?.high)),
...[...series].reverse().map((s) => at(s.r?.low)),
];
const scores = series.map((s) => at(s.r?.score));
return { return {
data: [ data: [
{ {
x: [...x, ...[...x].reverse()], x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))], y: band,
mode: 'lines', mode: 'lines',
fill: 'toself', fill: 'toself',
fillcolor: line + '33', fillcolor: line + '33',
@@ -468,13 +504,162 @@ export function historyFigure(
}, },
{ {
x, x,
y: series.map((s) => at(s.r?.score)), y: scores,
mode: 'lines+markers', mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana', name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line }, line: { color: line },
marker: { color: line }, marker: { color: line },
}, },
], ],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'), layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días', [...band, ...scores]),
};
}
export function sexCountBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const base = countBars(r, catalog, axis, period);
const cells = r.strata['sex-category'] ?? {};
return {
data: TEA_SEXES.map(({ code, color }) => ({
...base.data[0],
name: name(code),
marker: { color },
x: catalog.categories.map((c) => cells[`${code}|${c.code}`]?.['initial-population'] ?? 0),
hovertemplate: '%{y}: %{x:d}<extra>%{fullData.name}</extra>',
})) as Partial<Plotly.Data>[],
layout: { ...base.layout, barmode: 'group', showlegend: true },
};
}
const STOPPED = '#888888';
export function teaSankey(r: Reading): Figure {
const [mchat, psychology, neuro, eeg] = [
'mchat_only',
'psychology',
'neuropediatrics',
'eeg',
].map((code) => counted(r, code));
const nodes = [
{ label: 'M-CHAT', color: '#B8433A', value: mchat + psychology + neuro + eeg },
{ label: 'Evaluación<br>psicológica', color: '#D0B778', value: psychology + neuro + eeg },
{ label: 'Evaluación<br>neuropediátrica', color: '#7184A2', value: neuro + eeg },
{ label: 'EEG de<br>buena calidad', color: OLIVE, value: eeg },
{ label: 'Se quedó en evaluación<br>neuropediátrica', color: STOPPED, value: neuro },
{ label: 'Se quedó en evaluación<br>psicológica', color: STOPPED, value: psychology },
{ label: 'Se quedó en M-CHAT', color: STOPPED, value: mchat },
];
const shown = nodes.flatMap((node, index) => (node.value > 0 ? [index] : []));
const position = new Map(shown.map((index, place) => [index, place]));
const flows: [number, number][] = [
[0, 1],
[0, 6],
[1, 2],
[1, 5],
[2, 3],
[2, 4],
];
const links = flows.flatMap(([source, target]) =>
nodes[target].value > 0
? [{ source: position.get(source)!, target: position.get(target)!, index: target }]
: [],
);
const hovertemplate = '%{label}<br>%{value} pacientes<extra></extra>';
return {
data: [
{
type: 'sankey',
arrangement: 'fixed',
node: {
label: shown.map((index) => nodes[index].label),
color: shown.map((index) => nodes[index].color),
pad: 36,
hovertemplate,
},
link: {
source: links.map(({ source }) => source),
target: links.map(({ target }) => target),
value: links.map(({ index }) => nodes[index].value),
color: links.map(({ index }) => rgba(nodes[index].color, 0.45)),
label: links.map(({ index }) => nodes[index].label.replace('<br>', ' ')),
hovertemplate,
},
} as Partial<Plotly.Data>,
],
layout: { font: { size: 12 }, margin: { l: 20, r: 20, t: 24, b: 24 } },
};
}
export function teaSexBars(r: Reading, selectedSex?: string): Figure {
const cells = r.strata['sex-category'] ?? {};
const x = TEA_SEXES.map(({ code }) => name(code));
return {
data: [
{ code: 'confirmed', label: 'Diagnóstico confirmado' },
{ code: 'in_population', label: 'Sin diagnóstico confirmado' },
].map(({ code: category, label }, i) => {
const y = TEA_SEXES.map(
({ code }) => cells[`${code}|${category}`]?.['initial-population'] ?? 0,
);
return {
type: 'bar',
name: label,
x,
y,
marker: {
color: TEA_SEXES.map(({ color }) => (i ? rgba(color, 0.25) : color)),
line: {
color: TEA_SEXES.map(({ color }) => color),
width: TEA_SEXES.map(({ code }) => (code === selectedSex ? 2 : 0)),
},
},
customdata: TEA_SEXES.map(({ code }, j) => {
const total = r.strata['sex']?.[code]?.['initial-population'] ?? 0;
return [percent(total ? (100 * y[j]) / total : 0), total];
}),
hovertemplate:
'%{x} · %{fullData.name}<br>%{y:d} niños, %{customdata[0]} % de %{customdata[1]}<extra></extra>',
};
}),
layout: {
barmode: 'group',
xaxis: { title: { text: 'Sexo' }, type: 'category' },
yaxis: {
title: { text: 'Niños' },
rangemode: 'tozero',
...valueAxis(
TEA_SEXES.map(({ code }) => r.strata['sex']?.[code]?.['initial-population'] ?? 0),
),
},
},
};
}
export function teaAlterations(r: Reading): Figure {
const rows = [['', r.populations] as const, ...Object.entries(r.strata['alteration'] ?? {})];
const customdata = rows.map(([, c]) => [c['numerator'], c['denominator']]);
const rates = customdata.map(([n, total]) => (total ? (100 * n) / total : 0));
return {
data: [
{
type: 'bar',
x: rows.map(([code]) => (code ? name(code) : 'Alguna alteración')),
y: rates,
marker: { color: rows.map((_, i) => PALETTE[(i + 1) % PALETTE.length]) },
text: rates.map((rate) => `${percent(rate)} %`),
textposition: 'outside',
cliponaxis: false,
customdata,
hovertemplate:
'%{x}<br>%{text} (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
xaxis: { type: 'category', title: { text: 'Alteración del EEG' } },
yaxis: {
range: [0, 100],
...percentAxis,
title: { text: '% de niños con EEG de buena calidad' },
},
},
}; };
} }
+1 -1
View File
@@ -5,7 +5,7 @@ import { periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
it('starts the window the day after the same day months before (core.follow_up)', () => { it('starts the window the day after the same day months before (core.follow_up)', () => {
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23'); expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one expect(windowStart('2026-05-31', 3)).toBe('2026-03-01');
expect(windowStart('2026-01-15', 1)).toBe('2025-12-16'); expect(windowStart('2026-01-15', 1)).toBe('2025-12-16');
}); });
+6 -157
View File
@@ -1,8 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { ados2Component, ados2Groups } from '../ados2'; import { code, ext, patientCurp, patientName, resources } from '../fhir';
import { code, ext, label, resources } from '../fhir';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row { export interface Row {
patient: Patient; patient: Patient;
name?: string; name?: string;
@@ -16,8 +14,6 @@ export interface Row {
risk: Record<'cin2' | 'cancer', number | undefined>; risk: Record<'cin2' | 'cancer', number | undefined>;
} }
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
const AGE_GROUPS: [number, number][] = [ const AGE_GROUPS: [number, number][] = [
[25, 34], [25, 34],
[35, 44], [35, 44],
@@ -39,8 +35,6 @@ export function ageGroup(
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`; return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
} }
/** Her current risk of an outcome at a horizon: from the latest index date any of the
* outcome's models scored her at, the highest when several did (as the list is sorted). */
export function currentRisk( export function currentRisk(
risks: RiskAssessment[], risks: RiskAssessment[],
outcome: 'cin2' | 'cancer', outcome: 'cin2' | 'cancer',
@@ -65,8 +59,6 @@ export function currentRisk(
); );
} }
/** The list's rows from one page: per patient, her latest cytology and HPV sampled in the
* window, her days to diagnosis, and her latest reported biopsy. */
export function rows(page: Bundle, start: string, cutoff: string, horizon: number): Row[] { export function rows(page: Bundle, start: string, cutoff: string, horizon: number): Row[] {
const reports = resources<DiagnosticReport>(page, 'DiagnosticReport'); const reports = resources<DiagnosticReport>(page, 'DiagnosticReport');
const observations = new Map(resources<Observation>(page, 'Observation').map((o) => [o.id, o])); const observations = new Map(resources<Observation>(page, 'Observation').map((o) => [o.id, o]));
@@ -100,8 +92,8 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`); const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return { return {
patient, patient,
name: patient.name?.[0]?.text, name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patientCurp(patient),
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff), ageGroup: ageGroup(patient.birthDate, cutoff),
cytology: last && { cytology: last && {
@@ -127,7 +119,6 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
}); });
} }
/** The window's first day: `months` before the cut-off (the month's last day when shorter), plus one. */
export function windowStart(cutoff: string, months: number): string { export function windowStart(cutoff: string, months: number): string {
const [y, m, d] = cutoff.split('-').map(Number); const [y, m, d] = cutoff.split('-').map(Number);
const total = y * 12 + (m - 1) - months; const total = y * 12 + (m - 1) - months;
@@ -138,16 +129,13 @@ export function windowStart(cutoff: string, months: number): string {
return day.toISOString().slice(0, 10); return day.toISOString().slice(0, 10);
} }
/** One row of CaMa's follow-up list: her latest mammogram reported by the cut-off, where the interface CamaRow {
* biopsy it led to stands, and how soon she should be seen. */
export interface CamaRow {
patient: Patient; patient: Patient;
name?: string; name?: string;
curp?: string; curp?: string;
status: string; status: string;
priority: string; priority: string;
ageGroup: string; ageGroup: string;
/** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number }; mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string }; biopsy?: { date: string; histology?: string };
} }
@@ -188,8 +176,8 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1); .at(-1);
return { return {
patient, patient,
name: patient.name?.[0]?.text, name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patientCurp(patient),
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '', priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff, CAMA_AGE_GROUPS), ageGroup: ageGroup(patient.birthDate, cutoff, CAMA_AGE_GROUPS),
@@ -207,142 +195,3 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
}; };
}); });
} }
export const TEA_STEPS = [
{ code: 'mchat_only', label: 'M-CHAT' },
{ code: 'psychology', label: 'Psicología' },
{ code: 'neurology', label: 'Neuropediatría' },
{ code: 'eeg', label: 'EEG' },
] as const;
type Prediction = NonNullable<RiskAssessment['prediction']>[number];
function associationPair(p: Prediction) {
const stat = (name: string) => ext(p, `association-${name}`)?.valueDecimal;
return {
pair: code(p.outcome),
or: stat('odds-ratio'),
low: stat('ci-low'),
high: stat('ci-high'),
q: stat('q'),
probability: p.probabilityDecimal,
reference: stat('reference-probability'),
sameDirection: ext(p, 'association-same-direction')?.valueBoolean,
headline: ext(p, 'association-headline')?.valueBoolean === true,
};
}
function concordance(headline?: ReturnType<typeof associationPair>, ados?: Observation): string {
if (!headline || !ados || headline.probability == null || headline.reference == null) return '—';
const outcome = headline.pair?.split('|')[2];
const item = Number(outcome?.match(/^ados2_item_(\d{2})$/)?.[1]);
const score =
outcome === 'CSS' ? ados.valueInteger : ados2Component(ados, item)?.valueQuantity?.value;
if (score == null) return '—';
const event = score >= (outcome === 'CSS' ? 8 : 1);
const predicted = headline.probability >= headline.reference;
return event === predicted ? 'Concordante' : 'No concordante';
}
function byPatient<T extends DiagnosticReport | Observation | RiskAssessment>(
records: T[],
): Map<string | undefined, T[]> {
const grouped = new Map<string | undefined, T[]>();
for (const record of records) {
const subject = record.subject?.reference;
const group = grouped.get(subject);
if (group) group.push(record);
else grouped.set(subject, [record]);
}
return grouped;
}
export function teaRows(page: Bundle) {
const reports = byPatient(resources<DiagnosticReport>(page, 'DiagnosticReport'));
const observations = byPatient(resources<Observation>(page, 'Observation'));
const risks = byPatient(resources<RiskAssessment>(page, 'RiskAssessment'));
const dateOrder = (a: Observation | DiagnosticReport, b: Observation | DiagnosticReport) =>
(a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '');
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
const subject = `Patient/${patient.id}`;
const obs = observations.get(subject) ?? [];
const eegs = (reports.get(subject) ?? []).filter((r) => code(r.code) === 'eeg').sort(dateOrder);
const ados = obs.filter((o) => code(o.code) === 'ados2').sort(dateOrder);
const mchat = obs.filter((o) => code(o.code) === 'mchat.score').sort(dateOrder)[0];
const neurology = obs
.filter(
(o) =>
code(o.code) === 'clinical_note.specialty' &&
code(o.valueCodeableConcept) === 'pediatric_neurology',
)
.sort(dateOrder)[0];
const risk = risks.get(subject)?.[0];
const pairs = (risk?.prediction ?? []).map(associationPair);
const headline = pairs.find((p) => p.headline);
const basisAdos = risk?.basis?.find((ref) =>
ref.reference?.startsWith('Observation/'),
)?.reference;
const evaluation = basisAdos
? ados.find((o) => `Observation/${o.id}` === basisAdos)
: ados.at(-1);
const status = ext(patient, 'follow-up-status')?.valueCoding?.code;
const dates = [
mchat?.effectiveDateTime,
ados[0]?.effectiveDateTime,
neurology?.effectiveDateTime,
[
...eegs.map((e) => e.effectiveDateTime),
...obs.filter((o) => code(o.code) === 'eeg.lab_record_id').map((o) => o.effectiveDateTime),
]
.filter((day) => !!day)
.sort()[0],
];
const explicitStep = TEA_STEPS.findIndex((s) => s.code === ext(patient, 'tea-step')?.valueCode);
const lastReached =
explicitStep >= 0
? explicitStep
: status === 'finished'
? 3
: dates.slice(0, 3).reduce((last, date, index) => (date ? index : last), -1);
return {
patient,
name: patient.name?.[0]?.text,
recordNumbers: [
...new Set(
(patient.identifier ?? [])
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
.map((i) => i.value!),
),
],
status,
steps: TEA_STEPS.map((step, i) => ({
...step,
date: dates[i],
reached: i <= lastReached || (i === 0 && status === 'active'),
})),
mchatScore: mchat?.valueQuantity?.value,
ados: evaluation && {
date: evaluation.effectiveDateTime,
css: evaluation.valueInteger,
module: label(
evaluation.component?.find((c) => code(c.code) === 'ados2.module')?.valueCodeableConcept,
),
classification: label(evaluation.interpretation?.[0]),
groups: ados2Groups(evaluation),
},
eegs: eegs.map((e) => ({
id: e.id,
date: e.effectiveDateTime,
quality: label(e.conclusionCode?.[0]),
validity: label(e.conclusionCode?.[1]),
duration: ext(e, 'eeg-duration-min')?.valueDecimal,
channels: ext(e, 'eeg-channels')?.valueInteger,
})),
headline,
concordance: concordance(headline, evaluation),
pairs,
};
});
}
export type TeaRow = ReturnType<typeof teaRows>[number];
+1 -2
View File
@@ -13,7 +13,6 @@ import { TabSeguimiento } from './tab-seguimiento';
import { TabTrazabilidad } from './tab-trazabilidad'; import { TabTrazabilidad } from './tab-trazabilidad';
import { Loading } from '../loading'; import { Loading } from '../loading';
/** A domain's indicator page: four tabs over its FHIR measures and patients. */
@Component({ @Component({
selector: 'app-indicadores', selector: 'app-indicadores',
imports: [ imports: [
@@ -30,7 +29,7 @@ import { Loading } from '../loading';
<section class="page"> <section class="page">
<h1>{{ title() }}</h1> <h1>{{ title() }}</h1>
<p class="subtitle">Explora los indicadores de {{ title().toLowerCase() }}.</p> <p class="subtitle">Explora los indicadores de {{ title().toLowerCase() }}.</p>
<app-report-button /> <app-report-button class="button-row" />
@if (measures.isLoading()) { @if (measures.isLoading()) {
<app-loading what="los indicadores" /> <app-loading what="los indicadores" />
} @else if (measures.error()) { } @else if (measures.error()) {
-85
View File
@@ -1,85 +0,0 @@
/** Where each measure goes on a domain's indicator page (today's layout); measures not
* named here are clinical cards. Measures are named by their code (`Measure.name`). */
export interface Layout {
kpis: string[];
route: { label: string; fromSample: string; fromStep: string; step: string }[];
/** The measure whose data decides the default period. */
anchor: string;
}
export const LAYOUTS: Record<string, Layout> = {
cacu: {
kpis: [
'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
],
route: [
{
label: 'Resultado de citología',
step: 'Toma a resultado de citología',
fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE',
},
{
label: 'Colposcopía',
step: 'Del resultado de citología a la colposcopía',
fromSample: 'CACU_DIAS_TOMA_COLPOSCOPIA',
fromStep: 'CACU_DIAS_RESULTADO_COLPOSCOPIA',
},
{
label: 'Resultado de biopsia',
step: 'De la colposcopía al resultado de biopsia',
fromSample: 'CACU_DIAS_TOMA_BIOPSIA',
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
anchor: 'IND1',
},
cama: {
kpis: [
'CAMA_BIRADS',
'CAMA_EU38A',
'CAMA_DIAS_TOMA_DIAGNOSTICO',
'CAMA_CONFIRMACION_BIRADS45',
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
],
route: [
{
label: 'Resultado de mastografía',
step: 'Toma a resultado de mastografía',
fromSample: 'CAMA_EU38A',
fromStep: 'CAMA_EU38A',
},
{
label: 'Diagnóstico',
step: 'Del resultado de mastografía al diagnóstico',
fromSample: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
fromStep: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
},
],
anchor: 'CAMA_BIRADS',
},
tea: {
kpis: [
'M26_DIAS_MCHAT_ADOS2',
'M27_DIAS_ADOS2_DIAGNOSTICO',
'M25_DIAS_MCHAT_DIAGNOSTICO',
'M23_PACIENTES_EVALUADOS',
'M24_CONFIRMACION_DIAGNOSTICO',
'M21_DIAGNOSTICADOS_CON_EEG',
'M22_DIAGNOSTICADOS_SIN_EEG',
'M29_CALIDAD_EEG',
],
route: [],
anchor: 'M23_PACIENTES_EVALUADOS',
},
};
+2 -213
View File
@@ -1,11 +1,8 @@
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4'; import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
import { code, ext } from '../fhir'; import { code, ext } from '../fhir';
import { Figure, PALETTE } from '../plot';
export type PeriodType = 'semester' | 'month'; export type PeriodType = 'semester' | 'month';
export type Scoring = 'proportion' | 'continuous-variable' | 'cohort';
/** The periods back from today, most recent first: semesters (`2025-S1`) or months. */
export function periods(type: PeriodType, years = 6, today = new Date()): string[] { export function periods(type: PeriodType, years = 6, today = new Date()): string[] {
const found: string[] = []; const found: string[] = [];
const year = today.getFullYear(); const year = today.getFullYear();
@@ -32,17 +29,12 @@ export function periodLabel(period: string): string {
return `${month} ${year}`; return `${month} ${year}`;
} }
export function scoring(measure: Measure): Scoring {
return code(measure.scoring) as Scoring;
}
export function periodTypes(measure: Measure): PeriodType[] { export function periodTypes(measure: Measure): PeriodType[] {
return (measure.extension ?? []) return (measure.extension ?? [])
.filter((e) => e.url.endsWith('/period-type')) .filter((e) => e.url.endsWith('/period-type'))
.map((e) => e.valueCode as PeriodType); .map((e) => e.valueCode as PeriodType);
} }
/** What one report says: its counts, its score and interval, and its strata. */
export interface Reading { export interface Reading {
populations: Record<string, number>; populations: Record<string, number>;
score?: number; score?: number;
@@ -66,7 +58,6 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
const score = group.measureScore; const score = group.measureScore;
const strata: Reading['strata'] = {}; const strata: Reading['strata'] = {};
for (const s of group.stratifier ?? []) { for (const s of group.stratifier ?? []) {
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
strata[name] = Object.fromEntries( strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [ (s.stratum ?? []).map((x) => [
@@ -87,7 +78,6 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
}; };
} }
/** Codes as the screens name them. */
export const LABELS: Record<string, string> = { export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)', NILM: 'Normal (NILM)',
LSIL: 'LIEBG', LSIL: 'LIEBG',
@@ -136,215 +126,14 @@ export const LABELS: Record<string, string> = {
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
), ),
}; };
/** A follow-up priority's label. */
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' }; export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
export const STRATA: Record<string, string> = { export const STRATA: Record<string, string> = {
category: 'Categoría', category: 'Categoría',
age_group: 'Grupo de edad', age_group: 'Grupo de edad',
sex: 'Sexo',
age_sex: 'Grupo de edad y sexo',
follow_up_status: 'Estatus de seguimiento', follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado', result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía', birads: 'BI-RADS de la mastografía',
}; };
export const name = (value: string) => LABELS[value] ?? value; export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
if (!r || r.score === undefined) return 'Sin dato';
switch (scoring(measure)) {
case 'proportion':
return `${(r.score * 100).toFixed(1)} %`;
case 'continuous-variable':
return `${Math.round(r.score * 10) / 10} días`;
default:
return `${r.score}`;
}
}
export function detail(measure: Measure, r: Reading | undefined): string {
if (!r) return '';
const p = r.populations;
switch (scoring(measure)) {
case 'proportion':
return r.score === undefined
? 'Sin pacientes en el periodo.'
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable':
return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
: `Mediana de ${p['measure-observation']} mediciones; cuartiles ${r.low}–${r.high} días.`;
default:
return `${p['initial-population'] ?? 0} pacientes.`;
}
}
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export type Ring = { labels: string[]; values: number[] };
export function donut(
measure: Measure,
r: Reading,
stratifier = 'category',
inner?: Ring,
outer?: Ring,
): Figure {
let labels: string[], values: number[];
if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto'];
values = [numerator, denominator - numerator];
} else {
const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v));
values = cells.map(([, c]) => c['initial-population'] ?? 0);
}
return {
data: [
{
type: 'pie',
hole: inner ? 0.68 : 0.62,
...(outer ?? { labels, values }),
sort: false,
textinfo: 'value+percent',
marker: { colors: PALETTE },
},
...(inner
? [
{
type: 'pie' as const,
hole: 0.45,
...inner,
sort: false,
textinfo: 'percent' as const,
domain: { x: [0.17, 0.83] as [number, number], y: [0.17, 0.83] as [number, number] },
marker: { colors: PALETTE },
},
]
: []),
],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
};
}
/** Bars per stratum: the rate (proportion) or the count (others). */
export function strataBars(
measure: Measure,
r: Reading,
stratifier: string,
showCounts = false,
): Figure {
const cells = Object.entries(r.strata[stratifier] ?? {});
const proportion = scoring(measure) === 'proportion';
const values = cells.map(([, c]) =>
proportion
? c['denominator']
? (100 * (c['numerator'] ?? 0)) / c['denominator']
: 0
: (c['initial-population'] ?? 0),
);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: cells.map(([v]) => name(v)),
x: values,
...(showCounts
? {
text: cells.map(([, c], i) => `${c['numerator'] ?? 0} (${values[i].toFixed(1)} %)`),
hovertemplate: '%{y}: %{text}<extra></extra>',
}
: {}),
marker: { color: PALETTE[0] },
},
],
layout: {
xaxis: { title: { text: proportion ? '%' : 'Pacientes' } },
yaxis: { automargin: true },
margin: { t: 8, r: 16, b: 48, l: 8 },
},
};
}
/** Horizontal median bars with their interquartile range, one per measure. */
export function medians(rows: { label: string; r: Reading | undefined }[]): Figure {
const shown = rows.filter((x) => x.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map((x) => x.label),
x: shown.map((x) => x.r!.score!),
error_x: {
type: 'data',
symmetric: false,
array: shown.map((x) => (x.r!.high ?? x.r!.score!) - x.r!.score!),
arrayminus: shown.map((x) => x.r!.score! - (x.r!.low ?? x.r!.score!)),
color: '#17324d',
},
marker: { color: PALETTE[0] },
hovertemplate: '%{y}: %{x} días<extra></extra>',
},
],
layout: {
xaxis: { title: { text: 'Días (mediana, Q1–Q3)' } },
yaxis: { automargin: true, autorange: 'reversed' },
},
};
}
/** A measure over time: % with its interval, median with its quartiles, or counts by category. */
export function history(
measure: Measure,
series: { period: string; r: Reading | undefined }[],
): Figure {
const x = series.map((s) => periodLabel(s.period));
const kind = scoring(measure);
if (kind === 'cohort') {
const categories = [
...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {}))),
];
return {
data: categories.map((c, i) => ({
type: 'bar',
name: name(c),
x,
y: series.map((s) => s.r?.strata['category']?.[c]?.['initial-population'] ?? 0),
marker: { color: PALETTE[i % PALETTE.length] },
})),
layout: { barmode: 'stack', yaxis: { title: { text: 'Pacientes' } } },
};
}
const k = kind === 'proportion' ? 100 : 1;
const value = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x,
y: series.map((s) => value(s.r?.high)),
mode: 'lines',
line: { width: 0 },
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => value(s.r?.low)),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
fillcolor: 'rgba(168,194,67,0.25)',
name: kind === 'proportion' ? 'IC 95 %' : 'Q1–Q3',
},
{
x,
y: series.map((s) => value(s.r?.score)),
mode: 'lines+markers',
name: kind === 'proportion' ? '%' : 'Mediana',
line: { color: PALETTE[0] },
},
],
layout: { yaxis: { title: { text: kind === 'proportion' ? '%' : 'Días' } } },
};
}
+53
View File
@@ -0,0 +1,53 @@
import { Component, input, output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
@Component({
selector: 'app-pager',
imports: [MatButtonModule],
template: `
<nav class="pager" aria-label="Páginas de pacientes">
<span class="muted"><ng-content /></span>
<button
mat-stroked-button
type="button"
(click)="previous.emit()"
[disabled]="previousDisabled()"
>
Anterior
</button>
<button mat-stroked-button type="button" (click)="next.emit()" [disabled]="nextDisabled()">
Siguiente
</button>
</nav>
`,
styles: `
.pager {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: flex-end;
margin-top: var(--space-3);
}
:host(.print-pagination) .pager {
flex-wrap: nowrap;
}
@media print {
:host(.print-pagination) .pager {
display: flex !important;
}
}
.muted {
margin-right: auto;
}
`,
})
export class Pager {
readonly previousDisabled = input.required<boolean>();
readonly nextDisabled = input.required<boolean>();
readonly previous = output<void>();
readonly next = output<void>();
}
+45 -54
View File
@@ -1,16 +1,9 @@
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui): interface Page {
* the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */
export interface Page {
kpis: Kpi[]; kpis: Kpi[];
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[]; opportunity?: Section[];
clinical: Section[]; clinical: Section[];
/** The measure whose data decides the default period. */
anchor: string; anchor: string;
} }
/** A card: its measure (none: not published yet), its title, and its value and note as
* templates (figures.fill). */
export interface Kpi { export interface Kpi {
measure?: string; measure?: string;
title: string; title: string;
@@ -22,18 +15,13 @@ export type Section =
| { kind: 'figures'; title?: string; figures: FigureSpec[] } | { kind: 'figures'; title?: string; figures: FigureSpec[] }
| { | {
kind: 'boxes'; kind: 'boxes';
/** none: the boxes stand alone (TEA) */
title?: string; title?: string;
cards: { measure?: string; title: string }[]; cards: { measure?: string; title: string }[];
/** the measure's own title under each card's (CaMa) */
subtitles?: boolean; subtitles?: boolean;
} }
/** Each figure in its own card, titled, two to a row (TEA). */
| { kind: 'grid'; figures: FigureSpec[] } | { kind: 'grid'; figures: FigureSpec[] }
/** TEA's period summary in words, its numbers from the measures. */
| { kind: 'tea-summary' } | { kind: 'tea-summary' }
| ({ kind: 'card' } & Kpi); | ({ kind: 'card' } & Kpi);
/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec = export type FigureSpec =
| { | {
kind: 'donut' | 'share-donut'; kind: 'donut' | 'share-donut';
@@ -43,12 +31,18 @@ export type FigureSpec =
center: string; center: string;
} }
| { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string } | { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string }
| { kind: 'counts'; title: string; measure: string; catalog: Catalog; axis: string } | {
kind: 'counts' | 'sex-counts';
title: string;
measure: string;
catalog: Catalog;
axis: string;
}
| { kind: 'sankey' | 'sex-bars' | 'alterations'; title: string; measure: string }
| { | {
kind: 'age-stack' | 'age-share'; kind: 'age-stack' | 'age-share';
title: string; title: string;
measure: string; measure: string;
/** the numerator's and the rest's names (stack), or the axis (share) */
names: [string, string]; names: [string, string];
} }
| { | {
@@ -57,9 +51,7 @@ export type FigureSpec =
measure: string; measure: string;
stratum: string; stratum: string;
rows: Category[]; rows: Category[];
/** each row in its category's colour (else all rose) */
colored?: boolean; colored?: boolean;
/** the categories (of the measure) that count as a positive */
positive: string[]; positive: string[];
axis: string; axis: string;
}; };
@@ -73,14 +65,14 @@ export interface Category {
export interface Catalog { export interface Catalog {
groups: { id: string; label: string; color: string }[]; groups: { id: string; label: string; color: string }[];
categories: Category[]; categories: Category[];
/** categories drawn faded (not the ones the figure is about) */
faded?: string[]; faded?: string[];
} }
const TEA_ALTERATIONS_VALIDADAS = false;
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = { const CYTOLOGY: Catalog = {
groups: [ groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE }, { id: 'normal', label: 'Sin anomalía', color: OLIVE },
@@ -96,7 +88,6 @@ const CYTOLOGY: Catalog = {
], ],
}; };
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = { const BIOPSY: Catalog = {
groups: [ groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE }, { id: 'low', label: 'Menor que LIEAG', color: OLIVE },
@@ -122,7 +113,6 @@ const CAMA_DAYS = {
}; };
const PENDING = 'Indicador no publicado en el catálogo institucional.'; const PENDING = 'Indicador no publicado en el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = { const BIRADS: Catalog = {
groups: [], groups: [],
categories: [ categories: [
@@ -166,7 +156,7 @@ export const PAGES: Record<string, Page> = {
kind: 'grid', kind: 'grid',
figures: [ figures: [
{ {
kind: 'counts', kind: 'sex-counts',
title: 'Pacientes evaluados por resultado diagnóstico', title: 'Pacientes evaluados por resultado diagnóstico',
measure: 'M23_PACIENTES_EVALUADOS', measure: 'M23_PACIENTES_EVALUADOS',
axis: 'Conteo (paciente)', axis: 'Conteo (paciente)',
@@ -197,29 +187,9 @@ export const PAGES: Record<string, Page> = {
names: ['% de pacientes sin EEG', ''], names: ['% de pacientes sin EEG', ''],
}, },
{ {
kind: 'counts', kind: 'sankey',
title: 'Casos por estatus', title: 'Casos por estatus',
measure: 'M28_CASOS_POR_ESTADO', measure: 'M28_CASOS_POR_ESTADO',
axis: 'Conteo (paciente)',
catalog: {
groups: [],
categories: [
{ code: 'mchat_only', label: 'Solo M-CHAT', color: '#B8433A', group: '' },
{
code: 'psychology',
label: 'Hasta evaluación psicológica',
color: '#42C29C',
group: '',
},
{
code: 'neuropediatrics',
label: 'Hasta evaluación neuropediátrica',
color: '#7184A2',
group: '',
},
{ code: 'eeg', label: 'Con EEG', color: OLIVE, group: '' },
],
},
}, },
{ {
kind: 'counts', kind: 'counts',
@@ -235,6 +205,20 @@ export const PAGES: Record<string, Page> = {
], ],
}, },
}, },
{
kind: 'sex-bars',
title: 'Prevalencia registrada de TEA',
measure: 'M31_PREVALENCIA',
},
...(TEA_ALTERATIONS_VALIDADAS
? ([
{
kind: 'alterations',
title: 'Porcentaje de EEG normal y anormal',
measure: 'M30_RESULTADO_EEG',
},
] satisfies FigureSpec[])
: []),
], ],
}, },
], ],
@@ -429,24 +413,17 @@ export const PAGES: Record<string, Page> = {
}, },
}; };
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
export interface HistoryPanel { export interface HistoryPanel {
title: string; title: string;
measure: string; measure: string;
kind: 'stack' | 'percent' | 'median'; kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[]; series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string; axis?: string;
group?: string; group?: string;
} }
export interface History { interface History {
panels: HistoryPanel[]; panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string; line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number; months?: number;
} }
@@ -595,10 +572,15 @@ export const HISTORY: Record<string, History> = {
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO', measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [ stack(
'Pacientes evaluados por resultado diagnóstico',
'M23_PACIENTES_EVALUADOS',
'Pacientes',
[
['confirmed', 'Diagnóstico confirmado', '#A8C243'], ['confirmed', 'Diagnóstico confirmado', '#A8C243'],
['in_process', 'En proceso', '#B8433A'], ['in_process', 'En proceso', '#B8433A'],
]), ],
),
{ {
title: 'Porcentaje de confirmación diagnóstica', title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO', measure: 'M24_CONFIRMACION_DIAGNOSTICO',
@@ -614,7 +596,7 @@ export const HISTORY: Record<string, History> = {
measure: 'M22_DIAGNOSTICADOS_SIN_EEG', measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
kind: 'percent', kind: 'percent',
}, },
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [ stack('Casos por estatus', 'M28_CASOS_POR_ESTADO', 'Casos', [
['mchat_only', 'Solo M-CHAT', '#B8433A'], ['mchat_only', 'Solo M-CHAT', '#B8433A'],
['psychology', 'Hasta evaluación psicológica', '#42C29C'], ['psychology', 'Hasta evaluación psicológica', '#42C29C'],
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'], ['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
@@ -625,6 +607,15 @@ export const HISTORY: Record<string, History> = {
['bad', 'No aceptable', '#B8433A'], ['bad', 'No aceptable', '#B8433A'],
['not_analyzed', 'Sin analizar', GREY], ['not_analyzed', 'Sin analizar', GREY],
]), ]),
{
title: 'Porcentaje de EEG normal y anormal',
measure: 'M30_RESULTADO_EEG',
kind: 'percent',
},
stack('Prevalencia registrada de TEA', 'M31_PREVALENCIA', 'Niños', [
['confirmed', 'Diagnóstico confirmado', OLIVE],
['in_population', 'Sin diagnóstico confirmado', GREY],
]),
], ],
}, },
}; };
-6
View File
@@ -5,8 +5,6 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
/** A search box's text as FHIR Patient search parameters: one word with a digit is an
* identifier (a CURP or a record number); anything else is her name. */
export function patientSearch(text: string): { name?: string; identifier?: string } { export function patientSearch(text: string): { name?: string; identifier?: string } {
const t = text.trim(); const t = text.trim();
if (!t) return {}; if (!t) return {};
@@ -15,8 +13,6 @@ export function patientSearch(text: string): { name?: string; identifier?: strin
const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase(); const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
/** Whether a row matches the search in the browser (lists loaded whole): each word starts a
* word of one of its texts (a name, an identifier, the pseudonymous id). */
export function matchesSearch(text: string, texts: (string | undefined)[]): boolean { export function matchesSearch(text: string, texts: (string | undefined)[]): boolean {
const words = fold(text).split(/\s+/).filter(Boolean); const words = fold(text).split(/\s+/).filter(Boolean);
if (!words.length) return true; if (!words.length) return true;
@@ -24,7 +20,6 @@ export function matchesSearch(text: string, texts: (string | undefined)[]): bool
return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w)))); return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w))));
} }
/** "Buscar paciente": applied on Enter or the search button, cleared with the cross. */
@Component({ @Component({
selector: 'app-patient-search', selector: 'app-patient-search',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule], imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
@@ -65,7 +60,6 @@ export function matchesSearch(text: string, texts: (string | undefined)[]): bool
`, `,
}) })
export class PatientSearch { export class PatientSearch {
/** The search as applied. */
readonly value = model(''); readonly value = model('');
readonly searched = output<string>(); readonly searched = output<string>();
protected readonly draft = signal(''); protected readonly draft = signal('');
-4
View File
@@ -16,9 +16,6 @@ const IMPROVEMENT: Record<string, string> = {
}; };
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' }; const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
* indicator opening to what it is (how it scores, which way is better, its periods and
* strata). */
@Component({ @Component({
selector: 'app-tab-definiciones', selector: 'app-tab-definiciones',
template: ` template: `
@@ -124,7 +121,6 @@ export class TabDefiniciones {
protected readonly domainName = computed( protected readonly domainName = computed(
() => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(), () => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(),
); );
/** The periodicities any of its indicators admits. */
protected readonly available = computed(() => protected readonly available = computed(() =>
[...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p), [...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p),
); );

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