diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 5bbe1c2..659ded8 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -109,14 +109,25 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF', }) => { const problems = watch(page); 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', + 'Vista previa', + ]); + await page.getByRole('combobox', { name: 'Modo' }).click(); + await page.getByRole('option', { name: 'Sync' }).click(); await expect(page.getByRole('status').filter({ hasText: 'Disponible' })).toBeVisible(); 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(); - const monitor = page.locator('app-gobernanza > section > section app-run-monitor'); + const monitor = page.locator('app-governance-models app-run-monitor'); await page.getByRole('button', { name: 'Analizar EEG' }).click(); await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible(); await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 }); @@ -152,7 +163,8 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF', await dialog.getByRole('button', { name: 'Cerrar' }).click(); const bundles = page.locator('app-governance-bundles'); - await bundles.getByLabel('Versiones').selectOption('all'); + await bundles.getByRole('combobox', { name: 'Versiones' }).click(); + await page.getByRole('option', { name: 'Todas' }).click(); await bundles.getByRole('button', { name: 'Exportar bundle' }).click(); await expect(bundles.getByRole('alert')).toContainText('nothing to export'); expect(problems.filter((p) => !p.includes('409'))).toEqual([]); diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index a41e5ec..6dcd9f6 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -16,8 +16,8 @@ export const routes: Routes = [ { path: 'indicadores/tea/pacientes/:id/riesgo', canActivate: [domainAllowed], - data: { domain: 'tea' }, - loadComponent: () => import('./paciente/tea-patient').then((m) => m.TeaRisk), + data: { domain: 'tea', risk: true }, + loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente), }, { path: 'indicadores/:domain/pacientes/:id', diff --git a/src/app/gobernanza/bundles.ts b/src/app/gobernanza/bundles.ts index f54ad27..749c67f 100644 --- a/src/app/gobernanza/bundles.ts +++ b/src/app/gobernanza/bundles.ts @@ -2,6 +2,9 @@ import { HttpErrorResponse } from '@angular/common/http'; import { Component, inject, input, model, output, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; import { Api } from '../api/api'; import { exportModels, type ExportModels$Params } from '../api/fn/models/export-models'; import { importModels } from '../api/fn/models/import-models'; @@ -45,19 +48,19 @@ export function download(blob: Blob, filename: string): void { @Component({ selector: 'app-governance-bundles', - imports: [FormsModule, MatButtonModule], + imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule], template: ` -
-

Bundles

+
+

Bundles

- + + Versiones + + En producción + Últimas + Todas + +
@if (exportedHash()) { @@ -66,9 +69,28 @@ export function download(blob: Blob, filename: string): void {

}
- - - + @for (file of zipFiles(); track $index) { + {{ file.name }} + } + + SHA-256 esperado + + +
@@ -85,6 +107,7 @@ export class Bundles { readonly started = output(); protected readonly selection = signal>('champion'); protected readonly exportedHash = signal(''); + protected readonly zipFiles = signal(null); protected readonly hash = signal(''); protected readonly message = signal(''); protected readonly exporting = signal(false); @@ -125,6 +148,7 @@ export class Bundles { }), ); input.value = ''; + this.zipFiles.set(null); if (domain === this.domain()) this.started.emit(run_id); } catch (error) { this.message.set(errorText(error)); diff --git a/src/app/gobernanza/execution.spec.ts b/src/app/gobernanza/execution.spec.ts index d762293..1777c88 100644 --- a/src/app/gobernanza/execution.spec.ts +++ b/src/app/gobernanza/execution.spec.ts @@ -29,9 +29,13 @@ describe('execution', () => { expect(fixture.componentInstance.execution()).toEqual({ mode: 'local', scheduler: null }); expect(invoke).toHaveBeenCalledWith(executionHealth, { mode: 'local', scheduler: null }); - const mode: HTMLSelectElement = fixture.nativeElement.querySelector('select'); - mode.value = 'remote'; - mode.dispatchEvent(new Event('change')); + const trigger: HTMLElement = fixture.nativeElement.querySelector('.mat-mdc-select-trigger'); + trigger.click(); + fixture.detectChanges(); + const remote = Array.from(document.querySelectorAll('mat-option')).find( + (option) => option.textContent?.trim() === 'Remoto', + ); + remote!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); diff --git a/src/app/gobernanza/execution.ts b/src/app/gobernanza/execution.ts index 716fdd6..40bb2ab 100644 --- a/src/app/gobernanza/execution.ts +++ b/src/app/gobernanza/execution.ts @@ -1,5 +1,9 @@ import { DOCUMENT } from '@angular/common'; 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 { executionHealth } from '../api/fn/execution/execution-health'; import { executionOptions } from '../api/fn/execution/execution-options'; @@ -8,28 +12,30 @@ import type { Health } from '../api/models/health'; @Component({ selector: 'app-execution', + imports: [MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule], template: ` -
-

Ejecución

+
+

Ejecución

@if (options.hasValue()) { - + + Modo + + Sync + Local + Remoto + + @if (choice().mode === 'remote') { - + @for (host of options.value().schedulers; track host) { @@ -52,7 +58,9 @@ import type { Health } from '../api/models/health'; }

@if (h.dashboard_url && h.dashboard_ok !== false) { - Panel de Dask + Panel de Dask } } @else if (health.error() || options.error()) {

No se pudo consultar la ejecución.

diff --git a/src/app/gobernanza/gobernanza.html b/src/app/gobernanza/gobernanza.html index 8a17bcb..11281d9 100644 --- a/src/app/gobernanza/gobernanza.html +++ b/src/app/gobernanza/gobernanza.html @@ -1,305 +1,44 @@

Gobernanza de modelos

+

Administra la ejecución, las versiones y el entrenamiento por dominio.

- - -
-

Modelos

-
- - - @if (domain() === 'tea') { - - } - -
- @if (training(); as name) { - - } +
+ + + - @if (run(); as current) { -
-

{{ current.label }}

- -
+ @if (domain() === 'tea') { + + } - @if (message()) { -

{{ message() }}

- } - - @if (models.isLoading()) { -

Cargando modelos…

- } @else if (models.error(); as error) { -

{{ errorText(error) }}

- } @else if (!models.hasValue() || !models.value().length) { -

Este dominio todavía no tiene modelos entrenados.

- } - @for (m of models.hasValue() ? models.value() : []; track m.name) { -
-

{{ m.title }}

- - - - - - - - - - - - - - @for (v of m.versions; track v.version) { - - - - - - - - - } - -
VersiónCreadaEntrenamiento / pruebaInformesValidación clínicaComprobaciones y linaje
- v{{ v.version }} {{ v.status }} - {{ v.created | date: 'yyyy-MM-dd HH:mm' }} - {{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }} - - @for (report of v.reports; track report) { - - } - @if (v.reports.includes('interpretability')) { - - } - - @if (!v.reports.includes('clinical_validation')) { - - } @else { - Agregada - } - - - -
-
- } - - @if (chosen(); as version) { -
-

Interpretabilidad · {{ version.name }} v{{ version.version }}

- @if (feature(); as current) { - @if (ageFeatures().length > 1) { - - } - - } - @if (report.error() || band.error() || analysed.error(); as error) { -

{{ errorText(error) }}

- } - @for (f of figures(); track f.title) { -

{{ f.title }}

- - } @empty { - @if (report.isLoading() || band.isLoading()) { -

Cargando…

- } @else if (!report.error() && !band.error()) { -

Este informe no tiene gráficas.

- } - } -
- } -
- - @if (domain() === 'tea') { - - } - - - @if (checksFor(); as key) { -

Comprobaciones · {{ key.name }} v{{ key.version }}

- @if (checks.hasValue()) { - @let details = checks.value(); - @let actions = checkActions(details); -
    - @for (check of details.checks; track check.report) { -
  • - {{ reportNames[check.report] ?? check.report }} · - {{ check.present ? 'Presente' : 'Falta' }} -
  • - } -
- - - } @else if (checks.error(); as error) { -

{{ errorText(error) }}

- } @else { -

Cargando…

- } - @if (message()) { -

{{ message() }}

- } - } -
-
- - - @if (lineageFor(); as key) { -

Linaje · {{ key.name }} v{{ key.version }}

- @if (lineage.hasValue()) { - @let details = lineage.value(); -

Parámetros

-
- @for (entry of details.params | keyvalue; track entry.key) { -
{{ entry.key }}
-
{{ entry.value }}
- } -
-

Métricas

-
- @for (entry of details.metrics | keyvalue; track entry.key) { -
{{ entry.key }}
-
{{ entry.value }}
- } -
-

Etiquetas

-
- @for (entry of details.tags | keyvalue; track entry.key) { -
{{ entry.key }}
-
{{ entry.value }}
- } -
- @if (details.imported; as imported) { -

Importado de

-
- @for (entry of imported | keyvalue; track entry.key) { -
{{ entry.key }}
-
{{ entry.value }}
- } -
- } - } @else if (lineage.error(); as error) { -

{{ errorText(error) }}

- } @else { -

Cargando…

- } - } -
-
- - -

Promover candidatas

-
    - @for (candidate of candidates(); track candidate.name) { -
  • {{ candidate.name }} v{{ candidate.version }}
  • - } -
- -
-
+
diff --git a/src/app/gobernanza/gobernanza.scss b/src/app/gobernanza/gobernanza.scss index 03405bc..b7a501a 100644 --- a/src/app/gobernanza/gobernanza.scss +++ b/src/app/gobernanza/gobernanza.scss @@ -1,56 +1,20 @@ :host { display: block; } -h1 { - text-align: center; -} .domains { display: flex; - justify-content: center; - gap: var(--space-4); + flex-wrap: wrap; + gap: var(--space-3); margin-bottom: var(--space-4); } .domains a.active { font-weight: 600; text-decoration: underline; } -.actions { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-3); - margin-bottom: var(--space-4); +.sections { + display: grid; + gap: var(--space-4); } -.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; -} -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); +.sections > * { + min-width: 0; } diff --git a/src/app/gobernanza/gobernanza.ts b/src/app/gobernanza/gobernanza.ts index cbe4192..c1af590 100644 --- a/src/app/gobernanza/gobernanza.ts +++ b/src/app/gobernanza/gobernanza.ts @@ -1,79 +1,28 @@ -import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common'; -import { Component, computed, effect, inject, input, resource, signal } from '@angular/core'; -import { FormsModule } from '@angular/forms'; +import { Component, computed, inject, input, resource } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { RouterLink } from '@angular/router'; 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 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 { Plot } from '../plot'; -import { Bundles, download } from './bundles'; +import { Bundles } from './bundles'; import { Execution } from './execution'; -import { interpretabilityFigures, studyPoints, type Centile } from './figures'; -import { errorText, RunMonitor } from './run-monitor'; +import { Models } from './models'; +import { EegPreview } from './tea/preview'; import { EegStudies } from './tea/studies'; import { Training } from './training'; -const REPORTS: Record = { - 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; - metrics: Record; - tags: Record; - imported: Record | null; -} - -export function checkActions(checks: Checks) { - return { promote: checks.promotable, retire: checks.status !== 'champion' }; -} - @Component({ selector: 'app-gobernanza', imports: [ - DatePipe, - DecimalPipe, - KeyValuePipe, - FormsModule, MatButtonModule, RouterLink, - Plot, - Bundles, Execution, - RunMonitor, - EegStudies, + Models, Training, + Bundles, + EegStudies, + EegPreview, ], templateUrl: './gobernanza.html', styleUrl: './gobernanza.scss', @@ -82,322 +31,6 @@ export class Gobernanza { private readonly api = inject(Api); readonly domain = input.required(); protected readonly domainKey = computed(() => this.domain() as Domain); - protected readonly execution = signal(undefined); protected readonly labels = DOMAINS as Record; - protected readonly reportNames = REPORTS; - protected readonly errorText = errorText; protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); - protected readonly refreshed = signal(0); - - protected refresh(): void { - this.refreshed.update((value) => value + 1); - } - 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(undefined); - protected readonly checksFor = signal(undefined); - protected readonly lineageFor = signal(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([]); - 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(() => { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks; - } - - private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise { - 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(); - } } diff --git a/src/app/gobernanza/models.html b/src/app/gobernanza/models.html new file mode 100644 index 0000000..9da2bef --- /dev/null +++ b/src/app/gobernanza/models.html @@ -0,0 +1,279 @@ +
+

Modelos

+
+ + + @if (domain() === 'tea') { + + } + +
+ @if (run(); as current) { +
+

{{ current.label }}

+ +
+ } + @if (message()) { +

{{ message() }}

+ } + + @if (models.isLoading()) { +

Cargando modelos…

+ } @else if (models.error(); as error) { +

{{ errorText(error) }}

+ } @else if (!models.hasValue() || !models.value().length) { +

Este dominio todavía no tiene modelos entrenados.

+ } + @for (m of models.hasValue() ? models.value() : []; track m.name) { +
+

{{ m.title }}

+ + + + + + + + + + + + + + @for (v of m.versions; track v.version) { + + + + + + + + + } + +
VersiónCreadaEntrenamiento / pruebaInformesValidación clínicaComprobaciones y linaje
+ v{{ v.version }} {{ v.status }} + {{ v.created | date: 'yyyy-MM-dd HH:mm' }} + {{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }} + + @for (report of v.reports; track report) { + + } + @if (v.reports.includes('interpretability')) { + + } + + @if (!v.reports.includes('clinical_validation')) { + + + } @else { + Agregada + } + + + +
+
+ } + + @if (chosen(); as version) { +
+

Interpretabilidad · {{ version.name }} v{{ version.version }}

+ @if (feature(); as current) { + @if (ageFeatures().length > 1) { + + Característica + + @for (feature of ageFeatures(); track feature) { + {{ feature }} + } + + + } + Superponer estudios + } + @if (report.error() || band.error() || analysed.error(); as error) { +

{{ errorText(error) }}

+ } + @for (f of figures(); track f.title) { +

{{ f.title }}

+ + } @empty { + @if (report.isLoading() || band.isLoading()) { +

Cargando…

+ } @else if (!report.error() && !band.error()) { +

Este informe no tiene gráficas.

+ } + } +
+ } + + + @if (checksFor(); as key) { +

Comprobaciones · {{ key.name }} v{{ key.version }}

+ @if (checks.hasValue()) { + @let details = checks.value(); + @let actions = checkActions(details); +
    + @for (check of details.checks; track check.report) { +
  • + {{ reportNames[check.report] ?? check.report }} · + {{ check.present ? 'Presente' : 'Falta' }} +
  • + } +
+ + + } @else if (checks.error(); as error) { +

{{ errorText(error) }}

+ } @else { +

Cargando…

+ } + @if (message()) { +

{{ message() }}

+ } + } +
+
+ + + @if (lineageFor(); as key) { +

Linaje · {{ key.name }} v{{ key.version }}

+ @if (lineage.hasValue()) { + @let details = lineage.value(); +

Parámetros

+
+ @for (entry of details.params | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+

Métricas

+
+ @for (entry of details.metrics | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+

Etiquetas

+
+ @for (entry of details.tags | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+ @if (details.imported; as imported) { +

Importado de

+
+ @for (entry of imported | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+ } + } @else if (lineage.error(); as error) { +

{{ errorText(error) }}

+ } @else { +

Cargando…

+ } + } +
+
+ + +

Promover candidatas

+
    + @for (candidate of candidates(); track candidate.name) { +
  • {{ candidate.name }} v{{ candidate.version }}
  • + } +
+ +
+
+
diff --git a/src/app/gobernanza/models.scss b/src/app/gobernanza/models.scss new file mode 100644 index 0000000..8bb0aad --- /dev/null +++ b/src/app/gobernanza/models.scss @@ -0,0 +1,36 @@ +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); + margin-bottom: var(--space-4); +} +.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); +} +dialog form { + margin-top: var(--space-3); +} diff --git a/src/app/gobernanza/gobernanza.spec.ts b/src/app/gobernanza/models.spec.ts similarity index 93% rename from src/app/gobernanza/gobernanza.spec.ts rename to src/app/gobernanza/models.spec.ts index c801c48..a7e01ab 100644 --- a/src/app/gobernanza/gobernanza.spec.ts +++ b/src/app/gobernanza/models.spec.ts @@ -1,4 +1,4 @@ -import { checkActions } from './gobernanza'; +import { checkActions } from './models'; describe('version checks', () => { it('enables promotion only when the API says the version is promotable', () => { diff --git a/src/app/gobernanza/models.ts b/src/app/gobernanza/models.ts new file mode 100644 index 0000000..be9cb42 --- /dev/null +++ b/src/app/gobernanza/models.ts @@ -0,0 +1,410 @@ +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 { 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 type { Domain } from '../api/models/domain'; +import type { Execution as Choice } from '../api/models/execution'; +import type { Run } from '../api/models/run'; +import { Plot } from '../plot'; +import { download } from './bundles'; +import { interpretabilityFigures, studyPoints, type Centile } from './figures'; +import { errorText, RunMonitor } from './run-monitor'; + +const REPORTS: Record = { + 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; + metrics: Record; + tags: Record; + imported: Record | 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(); + readonly execution = input(); + readonly trainingRequested = output(); + 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(undefined); + protected readonly checksFor = signal(undefined); + protected readonly lineageFor = signal(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([]); + 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(() => { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 start(kind: 'score' | 'analyze'): Promise { + const domain = this.domain(); + 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.domain()) + 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 { + 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 { + return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks; + } + + private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise { + 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(); + } +} diff --git a/src/app/gobernanza/tea/preview.ts b/src/app/gobernanza/tea/preview.ts index e174758..afe7a60 100644 --- a/src/app/gobernanza/tea/preview.ts +++ b/src/app/gobernanza/tea/preview.ts @@ -2,6 +2,8 @@ import { KeyValuePipe } from '@angular/common'; import { Component, inject, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; import { Api } from '../../api/api'; import { previewStatus } from '../../api/fn/preview/preview-status'; import { startPreview } from '../../api/fn/preview/start-preview'; @@ -12,15 +14,50 @@ import { downloadPreviewPdf } from './preview-pdf'; @Component({ selector: 'app-eeg-preview', - imports: [FormsModule, KeyValuePipe, MatButtonModule, RunMonitor], + imports: [ + FormsModule, + KeyValuePipe, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + RunMonitor, + ], template: ` -
-

Vista previa

+
+

Vista previa

- - - - + + + @for (file of edfFiles(); track $index) { + {{ file.name }} + } + + + @for (file of adosFiles(); track $index) { + {{ file.name }} + } + + Fecha de nacimiento + + +
@if (error()) {

{{ error() }}

@@ -151,6 +188,8 @@ import { downloadPreviewPdf } from './preview-pdf'; }) export class EegPreview { private readonly api = inject(Api); + protected readonly edfFiles = signal(null); + protected readonly adosFiles = signal(null); protected readonly busy = signal(false); protected readonly error = signal(''); protected readonly runId = signal(''); diff --git a/src/app/gobernanza/tea/studies.html b/src/app/gobernanza/tea/studies.html index ce0881f..cb79158 100644 --- a/src/app/gobernanza/tea/studies.html +++ b/src/app/gobernanza/tea/studies.html @@ -1,29 +1,46 @@ -
-

Estudios EEG

+
+

Estudios EEG

- + + Alcance + + Pendientes + Primeros N + Por ID + + @if (mode() === 'first_n') { - + + Número de estudios + + } @if (mode() === 'ids') { - + + ID de estudios (uno por línea) + + }
- - + + + @for (file of selectedFiles(); track $index) { + {{ file.name }} + } +
@if (error()) {

{{ error() }}

@@ -31,7 +48,6 @@ @if (runId(); as id) { } -

Resumen

@if (summary.hasValue()) {
@@ -81,7 +97,12 @@ @for (e of eegs.hasValue() ? eegs.value() : []; track e.id) { - diff --git a/src/app/gobernanza/tea/studies.ts b/src/app/gobernanza/tea/studies.ts index dd2b165..78f8098 100644 --- a/src/app/gobernanza/tea/studies.ts +++ b/src/app/gobernanza/tea/studies.ts @@ -3,6 +3,9 @@ import { HttpErrorResponse } from '@angular/common/http'; import { Component, inject, input, output, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; import { Api } from '../../api/api'; import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs'; import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary'; @@ -15,7 +18,6 @@ import { runHistory } from '../../api/fn/runs/run-history'; import type { Execution } from '../../api/models/execution'; import type { Scope } from '../../api/models/scope'; import { errorText, RunMonitor } from '../run-monitor'; -import { EegPreview } from './preview'; @Component({ selector: 'app-eeg-studies', @@ -25,8 +27,10 @@ import { EegPreview } from './preview'; KeyValuePipe, FormsModule, MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule, RunMonitor, - EegPreview, ], templateUrl: './studies.html', }) @@ -94,6 +98,7 @@ export class EegStudies { protected readonly mode = signal>('pending'); protected readonly count = signal(null); protected readonly ids = signal(''); + protected readonly selectedFiles = signal(null); protected readonly busy = signal(false); protected readonly error = signal(''); protected readonly runId = signal(''); @@ -129,6 +134,7 @@ export class EegStudies { 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 = ''; + this.selectedFiles.set(null); return run; } catch (error) { if (error instanceof HttpErrorResponse && error.status === 404) { diff --git a/src/app/gobernanza/training.ts b/src/app/gobernanza/training.ts index 836d350..9eb881e 100644 --- a/src/app/gobernanza/training.ts +++ b/src/app/gobernanza/training.ts @@ -1,7 +1,21 @@ import { HttpErrorResponse } from '@angular/common/http'; -import { Component, inject, input, model, output, resource, signal } from '@angular/core'; +import { + Component, + ElementRef, + inject, + input, + linkedSignal, + model, + output, + resource, + signal, + viewChild, +} from '@angular/core'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; import { FormlyForm, provideFormlyCore } from '@ngx-formly/core'; import { FormlyJsonschema } from '@ngx-formly/core/json-schema'; import { withFormlyMaterial } from '@ngx-formly/material'; @@ -65,19 +79,29 @@ function allowedFile(file: File, allowed: string[]): boolean { @Component({ selector: 'app-governance-training', - imports: [FormsModule, ReactiveFormsModule, FormlyForm, MatButtonModule], + imports: [ + FormsModule, + ReactiveFormsModule, + FormlyForm, + MatButtonModule, + MatCheckboxModule, + MatFormFieldModule, + MatInputModule, + ], providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])], template: ` -
-

{{ name() === 'all' ? 'Entrenar modelos' : 'Reentrenar ' + name() }}

+
+

Entrenamiento

+ @if (name() !== 'all') { +

Reentrenar {{ name() }}

+ } @if (config.hasValue()) { @let form = config.value();
@if (domain() === 'tea') { - Promover al terminar } + + + @for (file of selectedFiles(); track $index) { + {{ file.name }} + } + } @else if (inputs.error(); as error) {

{{ errorText(error) }}

@@ -128,6 +168,7 @@ function allowedFile(file: File, allowed: string[]): boolean { `, }) export class Training { + private readonly heading = viewChild.required>('heading'); private readonly api = inject(Api); private readonly jsonschema = inject(FormlyJsonschema); readonly domain = input.required(); @@ -142,6 +183,7 @@ export class Training { const fields = [ this.jsonschema.toFieldConfig(schema, { map: (field, source) => { + field.props = { ...field.props, appearance: 'outline' }; if (source.format === 'date') { field.props = { ...field.props, type: 'date' }; } @@ -184,11 +226,19 @@ export class Training { }, }); readonly busy = model(false); + protected readonly selectedFiles = linkedSignal({ + source: () => (this.inputs.hasValue() ? this.inputs.value() : undefined), + computation: (): FileList | null => null, + }); protected readonly uploading = signal(false); protected readonly message = signal(''); - protected readonly autoPromote = signal(false); + protected readonly autoPromote = linkedSignal({ source: this.domain, computation: () => false }); protected readonly errorText = errorText; + focus(): void { + this.heading().nativeElement.focus(); + } + protected async start(model: TrainingConfig['defaults']): Promise { if (this.busy() || this.disabled()) return; this.busy.set(true); @@ -206,11 +256,11 @@ export class Training { ...(name === 'all' ? {} : { models: [name] }), }, }); - this.started.emit({ id: run_id, autoPromote }); + if (domain === this.domain()) this.started.emit({ id: run_id, autoPromote }); } catch (error) { - this.message.set(errorText(error)); + if (domain === this.domain()) this.message.set(errorText(error)); } finally { - this.busy.set(false); + if (domain === this.domain()) this.busy.set(false); } } @@ -239,6 +289,7 @@ export class Training { body: { files }, }); input.value = ''; + this.selectedFiles.set(null); this.inputs.reload(); } catch (error) { this.message.set(errorText(error)); diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts index 63069e8..100ccb0 100644 --- a/src/app/indicadores/pages.ts +++ b/src/app/indicadores/pages.ts @@ -619,6 +619,11 @@ export const HISTORY: Record = { ['bad', 'No aceptable', '#B8433A'], ['not_analyzed', 'Sin analizar', GREY], ]), + { + title: 'Porcentaje de EEG con alteraciones', + measure: 'M30_RESULTADO_EEG', + kind: 'percent', + }, ], }, }; diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index a503993..be84a25 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -1,296 +1,368 @@ -@if (domain() === 'tea') { - -} @else { -
- arrow_back Regresar - @if (error()) { - - } @else if (patient(); as p) { -

- {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} -

-
-
-
CURP
-
{{ identity().curp ?? 'Sin dato' }}
-
-
-
Expedientes
-
{{ identity().numbers.join(', ') || 'Sin dato' }}
-
-
-
Fecha de nacimiento
-
{{ p.birthDate ?? 'Sin dato' }}
-
-
-
Sexo
-
- {{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }} -
-
- @if (cama(); as c) { -
-
Grupo de edad
-
{{ c.ageGroup || 'No disponible' }}
-
-
-
Escenario clínico
-
{{ c.scenario }}
-
-
-
Estatus de seguimiento
-
- {{ c.status ?? 'Fuera de la lista (' + c.window + ' meses al ' + c.cutoff + ')' }} -
-
-
-
Prioridad
-
{{ c.priority ?? 'No disponible' }}
-
-
-
Días de mastografía a diagnóstico
-
{{ c.days ?? 'No disponible' }}
-
- } @else { - @if (status()) { +
+ arrow_back Regresar + @if (domain() === 'tea') { + @if (tea.error()) { + + } @else if (tea.value(); as t) { + @if (risk()) { +

Análisis de riesgo TEA

+ @if (t.patient.name?.[0]?.text; as name) { +

{{ name }}

+ } + } @else { +

+ {{ t.patient.name?.[0]?.text ?? 'Paciente' }} + {{ t.patient.id!.slice(0, 10) }} +

+
+ @for (row of teaIdentity(); track $index) {
-
Estatus de seguimiento
-
{{ status() }}
+
{{ row[0] }}
+
{{ row[1] }}
} +
+ } +
+ + @if (risk()) { + Expediente + } @else { + Análisis de riesgo } - @if (p.deceasedDateTime) { +
+ @if (exportError()) { + + } +
+ @for (section of teaSections(); track section.title) { + + @if (risk() && section.title === forestTitle) { + Solo zonas alteradas + } + @if (risk() && section.title === probabilityTitle && t.pairs.length) { + + Par + + @for (pair of t.pairs; track pair.key) { + {{ pair.title }} + } + + + } + + } +
+ } @else { + + } + } @else if (error()) { + + } @else if (patient(); as p) { +

+ {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} +

+
+
+
CURP
+
{{ identity().curp ?? 'Sin dato' }}
+
+
+
Expedientes
+
{{ identity().numbers.join(', ') || 'Sin dato' }}
+
+
+
Fecha de nacimiento
+
{{ p.birthDate ?? 'Sin dato' }}
+
+
+
Sexo
+
+ {{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }} +
+
+ @if (cama(); as c) { +
+
Grupo de edad
+
{{ c.ageGroup || 'No disponible' }}
+
+
+
Escenario clínico
+
{{ c.scenario }}
+
+
+
Estatus de seguimiento
+
+ {{ c.status ?? 'Fuera de la lista (' + c.window + ' meses al ' + c.cutoff + ')' }} +
+
+
+
Prioridad
+
{{ c.priority ?? 'No disponible' }}
+
+
+
Días de mastografía a diagnóstico
+
{{ c.days ?? 'No disponible' }}
+
+ } @else { + @if (status()) {
-
Defunción
-
{{ p.deceasedDateTime }}
+
Estatus de seguimiento
+
{{ status() }}
} -
+ } + @if (p.deceasedDateTime) { +
+
Defunción
+
{{ p.deceasedDateTime }}
+
+ } +
-
- @if (cama(); as c) { - - Mastografía - -

Última mastografía

-
-
-
Categoría BI-RADS
-
{{ c.birads ?? 'No disponible' }}
-
-
-
Fecha
-
{{ c.mammogram ?? 'No disponible' }}
-
-
-
-
- - Histopatología - -

Resultado histopatológico

-
-
-
Resultado
-
{{ c.histology ?? 'No disponible' }}
-
-
-
Fecha de reporte de la biopsia
-
{{ c.biopsy ?? 'No disponible' }}
-
-
-
-
- } - - Historial médico +
+ @if (cama(); as c) { + + Mastografía +

Última mastografía

+
+
+
Categoría BI-RADS
+
{{ c.birads ?? 'No disponible' }}
+
+
+
Fecha
+
{{ c.mammogram ?? 'No disponible' }}
+
+
+
+
+ + Histopatología + +

Resultado histopatológico

+
+
+
Resultado
+
{{ c.histology ?? 'No disponible' }}
+
+
+
Fecha de reporte de la biopsia
+
{{ c.biopsy ?? 'No disponible' }}
+
+
+
+
+ } + + Historial médico + + + + + + + + + + + @for (h of history(); track $index) { + + + + + + } @empty { + + + + } + +
FechaTipoDetalle
{{ h.date }}{{ h.kind }} + {{ h.text }} + @if (h.code && h.code !== h.text) { + ({{ h.code }}) + } +
Sin registros.
+
+
+ + + Pruebas y resultados + + + + + + + + + + + + @for (t of tests(); track $index) { + + + + + + + } @empty { + + + + } + +
TomaEstudioReporteResultados
{{ t.date }}{{ t.kind }}{{ t.reported ?? 'Pendiente' }}{{ t.results.join(' · ') || '—' }}
Sin estudios.
+
+
+ + + Riesgos y recomendaciones + + @if (models().length) { - - - + + + + + - @for (h of history(); track $index) { - - - - - - } @empty { - - - + @for (m of models(); track m.model) { + @for (p of m.predictions; track p.years) { + + + + + + + + } }
FechaTipoDetalleModeloFecha índiceHorizonteProbabilidadIC 95 %
{{ h.date }}{{ h.kind }} - {{ h.text }} - @if (h.code && h.code !== h.text) { - ({{ h.code }}) - } -
Sin registros.
{{ $first ? m.text : '' }}{{ $first ? m.index : '' }}{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-2' }} % + @if (p.low !== undefined) { + {{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }} + % + } @else { + — + } +
-
-
+ + } @else { +

Sin evaluación de un modelo en producción.

+ } + + - - Pruebas y resultados - - - - - - - - - - - - @for (t of tests(); track $index) { - - - - - - - } @empty { - - - - } - -
TomaEstudioReporteResultados
{{ t.date }}{{ t.kind }}{{ t.reported ?? 'Pendiente' }}{{ t.results.join(' · ') || '—' }}
Sin estudios.
-
-
- - + @if (recurrenceModel(); as rm) { + Riesgos y recomendacionesPronóstico y recomendaciones - @if (models().length) { - - +

Análisis de recurrencia

+
+ + + + + + + + @for (p of rm.predictions; track p.years) { - - - - - + + - - - @for (m of models(); track m.model) { - @for (p of m.predictions; track p.years) { - - - - - - - - } - } - -
HorizonteProbabilidad de recurrencia
ModeloFecha índiceHorizonteProbabilidadIC 95 %{{ p.years | number: '1.0-1' }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-1' }} %
{{ $first ? m.text : '' }}{{ $first ? m.index : '' }}{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-2' }} % - @if (p.low !== undefined) { - {{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }} - % - } @else { - — - } -
- - } @else { -

Sin evaluación de un modelo en producción.

+ } + + + @if (recurrence.isLoading()) { + + } @else if (recurrence.value(); as s) { +

Escenario clínico de la paciente

+
    + @for (name of s.scenarios; track name) { +
  • {{ name }}
  • + } +
+ @for (f of s.figures; track f.title) { +

{{ f.title }}

+ + } @empty { +

+ Sus escenarios no tienen recaídas suficientes para trazar curvas. +

+ } + + } @else if (recurrence.error()) { + }
- - - @if (recurrenceModel(); as rm) { - - Pronóstico y recomendaciones - -

Análisis de recurrencia

- - - - - - - - - @for (p of rm.predictions; track p.years) { - - - - - } - -
HorizonteProbabilidad de recurrencia
{{ p.years | number: '1.0-1' }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-1' }} %
- @if (recurrence.isLoading()) { - - } @else if (recurrence.value(); as s) { -

Escenario clínico de la paciente

-
    - @for (name of s.scenarios; track name) { -
  • {{ name }}
  • - } -
- @for (f of s.figures; track f.title) { -

{{ f.title }}

- - } @empty { -

- Sus escenarios no tienen recaídas suficientes para trazar curvas. -

+ } + @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { + + Riesgo de muerte + +

Análisis de supervivencia

+ @if (survival.isLoading()) { + + } @else if (survival.value(); as s) { +

Escenario clínico de la paciente

+
    + @for (name of s.scenarios; track name) { +
  • {{ name }}
  • } - - } @else if (recurrence.error()) { - +
+ @for (f of s.figures; track f.title) { +

{{ f.title }}

+ + } @empty { +

+ Sus escenarios no tienen fallecimientos suficientes para trazar curvas. +

} -
-
- } - @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { - - Riesgo de muerte - -

Análisis de supervivencia

- @if (survival.isLoading()) { - - } @else if (survival.value(); as s) { -

Escenario clínico de la paciente

-
    - @for (name of s.scenarios; track name) { -
  • {{ name }}
  • - } -
- @for (f of s.figures; track f.title) { -

{{ f.title }}

- - } @empty { -

- Sus escenarios no tienen fallecimientos suficientes para trazar curvas. -

- } - - } @else if (survival.error()) { - - } -
-
- } -
- } @else if (loading()) { - - } -
-} + + } @else if (survival.error()) { + + } + + + } + + } @else if (loading()) { + + } +
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index 23a5a44..5ab0ae0 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -18,6 +18,13 @@ margin: 0; } +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + margin-bottom: var(--space-4); +} + .cards { display: grid; gap: var(--space-4); @@ -54,44 +61,6 @@ mat-card-content { } } -.totals { - display: flex; - flex-wrap: wrap; - gap: 16px; -} - -.zones { - margin-top: 12px; -} -.regions { - list-style: none; - margin: 8px 0 0; - padding: 0; - max-width: 420px; - li { - display: flex; - justify-content: space-between; - padding: 4px 8px; - border-bottom: 1px solid var(--mat-sys-outline-variant); - } - li.marked { - font-weight: 600; - color: var(--mat-sys-error); - } -} -tr.chosen td { - background: var(--mat-sys-surface-container); -} - -.relation { - margin-top: 16px; - td small { - display: block; - color: var(--mat-sys-on-surface-variant); - font-size: 0.8em; - } -} - h1 .id { font-size: 14px; font-weight: 400; diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index d8fe8f3..cfdc31b 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -1,8 +1,11 @@ import { DecimalPipe } from '@angular/common'; -import { Component, computed, inject, input, resource } from '@angular/core'; +import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; +import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { RouterLink } from '@angular/router'; import type { Condition, @@ -13,6 +16,7 @@ import type { RiskAssessment, } from 'fhir/r4'; import { Api } from '../api/api'; +import { curve } from '../api/fn/models/curve'; import { readReport$Json } from '../api/fn/models/read-report-json'; import type { Domain } from '../api/models/domain'; import { code, EXT, ext, Fhir, label, resources } from '../fhir'; @@ -22,7 +26,17 @@ import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { Figure, PALETTE, Plot } from '../plot'; import { Loading } from '../loading'; import { Factores, ScenarioFactors } from './factores'; -import { TeaRecord } from './tea-patient'; +import { identityRows, loadTeaPatient, Study } from './tea-data'; +import { ageNorm, Centile } from './tea-figures'; +import { TeaSection } from './tea-section'; +import { + exportTeaPdf, + forestTitle, + probabilityTitle, + recordSections, + riskSections, + Section, +} from './tea-sections'; /** An Observation's value as the screens say it, whatever its type. */ function shown(o: Observation): string { @@ -46,10 +60,13 @@ function shown(o: Observation): string { DecimalPipe, MatButtonModule, MatCardModule, + MatFormFieldModule, MatIconModule, + MatSelectModule, + MatSlideToggleModule, RouterLink, Plot, - TeaRecord, + TeaSection, ], templateUrl: './paciente.html', styleUrl: './paciente.scss', @@ -57,11 +74,13 @@ function shown(o: Observation): string { export class Paciente { private readonly fhir = inject(Fhir); private readonly api = inject(Api); + private readonly host = inject>(ElementRef); readonly domain = input.required(); readonly id = input.required(); /** The follow-up list she was opened from: its window (months) and cut-off. */ readonly ventana = input(); readonly corte = input(); + readonly risk = input(false); private readonly data = resource({ params: () => (this.domain() === 'tea' ? undefined : { domain: this.domain(), id: this.id() }), @@ -345,4 +364,89 @@ export class Paciente { const p = this.patient(); return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : ''; }); + protected readonly tea = resource({ + params: () => (this.domain() === 'tea' ? this.id() : undefined), + loader: ({ params }) => loadTeaPatient(this.fhir, params), + }); + protected readonly norms = resource({ + params: () => (this.risk() || !this.tea.hasValue() ? undefined : this.tea.value().studies), + loader: ({ params }) => this.loadNorms(params), + }); + protected readonly onlyAltered = signal(false); + protected readonly selectedKey = signal(''); + protected readonly selectedPair = computed(() => { + const pairs = this.tea.hasValue() ? this.tea.value().pairs : []; + return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0]; + }); + protected readonly teaIdentity = computed(() => + this.tea.hasValue() ? identityRows(this.tea.value().patient) : [], + ); + protected readonly teaSections = computed(() => { + if (!this.tea.hasValue()) return []; + const patient = this.tea.value(); + return this.risk() + ? riskSections(patient, this.onlyAltered(), this.selectedPair()) + : recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map()); + }); + protected readonly forestTitle = forestTitle; + protected readonly probabilityTitle = probabilityTitle; + protected readonly exporting = signal(false); + protected readonly exportError = signal(false); + + private async loadNorms(studies: Study[]) { + const curves = new Map>(); + const charts = await Promise.all( + studies.flatMap((eeg) => + eeg.metrics.map(async (metric) => { + const model = /^tea\.([^/]+)\/([1-9]\d*)$/.exec(metric.model ?? ''); + if ( + !model || + metric.key === 'paroxysmal_spikes' || + metric.value == null || + eeg.age == null + ) { + return undefined; + } + const [, name, version] = model; + const key = model[0]; + if (!curves.has(key)) { + curves.set( + key, + this.api + .invoke(curve, { domain: 'tea', name, version: Number(version) }) + .then((rows) => rows as Centile[]) + .catch(() => []), + ); + } + const rows = await curves.get(key)!; + if (!rows.some((row) => row.median != null)) return undefined; + return [ + `${eeg.id}|${metric.key}`, + { + title: 'Norma por edad · p5–p95', + figure: ageNorm(rows, metric, eeg.age), + }, + ] as const; + }), + ), + ); + return new Map(charts.filter((chart) => chart !== undefined)); + } + + protected async download(): Promise { + this.exportError.set(false); + this.exporting.set(true); + try { + await exportTeaPdf( + this.risk() ? 'riesgos' : 'seguimiento', + this.risk() ? 'Análisis de riesgo TEA' : 'Expediente TEA', + this.teaSections(), + this.host.nativeElement.querySelectorAll('app-plot .plot'), + ); + } catch { + this.exportError.set(true); + } finally { + this.exporting.set(false); + } + } } diff --git a/src/app/paciente/tea-data.ts b/src/app/paciente/tea-data.ts index 548fb8f..cf9e6a5 100644 --- a/src/app/paciente/tea-data.ts +++ b/src/app/paciente/tea-data.ts @@ -1,5 +1,6 @@ import type { DiagnosticReport, + Identifier, Observation, ObservationComponent, Patient, @@ -7,6 +8,9 @@ import type { } from 'fhir/r4'; import { ados2Component, ados2Groups } from '../ados2'; import { code, ext, Fhir, label, resources } from '../fhir'; +import { CURP } from '../indicadores/follow-up'; + +const NSS = 'https://isssteleon.org/fhir/sid/nss'; const steps: Record = { mchat_only: 'Solo M-CHAT', @@ -81,15 +85,30 @@ function observationValue(o: Observation | ObservationComponent): string { return shown(label(o.valueCodeableConcept) || o.valueString || o.valueInteger); } -export function identity(patient: Patient): string[][] { +export function identityRows(patient: Patient): string[][] { const group = ext(patient, 'tea-age-group')?.valueCode; const step = ext(patient, 'tea-step')?.valueCode; const sex = { female: 'Femenino', male: 'Masculino', other: 'Otro', unknown: '—' }; + const system = (id: Identifier): string | undefined => + id.system === CURP + ? 'CURP' + : id.system === NSS + ? 'NSS' + : id.system?.startsWith('urn:isssteleon:') + ? 'Expediente' + : undefined; + const identifiers = ['Expediente', 'CURP', 'NSS'].flatMap((row) => { + const values = [ + ...new Set( + (patient.identifier ?? []).filter((id) => system(id) === row).map((id) => id.value ?? ''), + ), + ].filter(Boolean); + return values.length ? [[row, values.join(', ')]] : []; + }); return [ - ['Nombre', shown(patient.name?.[0]?.text)], - ...(patient.identifier ?? []).map((id) => [id.type?.text || 'Identificador', shown(id.value)]), - ['Sexo', patient.gender ? sex[patient.gender] : '—'], + ...identifiers, ['Fecha de nacimiento', shown(patient.birthDate)], + ['Sexo', patient.gender ? sex[patient.gender] : '—'], ['Grupo de edad', group && group !== 'no_data' ? `${group} meses` : '—'], ['Paso', shown(steps[step ?? ''] ?? step)], ]; diff --git a/src/app/paciente/tea-patient.spec.ts b/src/app/paciente/tea-patient.spec.ts index 98da9a3..7a97a81 100644 --- a/src/app/paciente/tea-patient.spec.ts +++ b/src/app/paciente/tea-patient.spec.ts @@ -1,15 +1,16 @@ -import { Component, input } from '@angular/core'; -import { TestBed } from '@angular/core/testing'; -import { provideRouter } from '@angular/router'; -import type { Observation } from 'fhir/r4'; -import { describe, expect, it, vi } from 'vitest'; -import { EXT, Fhir } from '../fhir'; -import { Paciente } from './paciente'; -import { loadTeaPatient, Metric, Pair } from './tea-data'; +import type { Observation, Patient } from 'fhir/r4'; +import { describe, expect, it } from 'vitest'; +import { EXT } from '../fhir'; +import { identityRows, Metric, Pair } from './tea-data'; import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures'; -import { TeaRecord, TeaSection } from './tea-patient'; -import { recordSections, teaPdfContent, teaPdfName } from './tea-sections'; - +import { + forestTitle, + probabilityTitle, + recordSections, + riskSections, + teaPdfContent, + teaPdfName, +} from './tea-sections'; const metric: Metric = { key: 'spindles_n2', @@ -38,6 +39,20 @@ const pair: Pair = { reference: 0.2, }; +const centiles = [ + { age_months: 20, p5: 0, median: 1, p95: 2 }, + { age_months: 21, p5: 0.2, median: 1.2, p95: 2.2 }, +]; + +const eeg = { + id: 'eeg-1', + date: '2025-11-30', + age: 20.5, + summary: [], + checks: [], + metrics: [metric], +}; + const ados: Observation = { resourceType: 'Observation', id: 'ados2-child-2025-11-22', @@ -104,14 +119,7 @@ describe('Figuras del paciente TEA', () => { }); it('dibuja los centiles del campeón y el valor observado a la edad del paciente', () => { - const figure = ageNorm( - [ - { age_months: 20, p5: 0, median: 1, p95: 2 }, - { age_months: 21, p5: 0.2, median: 1.2, p95: 2.2 }, - ], - metric, - 20.5, - ); + const figure = ageNorm(centiles, metric, 20.5); expect(figure.data[0]).toMatchObject({ fill: 'toself', y: [2, 2.2, 0.2, 0] }); expect(figure.data[2]).toMatchObject({ mode: 'markers', x: [20.5], y: [1.7] }); }); @@ -128,14 +136,7 @@ describe('Figuras del paciente TEA', () => { }); it('marca la banda de z entre −2 y 2', () => { - const figure = zBars({ - id: 'eeg-1', - date: '2025-11-22', - age: 20.5, - checks: [], - summary: [], - metrics: [metric], - }); + const figure = zBars(eeg); expect(figure.data[0]).toMatchObject({ x: [0.3, 2.4], y: ['Husos N2 · Global', 'Husos N2 · Central'], @@ -152,35 +153,90 @@ describe('Figuras del paciente TEA', () => { }); describe('Expediente TEA', () => { - it('muestra solo los ítems del módulo con dominio, subdominio, código y título', async () => { - const fixture = TestBed.createComponent(TeaSection); - fixture.componentRef.setInput( - 'section', - recordSections(record, new Map()).find((section) => section.title === 'ADOS-2'), - ); - await fixture.whenStable(); - const rows = fixture.nativeElement.querySelectorAll('tbody tr'); - expect(rows).toHaveLength(2); - const cells = Array.from(rows[0].cells, (c: HTMLTableCellElement) => c.textContent?.trim()); - expect(cells).toEqual(['Afectación social (AS)', 'Comunicación', 'A-7', 'Señalar', '0']); - expect(rows[1].cells[2].textContent.trim()).toBe('A-3'); + it('resume la identidad con un renglón por sistema de identificador', () => { + const patient: Patient = { + resourceType: 'Patient', + id: 'child', + name: [{ text: 'Paciente de prueba' }], + birthDate: '2024-01-15', + gender: 'female', + identifier: [ + { system: 'urn:isssteleon:tea', value: 'N-1001' }, + { system: 'urn:isssteleon:tea-eeg', value: 'N-1001' }, + { system: 'https://isssteleon.org/fhir/sid/curp', value: 'XAXX010101HDFXXX01' }, + { system: 'https://isssteleon.org/fhir/sid/nss', value: '12345678901' }, + ], + extension: [ + { url: EXT + 'tea-age-group', valueCode: '24-29' }, + { url: EXT + 'tea-step', valueCode: 'eeg' }, + ], + }; + expect(identityRows(patient)).toEqual([ + ['Expediente', 'N-1001'], + ['CURP', 'XAXX010101HDFXXX01'], + ['NSS', '12345678901'], + ['Fecha de nacimiento', '2024-01-15'], + ['Sexo', 'Femenino'], + ['Grupo de edad', '24-29 meses'], + ['Paso', 'EEG'], + ]); }); - it('exporta las secciones, tablas y figuras con un nombre sin identificador', async () => { - const table = recordSections(record, new Map()); + it('ordena las secciones del expediente sin tarjeta de datos', () => { + expect(recordSections(record, new Map()).map((section) => section.title)).toEqual([ + 'Línea del tiempo', + 'ADOS-2', + 'Calidad del EEG', + 'Alteraciones', + 'Relación con el ADOS-2', + ]); + }); + + it('agrupa los ítems del módulo con dominio, subdominio, código y título', () => { + const section = recordSections(record, new Map()).find((s) => s.title === 'ADOS-2'); + expect(section?.blocks).toHaveLength(1); + expect(section?.blocks[0].title).toBe('2025-11-22'); + expect(section?.blocks[0].fields).toEqual([ + ['Módulo', 'Módulo 1'], + ['CSS', '0'], + ['Clasificación', '—'], + ]); + expect(section?.blocks[0].table?.rows).toEqual([ + ['Afectación social (AS)', 'Comunicación', 'A-7', 'Señalar', '0'], + [ + 'Comportamiento restringido y repetitivo (CRR)', + 'Comportamientos restringidos y repetitivos', + 'A-3', + 'Entonación de las vocalizaciones o verbalizaciones', + '2', + ], + ]); + }); + + it('pone la norma de cada métrica tras su mapa de la cabeza', () => { + const patient = { ...record, studies: [eeg] }; + const norm = { title: 'Norma por edad · p5–p95', figure: ageNorm(centiles, metric, eeg.age) }; + const norms = new Map([[`eeg-1|${metric.key}`, norm]]); + const altered = recordSections(patient, norms).find((s) => s.title === 'Alteraciones'); + expect(altered?.blocks.map((block) => block.chart?.title)).toEqual([ + 'Mapa de la cabeza', + 'Norma por edad · p5–p95', + ]); + const without = recordSections(patient, new Map()).find((s) => s.title === 'Alteraciones'); + expect(without?.blocks).toHaveLength(1); + }); + + it('exporta las secciones, tablas y figuras con un nombre sin identificador', () => { const sections = [ - ...table, - { - title: 'Normas', - blocks: [{ chart: { title: 'Mapa', figure: headMap(metric.sites) } }], - }, + ...recordSections(record, new Map()), + { title: 'Normas', blocks: [{ chart: { title: 'Mapa', figure: headMap(metric.sites) } }] }, ]; const filename = teaPdfName('seguimiento'); const content = teaPdfContent('Expediente TEA', sections, ['data:image/png;base64,YQ==']); expect(filename).toMatch(/^tea-seguimiento-\d{4}-\d{2}-\d{2}$/); expect(content).toEqual( expect.arrayContaining([ - expect.objectContaining({ text: 'Datos' }), + expect.objectContaining({ text: 'Línea del tiempo' }), expect.objectContaining({ text: 'Relación con el ADOS-2' }), expect.objectContaining({ table: expect.objectContaining({ @@ -199,78 +255,26 @@ describe('Expediente TEA', () => { ]), ); }); - - it('usa los eventos visibles de la búsqueda y ordena primero el par principal', async () => { - const entry = [ - { resource: record.patient, search: { mode: 'match' } }, - { resource: ados, search: { mode: 'include' } }, - { - resource: { - resourceType: 'Observation', - code: { coding: [{ code: 'eeg.lab_record_id' }] }, - effectiveDateTime: '2025-11-30', - valueString: 'LAB-01', - }, - search: { mode: 'include' }, - }, - { - resource: { - resourceType: 'RiskAssessment', - prediction: [ - { outcome: { coding: [{ code: 'spikes|occipital|CSS' }] } }, - { - outcome: { coding: [{ code: pair.key }] }, - extension: [{ url: EXT + 'association-headline', valueBoolean: true }], - }, - ], - }, - search: { mode: 'include' }, - }, - ]; - const search = vi.fn(async () => ({ entry })); - const data = await loadTeaPatient({ search } as unknown as Fhir, 'child'); - expect(search).toHaveBeenCalledWith('tea', 'Patient', { - _id: 'child', - _revinclude: ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'], - }); - expect(data.timeline[0]).toEqual(['2025-11-30', 'EEG', 'LAB-01']); - expect(data.studies).toHaveLength(0); - expect(data.pairs[0].key).toBe(pair.key); - }); }); -@Component({ selector: 'app-tea-record', template: '

Datos

Línea del tiempo

' }) -class RecordStub { - readonly id = input.required(); -} - -describe('Secciones por dominio', () => { - it('elige las secciones TEA y sigue mostrando las secciones de CaCu y CaMa', async () => { - const read = vi.fn(async () => record.patient); - TestBed.configureTestingModule({ - providers: [ - provideRouter([]), - { provide: Fhir, useValue: { read, all: async () => [], search: async () => ({}) } }, - ], - }).overrideComponent(Paciente, { - remove: { imports: [TeaRecord] }, - add: { imports: [RecordStub] }, - }); - const fixture = TestBed.createComponent(Paciente); - fixture.componentRef.setInput('id', 'child'); - fixture.componentRef.setInput('domain', 'tea'); - await fixture.whenStable(); - expect(fixture.nativeElement.querySelector('app-tea-record')?.textContent).toContain( - 'Línea del tiempo', +describe('Análisis de riesgo TEA', () => { + it('arma las secciones con las zonas alteradas filtradas y el par elegido', () => { + const sections = riskSections({ ...record, studies: [eeg] }, true, pair); + expect(sections.map((section) => section.title)).toEqual([ + 'Qué calcula', + 'Puntuaciones z por métrica y zona', + forestTitle, + 'Probabilidad frente a la referencia', + probabilityTitle, + 'Limitaciones', + ]); + const scores = sections.find( + (section) => section.title === 'Puntuaciones z por métrica y zona', ); - expect(read).not.toHaveBeenCalled(); - - for (const domain of ['cacu', 'cama']) { - fixture.componentRef.setInput('domain', domain); - await fixture.whenStable(); - expect(fixture.nativeElement.querySelector('app-tea-record')).toBeNull(); - expect(fixture.nativeElement.textContent).toContain('Historial médico'); - expect(read).toHaveBeenCalledWith(domain, 'Patient', 'child'); - } + expect(scores?.blocks[0].chart?.figure.data[0]).toMatchObject({ x: [0.3, 2.4] }); + const effects = sections.find((section) => section.title === forestTitle); + expect(effects?.blocks[0].chart?.figure.data[0]).toMatchObject({ x: [3] }); + const chosen = sections.find((section) => section.title === probabilityTitle); + expect(chosen?.blocks[0].chart?.title).toBe(pair.title); }); }); diff --git a/src/app/paciente/tea-patient.ts b/src/app/paciente/tea-patient.ts deleted file mode 100644 index 13c4e2e..0000000 --- a/src/app/paciente/tea-patient.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core'; -import { MatButtonModule } from '@angular/material/button'; -import { MatCardModule } from '@angular/material/card'; -import { RouterLink } from '@angular/router'; -import { Api } from '../api/api'; -import { curve } from '../api/fn/models/curve'; -import { Fhir } from '../fhir'; -import { Plot } from '../plot'; -import { loadTeaPatient, Study } from './tea-data'; -import { ageNorm, Centile, forest, probabilityCurve, zBars } from './tea-figures'; -import { - calculation, - exportTeaPdf, - forestTitle, - limitations, - probabilityRows, - probabilityTitle, - recordSections, - Section, -} from './tea-sections'; - -@Component({ - selector: 'app-tea-section', - imports: [MatCardModule, Plot], - templateUrl: './tea-section.html', - styleUrl: './tea-section.scss', -}) -export class TeaSection { - readonly section = input.required
(); -} - -@Component({ - selector: 'app-tea-record', - imports: [TeaSection, RouterLink, MatButtonModule], - templateUrl: './tea-record.html', -}) -export class TeaRecord { - private readonly fhir = inject(Fhir); - private readonly api = inject(Api); - private readonly host = inject>(ElementRef); - readonly id = input.required(); - protected readonly patient = resource({ - params: () => this.id(), - loader: ({ params }) => loadTeaPatient(this.fhir, params), - }); - protected readonly norms = resource({ - params: () => (this.patient.hasValue() ? this.patient.value().studies : undefined), - loader: ({ params }) => this.loadNorms(params), - }); - protected readonly sections = computed(() => { - const patient = this.patient.hasValue() ? this.patient.value() : undefined; - return patient - ? recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map()) - : []; - }); - protected readonly exporting = signal(false); - protected readonly exportError = signal(false); - - private async loadNorms(studies: Study[]) { - const curves = new Map>(); - const charts = await Promise.all( - studies.flatMap((eeg) => - eeg.metrics.map(async (metric) => { - const model = /^tea\.([^/]+)\/([1-9]\d*)$/.exec(metric.model ?? ''); - if ( - !model || - metric.key === 'paroxysmal_spikes' || - metric.value == null || - eeg.age == null - ) { - return undefined; - } - const [, name, version] = model; - const key = model[0]; - if (!curves.has(key)) { - curves.set( - key, - this.api - .invoke(curve, { domain: 'tea', name, version: Number(version) }) - .then((rows) => rows as Centile[]) - .catch(() => []), - ); - } - const rows = await curves.get(key)!; - if (!rows.some((row) => row.median != null)) return undefined; - return [ - `${eeg.id}|${metric.key}`, - { - title: 'Norma por edad · p5–p95', - figure: ageNorm(rows, metric, eeg.age), - }, - ] as const; - }), - ), - ); - return new Map(charts.filter((chart) => chart !== undefined)); - } - - protected async download(): Promise { - this.exportError.set(false); - this.exporting.set(true); - try { - await exportTeaPdf( - 'seguimiento', - 'Expediente TEA', - this.sections(), - this.host.nativeElement.querySelectorAll('app-plot .plot'), - ); - } catch { - this.exportError.set(true); - } finally { - this.exporting.set(false); - } - } -} - -@Component({ - selector: 'app-tea-risk', - imports: [TeaSection, RouterLink, MatButtonModule], - templateUrl: './tea-risk.html', -}) -export class TeaRisk { - private readonly fhir = inject(Fhir); - private readonly host = inject>(ElementRef); - readonly id = input.required(); - protected readonly patient = resource({ - params: () => this.id(), - loader: ({ params }) => loadTeaPatient(this.fhir, params), - }); - protected readonly onlyAltered = signal(false); - protected readonly selectedKey = signal(''); - protected readonly selectedPair = computed(() => { - const pairs = this.patient.hasValue() ? this.patient.value().pairs : []; - return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0]; - }); - protected readonly forestTitle = forestTitle; - protected readonly probabilityTitle = probabilityTitle; - protected readonly sections = computed(() => { - if (!this.patient.hasValue()) return []; - const patient = this.patient.value(); - const studies = patient.riskStudy ? [patient.riskStudy] : patient.studies; - const scores = studies - .map((eeg) => ({ date: eeg.date, figure: zBars(eeg) })) - .find(({ figure }) => figure.data[0].x?.length); - const effects = forest(patient.pairs, this.onlyAltered()); - const pair = this.selectedPair(); - return [ - { title: 'Qué calcula', blocks: [{ text: calculation }] }, - { - title: 'Puntuaciones z por métrica y zona', - blocks: scores - ? [ - { - chart: { - title: scores.date, - figure: scores.figure, - height: Math.max(340, 24 * (scores.figure.data[0].x?.length ?? 0) + 80), - }, - }, - ] - : [], - }, - { - title: forestTitle, - blocks: [ - effects.data[0].x?.length - ? { - chart: { - title: 'OR e IC 95 %', - figure: effects, - height: Math.max(340, 26 * effects.data[0].x.length + 80), - }, - } - : { text: '—' }, - ], - }, - { - title: 'Probabilidad frente a la referencia', - blocks: [{ table: probabilityRows(patient.pairs) }], - }, - { - title: probabilityTitle, - blocks: pair ? [{ chart: { title: pair.title, figure: probabilityCurve(pair) } }] : [], - }, - { title: 'Limitaciones', blocks: [{ text: limitations }] }, - ]; - }); - protected readonly exporting = signal(false); - protected readonly exportError = signal(false); - - protected async download(): Promise { - this.exportError.set(false); - this.exporting.set(true); - try { - await exportTeaPdf( - 'riesgos', - 'Análisis de riesgo TEA', - this.sections(), - this.host.nativeElement.querySelectorAll('app-plot .plot'), - ); - } catch { - this.exportError.set(true); - } finally { - this.exporting.set(false); - } - } -} diff --git a/src/app/paciente/tea-record.html b/src/app/paciente/tea-record.html deleted file mode 100644 index d499db4..0000000 --- a/src/app/paciente/tea-record.html +++ /dev/null @@ -1,31 +0,0 @@ -
- - @if (patient.error()) { -

No se encontró el paciente.

- } @else if (patient.value(); as data) { -

{{ data.patient.name?.[0]?.text ?? 'Expediente TEA' }}

- - @if (exportError()) { -

No se pudo exportar el PDF.

- } - @for (section of sections(); track section.title) { - - } - } @else if (patient.isLoading()) { -

Cargando…

- } -
diff --git a/src/app/paciente/tea-risk.html b/src/app/paciente/tea-risk.html deleted file mode 100644 index 3012d31..0000000 --- a/src/app/paciente/tea-risk.html +++ /dev/null @@ -1,51 +0,0 @@ -
- -

Análisis de riesgo TEA

- @if (patient.error()) { -

No se encontró el paciente.

- } @else if (patient.value(); as data) { - @if (data.patient.name?.[0]?.text; as name) { -

{{ name }}

- } - - @if (exportError()) { -

No se pudo exportar el PDF.

- } - @for (section of sections(); track section.title) { - - @if (section.title === forestTitle) { - - } - @if (section.title === probabilityTitle && data.pairs.length) { - - } - - } - } @else if (patient.isLoading()) { -

Cargando…

- } -
diff --git a/src/app/paciente/tea-section.html b/src/app/paciente/tea-section.html deleted file mode 100644 index 9e1177d..0000000 --- a/src/app/paciente/tea-section.html +++ /dev/null @@ -1,56 +0,0 @@ - -

{{ section().title }}

- - - @for (block of section().blocks; track $index) { - @if (block.title) { -

{{ block.title }}

- } - @if (block.text) { -

{{ block.text }}

- } - @if (block.fields; as fields) { -
- @for (field of fields; track $index) { -
-
{{ field[0] }}
-
{{ field[1] }}
-
- } -
- } - @if (block.table; as table) { - @if (table.rows.length) { - - - - @for (header of table.headers; track $index) { - - } - - - - @for (row of table.rows; track $index) { - - @for (cell of row; track $index) { - - } - - } - -
{{ header }}
{{ cell }}
- } @else { -

—

- } - } - @if (block.chart; as chart) { -

{{ chart.title }}

- - } - } @empty { -

—

- } -
-
diff --git a/src/app/paciente/tea-section.scss b/src/app/paciente/tea-section.scss deleted file mode 100644 index 7772fb0..0000000 --- a/src/app/paciente/tea-section.scss +++ /dev/null @@ -1,28 +0,0 @@ -:host { - display: block; - margin-block: var(--space-4); -} - -mat-card-content { - overflow-x: auto; -} - -h2 { - margin: 0 0 var(--space-3); -} - -dl { - display: flex; - flex-wrap: wrap; - gap: var(--space-4); - margin-block: var(--space-3); -} - -dt { - color: var(--color-text-secondary); -} - -dd { - margin: 0; - font-weight: 500; -} diff --git a/src/app/paciente/tea-section.ts b/src/app/paciente/tea-section.ts new file mode 100644 index 0000000..b3fb7f2 --- /dev/null +++ b/src/app/paciente/tea-section.ts @@ -0,0 +1,90 @@ +import { Component, input } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; +import { Plot } from '../plot'; +import { Section } from './tea-sections'; + +@Component({ + selector: 'app-tea-section', + imports: [MatCardModule, Plot], + template: ` + + {{ section().title }} + + + @for (block of section().blocks; track $index) { + @if (block.title) { +

{{ block.title }}

+ } + @if (block.text) { +

{{ block.text }}

+ } + @if (block.fields; as fields) { +
+ @for (field of fields; track $index) { +
+
{{ field[0] }}
+
{{ field[1] }}
+
+ } +
+ } + @if (block.table; as table) { + @if (table.rows.length) { + + + + @for (header of table.headers; track $index) { + + } + + + + @for (row of table.rows; track $index) { + + @for (cell of row; track $index) { + + } + + } + +
{{ header }}
{{ cell }}
+ } @else { +

—

+ } + } + @if (block.chart; as chart) { +

{{ chart.title }}

+ + } + } @empty { +

—

+ } +
+
+ `, + styles: ` + :host { + display: block; + } + mat-card-content { + overflow-x: auto; + } + dl { + display: flex; + flex-wrap: wrap; + gap: var(--space-4); + margin-block: var(--space-3); + } + dt { + color: var(--color-text-secondary); + font-size: 12px; + } + dd { + margin: 0; + font-weight: 500; + } + `, +}) +export class TeaSection { + readonly section = input.required
(); +} \ No newline at end of file diff --git a/src/app/paciente/tea-sections.ts b/src/app/paciente/tea-sections.ts index 17aea12..cbf25b7 100644 --- a/src/app/paciente/tea-sections.ts +++ b/src/app/paciente/tea-sections.ts @@ -3,17 +3,8 @@ import { downloadPdf } from '../export/pdf'; import { safeName } from '../export/safe-name'; import type { Figure } from '../plot'; import plotly from '../plotly-bundle'; -import { - adosItems, - adosSummary, - alteration, - identity, - Pair, - percent, - shown, - TeaPatient, -} from './tea-data'; -import { headMap } from './tea-figures'; +import { adosItems, adosSummary, alteration, Pair, percent, shown, TeaPatient } from './tea-data'; +import { forest, headMap, probabilityCurve, zBars } from './tea-figures'; type Table = { headers: string[]; rows: string[][] }; type Chart = { title: string; figure: Figure; height?: number }; @@ -46,7 +37,6 @@ function associationRows(pairs: Pair[]): string[][] { export function recordSections(patient: TeaPatient, norms: ReadonlyMap): Section[] { return [ - { title: 'Datos', blocks: [{ fields: identity(patient.patient) }] }, { title: 'Línea del tiempo', blocks: [ @@ -112,6 +102,54 @@ export function recordSections(patient: TeaPatient, norms: ReadonlyMap ({ date: eeg.date, figure: zBars(eeg) })) + .find(({ figure }) => figure.data[0].x?.length); + const effects = forest(patient.pairs, alteredOnly); + return [ + { title: 'Qué calcula', blocks: [{ text: calculation }] }, + { + title: 'Puntuaciones z por métrica y zona', + blocks: scores + ? [ + { + chart: { + title: scores.date, + figure: scores.figure, + height: Math.max(340, 24 * (scores.figure.data[0].x?.length ?? 0) + 80), + }, + }, + ] + : [], + }, + { + title: forestTitle, + blocks: [ + effects.data[0].x?.length + ? { + chart: { + title: 'OR e IC 95 %', + figure: effects, + height: Math.max(340, 26 * effects.data[0].x.length + 80), + }, + } + : { text: '—' }, + ], + }, + { + title: 'Probabilidad frente a la referencia', + blocks: [{ table: probabilityRows(patient.pairs) }], + }, + { + title: probabilityTitle, + blocks: pair ? [{ chart: { title: pair.title, figure: probabilityCurve(pair) } }] : [], + }, + { title: 'Limitaciones', blocks: [{ text: limitations }] }, + ]; +} + export function probabilityRows(pairs: Pair[]): Table { return { headers: ['Par', 'Probabilidad', 'Referencia'],