From 0b22b3c309c21070908862887c3524ba18997586 Mon Sep 17 00:00:00 2001 From: ulises Date: Mon, 23 Nov 2026 09:29:33 -0600 Subject: [PATCH] =?UTF-8?q?Gobernanza:=20TEA=20=C2=B7=20EEG=20tab=20with?= =?UTF-8?q?=20cluster=20check,=20reference=20data,=20training,=20baselines?= =?UTF-8?q?,=20reports,=20promotion,=20run=20monitor,=20analysis=20and=20r?= =?UTF-8?q?esult?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/governance/api/tea-eeg.api.spec.ts | 185 +++++++++++++++++ src/app/governance/api/tea-eeg.api.ts | 137 +++++++++++++ src/app/governance/api/tea-eeg.types.ts | 180 ++++++++++++++++ .../components/analyze-step/analyze-step.html | 53 +++++ .../components/analyze-step/analyze-step.scss | 4 + .../analyze-step/analyze-step.spec.ts | 138 +++++++++++++ .../components/analyze-step/analyze-step.ts | 161 +++++++++++++++ .../baseline-check/baseline-check.html | 76 +++++++ .../baseline-check/baseline-check.scss | 2 + .../baseline-check/baseline-check.spec.ts | 77 +++++++ .../baseline-check/baseline-check.ts | 74 +++++++ .../baseline-check/baseline-figure.ts | 53 +++++ .../cluster-health-card.html | 35 ++++ .../cluster-health-card.scss | 102 +++++++++ .../cluster-health-card.spec.ts | 193 ++++++++++++++++++ .../cluster-health-card.ts | 153 ++++++++++++++ .../cluster-selector/cluster-selector.html | 13 ++ .../cluster-selector/cluster-selector.scss | 10 + .../cluster-selector/cluster-selector.spec.ts | 58 ++++++ .../cluster-selector/cluster-selector.ts | 44 ++++ .../components/eeg-picker/eeg-picker.spec.ts | 39 ++++ .../components/eeg-picker/eeg-picker.ts | 60 ++++++ src/app/governance/components/eeg-step.scss | 8 + .../governance-page/governance-page.html | 7 + .../governance-page/governance-page.spec.ts | 97 +++++++++ .../governance-page/governance-page.ts | 16 +- .../components/result-step/result-step.html | 23 +++ .../components/result-step/result-step.scss | 3 + .../result-step/result-step.spec.ts | 88 ++++++++ .../components/result-step/result-step.ts | 64 ++++++ .../components/run-monitor/run-monitor.html | 61 ++++++ .../components/run-monitor/run-monitor.scss | 11 + .../run-monitor/run-monitor.spec.ts | 103 ++++++++++ .../components/run-monitor/run-monitor.ts | 117 +++++++++++ .../baselines-step/baselines-step.html | 72 +++++++ .../baselines-step/baselines-step.scss | 81 ++++++++ .../baselines-step/baselines-step.spec.ts | 108 ++++++++++ .../baselines-step/baselines-step.ts | 107 ++++++++++ .../promote-step/promote-step.html | 92 +++++++++ .../promote-step/promote-step.scss | 95 +++++++++ .../promote-step/promote-step.spec.ts | 119 +++++++++++ .../promote-step/promote-step.ts | 146 +++++++++++++ .../reference-step/reference-step.html | 72 +++++++ .../reference-step/reference-step.scss | 89 ++++++++ .../reference-step/reference-step.spec.ts | 129 ++++++++++++ .../reference-step/reference-step.ts | 152 ++++++++++++++ .../components/tea-eeg-panel/report-fields.ts | 17 ++ .../reports-step/reports-step.html | 59 ++++++ .../reports-step/reports-step.scss | 59 ++++++ .../reports-step/reports-step.spec.ts | 145 +++++++++++++ .../reports-step/reports-step.ts | 150 ++++++++++++++ .../tea-eeg-panel/tea-candidates.ts | 20 ++ .../tea-eeg-panel/tea-eeg-panel.html | 32 +++ .../tea-eeg-panel/tea-eeg-panel.scss | 15 ++ .../components/tea-eeg-panel/tea-eeg-panel.ts | 36 ++++ .../training-step/training-step.html | 108 ++++++++++ .../training-step/training-step.scss | 96 +++++++++ .../training-step/training-step.spec.ts | 148 ++++++++++++++ .../training-step/training-step.ts | 163 +++++++++++++++ src/styles.scss | 8 + 60 files changed, 4759 insertions(+), 4 deletions(-) create mode 100644 src/app/governance/api/tea-eeg.api.spec.ts create mode 100644 src/app/governance/api/tea-eeg.api.ts create mode 100644 src/app/governance/api/tea-eeg.types.ts create mode 100644 src/app/governance/components/analyze-step/analyze-step.html create mode 100644 src/app/governance/components/analyze-step/analyze-step.scss create mode 100644 src/app/governance/components/analyze-step/analyze-step.spec.ts create mode 100644 src/app/governance/components/analyze-step/analyze-step.ts create mode 100644 src/app/governance/components/baseline-check/baseline-check.html create mode 100644 src/app/governance/components/baseline-check/baseline-check.scss create mode 100644 src/app/governance/components/baseline-check/baseline-check.spec.ts create mode 100644 src/app/governance/components/baseline-check/baseline-check.ts create mode 100644 src/app/governance/components/baseline-check/baseline-figure.ts create mode 100644 src/app/governance/components/cluster-health-card/cluster-health-card.html create mode 100644 src/app/governance/components/cluster-health-card/cluster-health-card.scss create mode 100644 src/app/governance/components/cluster-health-card/cluster-health-card.spec.ts create mode 100644 src/app/governance/components/cluster-health-card/cluster-health-card.ts create mode 100644 src/app/governance/components/cluster-selector/cluster-selector.html create mode 100644 src/app/governance/components/cluster-selector/cluster-selector.scss create mode 100644 src/app/governance/components/cluster-selector/cluster-selector.spec.ts create mode 100644 src/app/governance/components/cluster-selector/cluster-selector.ts create mode 100644 src/app/governance/components/eeg-picker/eeg-picker.spec.ts create mode 100644 src/app/governance/components/eeg-picker/eeg-picker.ts create mode 100644 src/app/governance/components/eeg-step.scss create mode 100644 src/app/governance/components/governance-page/governance-page.spec.ts create mode 100644 src/app/governance/components/result-step/result-step.html create mode 100644 src/app/governance/components/result-step/result-step.scss create mode 100644 src/app/governance/components/result-step/result-step.spec.ts create mode 100644 src/app/governance/components/result-step/result-step.ts create mode 100644 src/app/governance/components/run-monitor/run-monitor.html create mode 100644 src/app/governance/components/run-monitor/run-monitor.scss create mode 100644 src/app/governance/components/run-monitor/run-monitor.spec.ts create mode 100644 src/app/governance/components/run-monitor/run-monitor.ts create mode 100644 src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.html create mode 100644 src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.scss create mode 100644 src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.spec.ts create mode 100644 src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.ts create mode 100644 src/app/governance/components/tea-eeg-panel/promote-step/promote-step.html create mode 100644 src/app/governance/components/tea-eeg-panel/promote-step/promote-step.scss create mode 100644 src/app/governance/components/tea-eeg-panel/promote-step/promote-step.spec.ts create mode 100644 src/app/governance/components/tea-eeg-panel/promote-step/promote-step.ts create mode 100644 src/app/governance/components/tea-eeg-panel/reference-step/reference-step.html create mode 100644 src/app/governance/components/tea-eeg-panel/reference-step/reference-step.scss create mode 100644 src/app/governance/components/tea-eeg-panel/reference-step/reference-step.spec.ts create mode 100644 src/app/governance/components/tea-eeg-panel/reference-step/reference-step.ts create mode 100644 src/app/governance/components/tea-eeg-panel/report-fields.ts create mode 100644 src/app/governance/components/tea-eeg-panel/reports-step/reports-step.html create mode 100644 src/app/governance/components/tea-eeg-panel/reports-step/reports-step.scss create mode 100644 src/app/governance/components/tea-eeg-panel/reports-step/reports-step.spec.ts create mode 100644 src/app/governance/components/tea-eeg-panel/reports-step/reports-step.ts create mode 100644 src/app/governance/components/tea-eeg-panel/tea-candidates.ts create mode 100644 src/app/governance/components/tea-eeg-panel/tea-eeg-panel.html create mode 100644 src/app/governance/components/tea-eeg-panel/tea-eeg-panel.scss create mode 100644 src/app/governance/components/tea-eeg-panel/tea-eeg-panel.ts create mode 100644 src/app/governance/components/tea-eeg-panel/training-step/training-step.html create mode 100644 src/app/governance/components/tea-eeg-panel/training-step/training-step.scss create mode 100644 src/app/governance/components/tea-eeg-panel/training-step/training-step.spec.ts create mode 100644 src/app/governance/components/tea-eeg-panel/training-step/training-step.ts diff --git a/src/app/governance/api/tea-eeg.api.spec.ts b/src/app/governance/api/tea-eeg.api.spec.ts new file mode 100644 index 0000000..e3f096e --- /dev/null +++ b/src/app/governance/api/tea-eeg.api.spec.ts @@ -0,0 +1,185 @@ +/** + * Covers `TeaEegApi`'s HTTP mapping: every method hits the contract's exact URL, verb, query and body, + * and the multipart uploads send `reportProgress` so the UI can show progress. Fixtures: a real + * `HttpClient` answered by `HttpTestingController`; each test flushes one canned response. + */ +import { HttpEvent, HttpEventType } from '@angular/common/http'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { TeaEegApi } from './tea-eeg.api'; +import { AnalyzeJob, ClusterStatus, TeaTrainBody } from './tea-eeg.types'; + +const STATUS: ClusterStatus = { + mode: 'auto', scheduler: 'tcp://equipo:8786', reachable: true, workers: 4, expected_workers: 4, + versions_ok: true, version_error: null, dashboard_ok: true, dashboard_url: 'http://equipo:8787/status', + reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42, error: null, +}; + +// A finished analysis job, as `GET` answers it. +const ANALYZE_JOB: AnalyzeJob = { + id: 'a1', iniciado: '2026-11-01T10:00:00+00:00', estado: 'completado', codigo: 0, + salida: '2 válidos, 1 no válido', error: '', cluster: null, ids: null, + summary: { pending: 0, valid: 2, not_valid: 1, failed: 0 }, +}; + +describe('TeaEegApi', () => { + let api: TeaEegApi; + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + api = TestBed.inject(TeaEegApi); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + // Fails if the health check changes route, or sends params when no cluster was picked. + it('asks for the cluster health without params, and with them when a choice is given', () => { + api.clusterStatus().subscribe((s) => expect(s).toEqual(STATUS)); + http.expectOne((r) => r.url === '/governance/tea/cluster' && r.params.keys().length === 0).flush(STATUS); + + api.clusterStatus({ mode: 'remote', scheduler: 'tcp://equipo:8786' }).subscribe(); + const req = http.expectOne((r) => r.url === '/governance/tea/cluster'); + expect(req.request.params.get('mode')).toBe('remote'); + expect(req.request.params.get('scheduler')).toBe('tcp://equipo:8786'); + req.flush(STATUS); + }); + + // Fails if the cohort list moves, or the file upload stops being multipart on the cohort's route. + it('lists reference cohorts and uploads one cohort file with progress events', () => { + api.listReferenceCohorts().subscribe(); + http.expectOne((r) => r.url === '/governance/tea/reference-cohorts').flush([]); + + const types: HttpEventType[] = []; + api.uploadReferenceFile('referencia_2026', new File(['x'], 'estudio.edf')).subscribe((e) => types.push(e.type)); + const req = http.expectOne((r) => r.url === '/governance/tea/reference-cohorts/referencia_2026/files'); + expect(req.request.method).toBe('POST'); + expect(req.request.reportProgress).toBe(true); + const body = req.request.body as FormData; + expect(body.get('name')).toBeNull(); + expect((body.get('file') as File).name).toBe('estudio.edf'); + req.event({ type: HttpEventType.UploadProgress, loaded: 2, total: 4 }); + req.flush({ name: 'referencia_2026', file: 'estudio.edf', size_bytes: 4 }); + expect(types).toEqual([HttpEventType.Sent, HttpEventType.UploadProgress, HttpEventType.Response]); + }); + + // Fails if training moves off the existing route, or the optional body stops being sent as-is. + it('starts the TEA training on the existing train-jobs route', () => { + api.startTeaTraining().subscribe(); + const empty = http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg/train-jobs'); + expect(empty.request.method).toBe('POST'); + expect(empty.request.body).toEqual({}); + empty.flush({ job: null }); + + const body: TeaTrainBody = { + reference_name: 'referencia_2026', reference_dir: '/datos/tea/referencia_2026', reference_ages: 'edades.csv', + line_hz: 50, promote: false, cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' }, + }; + api.startTeaTraining(body).subscribe(); + const req = http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg/train-jobs'); + expect(req.request.body).toEqual(body); + req.flush({ job: null }); + }); + + // Fails if the export URL loses its query or the import moves off the baselines route. + it('builds the baselines export URL and imports a bundle with progress events', () => { + expect(api.baselinesExportUrl()).toBe('/governance/tea/baselines/export?environment=prod'); + expect(api.baselinesExportUrl('staging', false)).toBe('/governance/tea/baselines/export?environment=staging&production=0'); + + const events: HttpEvent<{ sha256: string }>[] = []; + api.importBaselines(new File(['zip'], 'baselines.zip')).subscribe((e) => events.push(e)); + const req = http.expectOne((r) => r.url === '/governance/tea/baselines/import'); + expect(req.request.method).toBe('POST'); + expect(req.request.reportProgress).toBe(true); + expect(((req.request.body as FormData).get('file') as File).name).toBe('baselines.zip'); + req.flush({ sha256: 'abc', imported: [] }); + expect(events.at(-1)?.type).toBe(HttpEventType.Response); + }); + + // Fails if the analysis jobs change route, or the start/list/get verbs drift from the contract. + it('starts, lists and gets analysis jobs on the analyze-jobs routes', () => { + api.startAnalyzeJob({ all: true, cluster: { mode: 'sync' } }).subscribe((j) => expect(j).toEqual(ANALYZE_JOB)); + const started = http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs'); + expect(started.request.method).toBe('POST'); + expect(started.request.body).toEqual({ all: true, cluster: { mode: 'sync' } }); + started.flush(ANALYZE_JOB); + + api.analyzeJobs().subscribe(); + http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs').flush([ANALYZE_JOB]); + + api.analyzeJob('a1').subscribe(); + http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs/a1').flush(ANALYZE_JOB); + }); + + // Fails if the progress route stops being jobs///progress for either kind. + it('reads a run progress for training and analysis', () => { + api.runProgress('train', 't1').subscribe(); + http.expectOne((r) => r.url === '/governance/tea/jobs/train/t1/progress').flush(null); + + api.runProgress('analyze', 'a1').subscribe(); + http.expectOne((r) => r.url === '/governance/tea/jobs/analyze/a1/progress').flush(null); + }); + + // Fails if the baseline check routes drift, or the curve loses its metric query. + it('reads baseline metric names and one metric curve', () => { + api.baselineMetrics('tea_nsr', 3).subscribe(); + http.expectOne((r) => r.url === '/governance/tea/baselines/tea_nsr/3/metrics').flush(['alpha_peak']); + + api.baselineCurve('tea_nsr', 3, 'alpha_peak').subscribe(); + const req = http.expectOne((r) => r.url === '/governance/tea/baselines/tea_nsr/3/curve'); + expect(req.request.params.get('metric')).toBe('alpha_peak'); + req.flush(null); + }); + + // Fails if the EEG catalog loses its paging, or the metrics/summary routes move. + it('lists EEGs paged and reads one EEG metrics and the summary', () => { + api.eegList().subscribe(); + const list = http.expectOne((r) => r.url === '/governance/tea/eeg'); + expect(list.request.params.get('limit')).toBe('200'); + expect(list.request.params.get('offset')).toBe('0'); + list.flush([]); + + api.eegList(50, 100).subscribe(); + const paged = http.expectOne((r) => r.url === '/governance/tea/eeg'); + expect(paged.request.params.get('limit')).toBe('50'); + expect(paged.request.params.get('offset')).toBe('100'); + paged.flush([]); + + api.eegMetrics(7).subscribe(); + http.expectOne((r) => r.url === '/governance/tea/eeg/7/metrics').flush(null); + + api.eegSummary().subscribe(); + http.expectOne((r) => r.url === '/governance/tea/eeg/summary').flush(null); + }); + + // Fails if the EEG upload stops sending the file under the `file` field, or drops the patient id. + it('uploads one EDF with an optional patient id', () => { + api.uploadEeg(new File(['x'], 'estudio.edf')).subscribe(); + const bare = http.expectOne((r) => r.url === '/governance/tea/eeg/upload'); + expect(bare.request.method).toBe('POST'); + const form = bare.request.body as FormData; + expect((form.get('file') as File).name).toBe('estudio.edf'); + expect(form.get('patient_id')).toBeNull(); + bare.flush({ eeg_id: 7, lab_id: null, created: true }); + + api.uploadEeg(new File(['x'], 'otro.edf'), 42).subscribe(); + const withPatient = http.expectOne((r) => r.url === '/governance/tea/eeg/upload'); + expect((withPatient.request.body as FormData).get('patient_id')).toBe('42'); + withPatient.flush({ eeg_id: 8, lab_id: 'L-2', created: false }); + }); + + // Fails if the recalculation moves off the existing indicators route, or sends a body without a cluster. + it('recalculates the TEA indicators with an optional cluster body', () => { + api.recalculateTeaIndicators().subscribe(); + const bare = http.expectOne((r) => r.url === '/reportes/indicadores/tea/recalcular'); + expect(bare.request.method).toBe('POST'); + expect(bare.request.body).toEqual({}); + bare.flush({ pendiente: true }); + + api.recalculateTeaIndicators({ mode: 'local' }).subscribe(); + const withCluster = http.expectOne((r) => r.url === '/reportes/indicadores/tea/recalcular'); + expect(withCluster.request.body).toEqual({ cluster: { mode: 'local' } }); + withCluster.flush({ pendiente: true }); + }); +}); diff --git a/src/app/governance/api/tea-eeg.api.ts b/src/app/governance/api/tea-eeg.api.ts new file mode 100644 index 0000000..aafac0f --- /dev/null +++ b/src/app/governance/api/tea-eeg.api.ts @@ -0,0 +1,137 @@ +import { HttpClient, HttpEvent, HttpParams } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable } from 'rxjs'; +import { + AnalyzeBody, + AnalyzeJob, + BaselineCurve, + BaselineImport, + ClusterChoice, + ClusterStatus, + EegId, + EegListItem, + EegMetrics, + EegSummary, + EegUploadResult, + ReferenceCohort, + ReferenceFileUpload, + RunProgress, + TeaTrainBody, + TeaTrainJob, +} from './tea-eeg.types'; + +/** `/governance/tea/*`: the TEA·EEG cluster, reference cohorts, training, baseline bundles, analysis + * jobs and the EEG catalog. The multipart uploads report progress events. */ +@Injectable({ providedIn: 'root' }) +export class TeaEegApi { + private readonly http = inject(HttpClient); + + /** Effective cluster health after resolving 'auto'; both query params optional. */ + clusterStatus(choice?: ClusterChoice): Observable { + const params = toParams(choice ? { mode: choice.mode, scheduler: choice.scheduler } : {}); + return this.http.get('/governance/tea/cluster', { params }); + } + + listReferenceCohorts(): Observable { + return this.http.get('/governance/tea/reference-cohorts'); + } + + /** One `.edf` or the cohort's `edades.csv`; emits upload progress events, then the stored file. */ + uploadReferenceFile(name: string, file: File): Observable> { + const form = new FormData(); + form.append('file', file); + return this.http.post(`/governance/tea/reference-cohorts/${encodeURIComponent(name)}/files`, form, { + reportProgress: true, + observe: 'events', + }); + } + + /** Starts the TEA training in the background: 202 with the job, 409 with the running one; the body + * overrides the server's `TEA_REFERENCE_*` settings. */ + startTeaTraining(body: TeaTrainBody = {}): Observable<{ job: TeaTrainJob }> { + return this.http.post<{ job: TeaTrainJob }>('/governance/model-versions/tea/eeg/train-jobs', body); + } + + /** Where the zip bundle of promoted baselines downloads from; `production=0` excludes them. */ + baselinesExportUrl(environment = 'prod', production?: boolean): string { + let query = `environment=${encodeURIComponent(environment)}`; + if (production !== undefined) query += `&production=${production ? 1 : 0}`; + return `/governance/tea/baselines/export?${query}`; + } + + /** Imports a baseline bundle; emits upload progress events, then what was imported. */ + importBaselines(file: File): Observable> { + const form = new FormData(); + form.append('file', file); + return this.http.post('/governance/tea/baselines/import', form, { + reportProgress: true, + observe: 'events', + }); + } + + /** Starts an EEG analysis: 202 with the job, 409 while one runs. */ + startAnalyzeJob(body: AnalyzeBody): Observable { + return this.http.post('/governance/tea/eeg/analyze-jobs', body); + } + + /** The analysis jobs, newest first. */ + analyzeJobs(): Observable { + return this.http.get('/governance/tea/eeg/analyze-jobs'); + } + + analyzeJob(id: string): Observable { + return this.http.get(`/governance/tea/eeg/analyze-jobs/${encodeURIComponent(id)}`); + } + + /** Live progress of a training (`kind: 'train'`) or analysis (`'analyze'`) run; 404 before the first + * sample. Non-Dask jobs answer `cluster: null` and `tasks: null`. */ + runProgress(kind: 'train' | 'analyze', jobId: string): Observable { + return this.http.get(`/governance/tea/jobs/${kind}/${encodeURIComponent(jobId)}/progress`); + } + + /** The metric names a baseline version has a curve for. */ + baselineMetrics(scenario: string, version: number): Observable { + return this.http.get(`/governance/tea/baselines/${encodeURIComponent(scenario)}/${version}/metrics`); + } + + /** One metric's curve across age for a baseline version. */ + baselineCurve(scenario: string, version: number, metric: string): Observable { + return this.http.get(`/governance/tea/baselines/${encodeURIComponent(scenario)}/${version}/curve`, { + params: new HttpParams().set('metric', metric), + }); + } + + /** The EEG catalog, paged; feeds the ticked list of the analysis step. */ + eegList(limit = 200, offset = 0): Observable { + return this.http.get('/governance/tea/eeg', { params: toParams({ limit, offset }) }); + } + + eegMetrics(eegId: EegId): Observable { + return this.http.get(`/governance/tea/eeg/${encodeURIComponent(eegId)}/metrics`); + } + + eegSummary(): Observable { + return this.http.get('/governance/tea/eeg/summary'); + } + + /** One `.edf` through the existing import pipeline; 400 when MNE cannot open it. */ + uploadEeg(file: File, patientId?: number): Observable { + const form = new FormData(); + form.append('file', file); + if (patientId !== undefined) form.append('patient_id', String(patientId)); + return this.http.post('/governance/tea/eeg/upload', form); + } + + /** Recomputes the TEA indicators on the given cluster; the body is optional. */ + recalculateTeaIndicators(cluster?: ClusterChoice): Observable<{ pendiente: boolean }> { + return this.http.post<{ pendiente: boolean }>('/reportes/indicadores/tea/recalcular', cluster ? { cluster } : {}); + } +} + +function toParams(filters: Record): HttpParams { + let params = new HttpParams(); + for (const [key, value] of Object.entries(filters)) { + if (value !== undefined && value !== null && value !== '') params = params.set(key, String(value)); + } + return params; +} diff --git a/src/app/governance/api/tea-eeg.types.ts b/src/app/governance/api/tea-eeg.types.ts new file mode 100644 index 0000000..d61dcab --- /dev/null +++ b/src/app/governance/api/tea-eeg.types.ts @@ -0,0 +1,180 @@ +/** Shapes of the `/governance/tea/*` JSON contract: cluster health, reference cohorts, TEA training, + * baseline bundles, EEG analysis jobs and the EEG catalog. */ +import { TrainingJob } from './governance.types'; + +export type ClusterMode = 'auto' | 'local' | 'remote' | 'sync'; + +/** Where the work runs; `scheduler` is only meaningful for 'remote'. */ +export interface ClusterChoice { + mode: ClusterMode; + scheduler?: string; +} + +export type JobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido'; + +/** Effective cluster health after resolving 'auto'. */ +export interface ClusterStatus { + mode: ClusterMode; + scheduler: string | null; + reachable: boolean; + workers: number | null; + expected_workers: number | null; + versions_ok: boolean | null; + version_error: string | null; + dashboard_ok: boolean | null; + dashboard_url: string | null; + reference: { name: string; edfs: number } | null; + latency_ms: number | null; + error: string | null; +} + +/** One reference cohort folder under `TEA_REFERENCE_ROOT`. */ +export interface ReferenceCohort { + name: string; + edfs: number; + size_bytes: number; + has_ages: boolean; + path: string; +} + +/** The answer to uploading one cohort file (`.edf` or `edades.csv`): 201. */ +export interface ReferenceFileUpload { + name: string; + file: string; + size_bytes: number; +} + +/** Body of the TEA training route; fields override the server's `TEA_REFERENCE_*`. */ +export interface TeaTrainBody { + reference_name?: string; + reference_dir?: string; + reference_ages?: string; + line_hz?: number; + promote?: boolean; + cluster?: ClusterChoice; +} + +/** The training job the existing route answers, with the cluster it ran on. */ +export interface TeaTrainJob extends TrainingJob { + cluster: ClusterChoice | null; +} + +/** The answer to importing a baseline bundle. */ +export interface BaselineImport { + sha256: string; + imported: { scenario: string; version: number }[]; +} + +/** Body of an analysis job start. */ +export interface AnalyzeBody { + all?: boolean; + limit?: number; + ids?: (number | string)[]; + cluster?: ClusterChoice; +} + +/** Counts behind an analysis job, present once it finished. */ +export interface AnalyzeSummary { + pending: number; + valid: number; + not_valid: number; + failed: number; +} + +/** An EEG analysis job in the background. */ +export interface AnalyzeJob { + id: string; + iniciado: string; + estado: JobState; + codigo: number | null; + salida: string; + error: string; + cluster: ClusterChoice | null; + ids: (number | string)[] | null; + summary: AnalyzeSummary | null; +} + +/** Live progress of a training or analysis run. */ +export interface RunProgress { + updated_at: string; + phase: string; + done: number; + total: number; + elapsed_s: number; + eta_s: number | null; + tasks: { processing: number; waiting: number; memory: number; erred: number } | null; + cluster: { + mode: ClusterMode; + scheduler: string | null; + workers: WorkerSample[]; + cpu_pct: number; + memory_pct: number; + } | null; + history: { t: number; done: number; cpu_pct: number; memory_pct: number }[]; +} + +/** One Dask worker sample inside a run's progress. */ +export interface WorkerSample { + name: string; + cpu_pct: number; + memory_bytes: number; + memory_limit: number | null; + executing: number; + threads: number; +} + +/** A stored baseline curve for one metric. */ +export interface BaselineCurve { + scenario: string; + version: number; + metric: string; + edad_meses: number[]; + p5: number[]; + p25: number[]; + mediana: number[]; + p75: number[]; + p95: number[]; +} + +/** One EEG's metric values with their z scores against the baseline. */ +export interface EegMetrics { + eeg_id: EegId; + valid: boolean | null; + level: string | null; + age_months: number | null; + metrics: { name: string; value: number; z: number | null; outside: -1 | 0 | 1 | null; model: string | null }[]; +} + +export type EegId = number | string; + +/** One EEG of the catalog, as listed for the analysis step's ticked list. */ +export interface EegListItem { + id: EegId; + lab_id: string | null; + patient_id: number | null; + study_date: string | null; + valid: boolean | null; + analysed: boolean; +} + +/** The answer to uploading one `.edf`: 201. */ +export interface EegUploadResult { + eeg_id: EegId | null; + lab_id: string | null; + created: boolean; +} + +/** Catalog counts for the result step. */ +export interface EegSummary { + eegs: number; + analysed: number; + valid: number; + not_valid: number; + failed: number; + metrics: number; + metrics_with_z: number; + high: number; + low: number; + fhir_eegs: number; + fhir_metrics: number; +} diff --git a/src/app/governance/components/analyze-step/analyze-step.html b/src/app/governance/components/analyze-step/analyze-step.html new file mode 100644 index 0000000..7f6657a --- /dev/null +++ b/src/app/governance/components/analyze-step/analyze-step.html @@ -0,0 +1,53 @@ +

Alcance del análisis

+ + Pendientes + Primeros N + EEGs elegidos + +@if (scope() === 'limit') { +
+} +@if (scope() === 'selected') { + +} +
+ + +
+@if (actionError()) {

{{ actionError() }}

} +@if (cycleMessage()) {

{{ cycleMessage() }}

} +@if (loading()) {

Cargando análisis…

} +@if (jobError()) { +

{{ jobError() }}

+ +} @else if (!loading() && !job()) {

Todavía no hay análisis de EEG.

} + +@if (job(); as current) { +

Último análisis · {{ states[current.estado] }}

+ + @if (current.summary; as summary) { +
+
Pendientes
{{ summary.pending }}
+
Válidos
{{ summary.valid }}
+
No válidos
{{ summary.not_valid }}
+
Fallidos
{{ summary.failed }}
+
+ } + @if (current.error) {

{{ current.error }}

} + @if (current.salida) { +
Ver últimas líneas de salida
{{ current.salida }}
+ } +} + +
+ Subir EDF +
+ + + +
+ @if (uploadError()) {

{{ uploadError() }}

} + @if (uploaded(); as result) { +

EEG {{ result.eeg_id ?? '—' }} · Laboratorio {{ result.lab_id ?? '—' }} · {{ result.created ? 'Creado' : 'Actualizado' }}

+ } +
diff --git a/src/app/governance/components/analyze-step/analyze-step.scss b/src/app/governance/components/analyze-step/analyze-step.scss new file mode 100644 index 0000000..c565b5d --- /dev/null +++ b/src/app/governance/components/analyze-step/analyze-step.scss @@ -0,0 +1,4 @@ +dl { display: flex; flex-wrap: wrap; gap: 1rem; } +dd { margin: 0; font-weight: 600; } +pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 16rem; overflow: auto; } +.upload { border-top: 1px solid var(--mat-sys-outline-variant); margin-block-start: 1rem; padding-block: .75rem; } diff --git a/src/app/governance/components/analyze-step/analyze-step.spec.ts b/src/app/governance/components/analyze-step/analyze-step.spec.ts new file mode 100644 index 0000000..238c1d1 --- /dev/null +++ b/src/app/governance/components/analyze-step/analyze-step.spec.ts @@ -0,0 +1,138 @@ +/** Pins analysis, conflict recovery and EDF uploads against mocked HTTP jobs and catalog rows. */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { AnalyzeJob } from '../../api/tea-eeg.types'; +import { AnalyzeStepComponent } from './analyze-step'; + +const jobs = '/governance/tea/eeg/analyze-jobs'; +const progress = '/governance/tea/jobs/analyze/a1/progress'; +const upload = '/governance/tea/eeg/upload'; + +// A running job discovered on conflict or returned by a successful start. +const running: AnalyzeJob = { + id: 'a1', iniciado: '2026-11-23T00:00:00Z', estado: 'en_curso', codigo: null, + salida: '', error: '', cluster: null, ids: null, summary: null, +}; + +describe('AnalyzeStepComponent', () => { + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + /** Creates the step with a remote choice and an empty analysis history. */ + function create() { + const fixture = TestBed.createComponent(AnalyzeStepComponent); + fixture.componentRef.setInput('choice', { mode: 'remote', scheduler: 'tcp://equipo:8786' }); + fixture.detectChanges(); + http.expectOne(jobs).flush([]); + return fixture; + } + + /** Fails if the limit or cluster is omitted, polling stops early, or final results are hidden. */ + it('starts a bounded run and displays its final summary and tail', () => { + vi.useFakeTimers(); + try { + const fixture = create(); + const step = fixture.componentInstance; + step.scope.set('limit'); + step.limit.set(5); + step.analyze(); + const request = http.expectOne(jobs); + expect(request.request.body).toEqual({ limit: 5, cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } }); + request.flush(running); + fixture.detectChanges(); + http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' }); + vi.advanceTimersByTime(2000); + const runningProgress = http.expectOne(progress); + http.expectOne(`${jobs}/a1`).flush({ + ...running, estado: 'completado', codigo: 0, salida: 'EEG 14 procesado', + summary: { pending: 1, valid: 2, not_valid: 1, failed: 1 }, + }); + fixture.detectChanges(); + expect(runningProgress.cancelled).toBe(true); + http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' }); + expect(fixture.nativeElement.textContent).toContain('EEG 14 procesado'); + expect(fixture.nativeElement.querySelector('dd').textContent).toBe('1'); + vi.advanceTimersByTime(2000); + http.expectNone(`${jobs}/a1`); + fixture.destroy(); + } finally { + vi.useRealTimers(); + } + }); + + /** Fails if pending scope requests a full rerun, a conflict hides the active job, or an unknown EEG is silent. */ + it('recovers the active job on conflict and explains unknown EEGs', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.analyze(); + const missing = http.expectOne(jobs); + expect(missing.request.body).toEqual({ cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } }); + missing.flush(null, { status: 404, statusText: 'Not Found' }); + expect(step.actionError()).toContain('No se encontró'); + + step.analyze(); + http.expectOne(jobs).flush(null, { status: 409, statusText: 'Conflict' }); + http.expectOne(jobs).flush([running]); + fixture.detectChanges(); + http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' }); + expect(fixture.nativeElement.textContent).toContain('Ya hay un análisis de EEG en curso.'); + expect(step.canAnalyze()).toBe(false); + }); + + /** Fails if an invalid EDF gets selected, or a successful upload fails to tick its catalog row. */ + it('keeps a failed EDF retryable and ticks the successfully uploaded EEG', async () => { + const fixture = create(); + const step = fixture.componentInstance; + const input: HTMLInputElement = fixture.nativeElement.querySelector('input[type=file]'); + step.file.set(new File(['edf'], 'estudio.edf')); + step.patientId.set(42); + step.upload(input); + const failed = http.expectOne(upload); + expect(failed.request.body.get('patient_id')).toBe('42'); + failed.flush({ error: 'EDF inválido' }, { status: 400, statusText: 'Bad Request' }); + expect(step.uploadError()).toBe('EDF inválido'); + expect(step.selected()).toEqual([]); + expect(step.canUpload()).toBe(true); + + step.upload(input); + http.expectOne(upload).flush({ eeg_id: '8', lab_id: 'LAB-8', created: true }); + fixture.detectChanges(); + http.expectOne((req) => req.url === '/governance/tea/eeg').flush([ + { id: 8, lab_id: 'LAB-8', patient_id: 42, study_date: null, valid: null, analysed: false }, + ]); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('input[type=checkbox]').checked).toBe(true); + expect(fixture.nativeElement.textContent).toContain('Creado'); + }); + + /** Fails if the analysis by selection stops sending UUID ids, which real EEGs carry, as text. */ + it('analyses chosen EEGs by their UUID ids', () => { + const fixture = create(); + const step = fixture.componentInstance; + const uuid = 'ed257fbd-61d5-4c9c-bb72-00c4ec550961'; + step.scope.set('selected'); + step.selected.set([uuid]); + expect(step.canAnalyze()).toBe(true); + step.analyze(); + const request = http.expectOne('/governance/tea/eeg/analyze-jobs'); + expect(request.request.body.ids).toEqual([uuid]); + request.flush({ id: 'j1', estado: 'en_curso', ids: [uuid], cluster: null, summary: null, salida: '', error: '', codigo: null, iniciado: '' }); + }); + + /** Fails if the TEA indicator cycle loses the selected cluster. */ + it('requests the indicator cycle on the selected cluster', () => { + const fixture = create(); + fixture.componentInstance.recalculate(); + const request = http.expectOne('/reportes/indicadores/tea/recalcular'); + expect(request.request.body).toEqual({ cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } }); + request.flush({ pendiente: true }); + expect(fixture.componentInstance.cycleMessage()).toContain('Pendiente'); + }); +}); diff --git a/src/app/governance/components/analyze-step/analyze-step.ts b/src/app/governance/components/analyze-step/analyze-step.ts new file mode 100644 index 0000000..1341304 --- /dev/null +++ b/src/app/governance/components/analyze-step/analyze-step.ts @@ -0,0 +1,161 @@ +import { Component, DestroyRef, OnInit, computed, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatRadioModule } from '@angular/material/radio'; +import { finalize, exhaustMap, catchError, EMPTY, timer } from 'rxjs'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { TeaEegApi } from '../../api/tea-eeg.api'; +import { AnalyzeBody, AnalyzeJob, ClusterChoice, EegId, EegUploadResult, JobState } from '../../api/tea-eeg.types'; +import { EegPicker } from '../eeg-picker/eeg-picker'; +import { RunMonitorComponent } from '../run-monitor/run-monitor'; + +@Component({ + selector: 'app-analyze-step', + imports: [EegPicker, FormsModule, MatButtonModule, MatRadioModule, RunMonitorComponent], + templateUrl: './analyze-step.html', + styleUrls: ['../eeg-step.scss', './analyze-step.scss'], +}) +export class AnalyzeStepComponent implements OnInit { + private readonly api = inject(TeaEegApi); + private readonly destroyRef = inject(DestroyRef); + readonly choice = input({ mode: 'auto' }); + readonly scope = signal<'pending' | 'limit' | 'selected'>('pending'); + readonly limit = signal(10); + readonly selected = signal([]); + readonly revision = signal(0); + readonly jobs = signal([]); + readonly job = computed(() => this.jobs().find((job) => job.estado === 'en_curso') ?? this.jobs()[0]); + private readonly runningId = computed(() => this.job()?.estado === 'en_curso' ? this.job()?.id : undefined); + readonly loading = signal(false); + readonly starting = signal(false); + readonly recalculating = signal(false); + readonly jobError = signal(''); + readonly actionError = signal(''); + readonly cycleMessage = signal(''); + readonly busy = computed(() => this.loading() || this.starting() || this.recalculating() || !!this.runningId()); + readonly canAnalyze = computed(() => !this.busy() && ( + this.scope() === 'pending' || + (this.scope() === 'selected' ? this.selected().length > 0 : positiveInteger(this.limit())) + )); + readonly file = signal(null); + readonly patientId = signal(null); + readonly uploading = signal(false); + readonly uploadError = signal(''); + readonly uploaded = signal(null); + readonly canUpload = computed(() => !this.uploading() && /\.edf$/i.test(this.file()?.name ?? '') && + (this.patientId() === null || (Number.isSafeInteger(this.patientId()) && this.patientId()! >= 0))); + readonly states: Record = { + en_curso: 'En curso', completado: 'Completado', entrenado_sin_promover: 'Completado', + fallido: 'Falló', interrumpido: 'Interrumpido', + }; + + constructor() { + effect((cleanup) => { + const id = this.runningId(); + if (!id) return; + const polling = timer(2000, 2000).pipe(exhaustMap(() => this.api.analyzeJob(id).pipe( + catchError((error) => { + this.jobError.set(apiErrorMessage(error, error.status === 404 + ? 'No se encontró el trabajo de análisis.' : 'No se pudo consultar el trabajo de análisis.')); + if (error.status === 404) this.jobs.update((jobs) => jobs.filter((job) => job.id !== id)); + return EMPTY; + }), + ))).subscribe((job) => { + this.jobError.set(''); + this.storeJob(job); + if (job.estado !== 'en_curso') this.revision.update((value) => value + 1); + }); + cleanup(() => polling.unsubscribe()); + }); + } + + ngOnInit(): void { + this.refreshJobs(); + } + + refreshJobs(): void { + if (this.loading()) return; + this.loading.set(true); + this.jobError.set(''); + this.api.analyzeJobs().pipe( + takeUntilDestroyed(this.destroyRef), finalize(() => this.loading.set(false)), + ).subscribe({ + next: (jobs) => this.jobs.set(jobs), + error: (error) => this.jobError.set(apiErrorMessage(error, 'No se pudieron cargar los análisis.')), + }); + } + + analyze(): void { + if (!this.canAnalyze()) return; + const body: AnalyzeBody = { cluster: this.choice() }; + if (this.scope() === 'limit') body.limit = this.limit()!; + if (this.scope() === 'selected') body.ids = this.selected(); + this.starting.set(true); + this.actionError.set(''); + this.api.startAnalyzeJob(body).pipe( + takeUntilDestroyed(this.destroyRef), finalize(() => this.starting.set(false)), + ).subscribe({ + next: (job) => this.storeJob(job), + error: (error) => { + const message = error.status === 409 ? 'Ya hay un análisis de EEG en curso.' + : error.status === 404 ? 'No se encontró uno de los EEGs elegidos.' : 'No se pudo iniciar el análisis.'; + this.actionError.set(apiErrorMessage(error, message)); + if (error.status === 409) this.refreshJobs(); + }, + }); + } + + recalculate(): void { + if (this.busy()) return; + this.recalculating.set(true); + this.actionError.set(''); + this.cycleMessage.set(''); + this.api.recalculateTeaIndicators(this.choice()).pipe( + takeUntilDestroyed(this.destroyRef), finalize(() => this.recalculating.set(false)), + ).subscribe({ + next: ({ pendiente }) => this.cycleMessage.set(pendiente ? 'Ciclo de indicadores solicitado. Pendiente de actualización.' : 'Solicitud de indicadores recibida.'), + error: (error) => this.actionError.set(apiErrorMessage(error, 'No se pudo ejecutar el ciclo de indicadores.')), + }); + } + + chooseFile(event: Event): void { + this.file.set((event.target as HTMLInputElement).files?.item(0) ?? null); + this.uploaded.set(null); + this.uploadError.set(''); + if (this.file() && !/\.edf$/i.test(this.file()!.name)) this.uploadError.set('Elige un archivo .edf.'); + } + + upload(fileInput: HTMLInputElement): void { + const file = this.file(); + if (!file || !this.canUpload()) return; + this.uploading.set(true); + this.uploadError.set(''); + this.uploaded.set(null); + this.api.uploadEeg(file, this.patientId() ?? undefined).pipe( + takeUntilDestroyed(this.destroyRef), finalize(() => this.uploading.set(false)), + ).subscribe({ + next: (result) => { + this.uploaded.set(result); + // The catalog lists canonical numeric keys as numbers and any other key (a UUID) as text. + const rawId = result.eeg_id; + const id = typeof rawId === 'string' && /^\d+$/.test(rawId) && String(Number(rawId)) === rawId + ? Number(rawId) : rawId; + if (id !== null) this.selected.update((ids) => ids.includes(id) ? ids : [...ids, id]); + this.scope.set('selected'); + this.revision.update((value) => value + 1); + this.file.set(null); + fileInput.value = ''; + }, + error: (error) => this.uploadError.set(apiErrorMessage(error, 'No se pudo subir el EDF.')), + }); + } + + private storeJob(job: AnalyzeJob): void { + this.jobs.update((jobs) => [job, ...jobs.filter((item) => item.id !== job.id)]); + } +} + +function positiveInteger(value: number | null): boolean { + return value !== null && Number.isSafeInteger(value) && value > 0; +} diff --git a/src/app/governance/components/baseline-check/baseline-check.html b/src/app/governance/components/baseline-check/baseline-check.html new file mode 100644 index 0000000..e3b714c --- /dev/null +++ b/src/app/governance/components/baseline-check/baseline-check.html @@ -0,0 +1,76 @@ +
+ + + + +
+@if (versions.isLoading() || metrics.isLoading() || curve.isLoading()) {

Cargando línea base…

} +@if (versions.error()) { +

No se pudieron cargar las versiones.

+} @else if (versions.hasValue() && !scenarios().length) {

No hay versiones de escenarios EEG.

} +@if (metrics.error()) { +

No se pudieron cargar las métricas de la línea base.

+} @else if (metrics.hasValue() && !metrics.value().length) {

Esta versión no tiene métricas con curvas.

} +@if (curve.error()) { +

No se pudo cargar la curva.

+} @else if (curve.hasValue() && !figure()) {

La curva no tiene datos.

} + +@if (figure(); as chart) { + + @if (curve.hasValue()) { + @let data = curve.value(); +
+ Ver valores de la curva +
+ + + + @for (age of data.edad_meses; track $index) { + + + } + +
Edad (meses)P5P25MedianaP75P95
{{ age }}{{ data.p5[$index] }}{{ data.p25[$index] }}{{ data.mediana[$index] }}{{ data.p75[$index] }}{{ data.p95[$index] }}
+
+
+ } +} +

EEGs para comparar

+ +@if (eegMetrics.isLoading()) {

Cargando métricas de los EEGs…

} +@else if (eegMetrics.error()) { +

No se pudieron cargar las métricas de los EEGs elegidos.

+ +} @else if (selected().length && metric() && !points().length) {

No hay EEGs elegidos con edad y valor para esta métrica.

} +@if (points().length) { +
+ Ver valores de los EEGs elegidos +
+ + + + @for (point of points(); track $index) { + + } + +
EEGEdad (meses)ValorClasificación
{{ point.id }}{{ point.age }}{{ point.value }}{{ point.label }}
+
+
+} diff --git a/src/app/governance/components/baseline-check/baseline-check.scss b/src/app/governance/components/baseline-check/baseline-check.scss new file mode 100644 index 0000000..deb5101 --- /dev/null +++ b/src/app/governance/components/baseline-check/baseline-check.scss @@ -0,0 +1,2 @@ +app-plotly-chart { --plot-height: 400px; --plot-min-width: 360px; } +details { margin-block: .5rem; } diff --git a/src/app/governance/components/baseline-check/baseline-check.spec.ts b/src/app/governance/components/baseline-check/baseline-check.spec.ts new file mode 100644 index 0000000..109f88e --- /dev/null +++ b/src/app/governance/components/baseline-check/baseline-check.spec.ts @@ -0,0 +1,77 @@ +/** Pins version filtering, percentile curves and EEG overlays with mocked HTTP responses. */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; +import { BaselineCheckComponent } from './baseline-check'; + +const baseline = '/governance/tea/baselines/eeg-posterior-rhythm/3'; + +describe('BaselineCheckComponent', () => { + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [ + provideHttpClient(), provideHttpClientTesting(), + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react: vi.fn(), purge: vi.fn() }) }, + ] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + /** Sets up an EEG version, an unrelated TEA version and an empty catalog page. */ + async function create() { + const fixture = TestBed.createComponent(BaselineCheckComponent); + fixture.detectChanges(); + const versions = http.expectOne((req) => req.url === '/governance/model-versions'); + expect(versions.request.params.get('domain')).toBe('tea'); + versions.flush({ model_versions: [ + { version: '3', tags: { scenario: 'eeg-posterior-rhythm' } }, + { version: '9', tags: { scenario: 'riesgo-tea' } }, + ] }); + http.expectOne((req) => req.url === '/governance/tea/eeg').flush([]); + await fixture.whenStable(); + const step = fixture.componentInstance; + expect(step.scenarios()).toEqual(['eeg-posterior-rhythm']); + step.chooseScenario('eeg-posterior-rhythm'); + step.chooseVersion(3); + fixture.detectChanges(); + http.expectOne(`${baseline}/metrics`).flush(['peak']); + await fixture.whenStable(); + step.metric.set('peak'); + return fixture; + } + + /** Fails if the two percentile bands, medians or labeled high/low/inside points are lost. */ + it('draws the age curve and classifies the selected EEG values', async () => { + const fixture = await create(); + const step = fixture.componentInstance; + step.selected.set([8]); + fixture.detectChanges(); + const curve = http.expectOne((req) => req.url === `${baseline}/curve`); + expect(curve.request.params.get('metric')).toBe('peak'); + curve.flush({ edad_meses: [24, 36], p5: [1, 2], p25: [2, 3], mediana: [3, 4], metric: 'peak', p75: [4, 5], p95: [5, 6] }); + http.expectOne('/governance/tea/eeg/8/metrics').flush({ eeg_id: 8, age_months: 30, metrics: [ + { name: 'peak', value: 0.5, outside: -1 }, + { name: 'peak', value: 3, outside: 0 }, + { name: 'peak', value: 8, outside: 1 }, + { name: 'other', value: 7, outside: 1 }, + ] }); + await fixture.whenStable(); + fixture.detectChanges(); + const traces = step.figure()?.data; + expect(traces?.map((trace) => trace['name'])).toEqual(['P5–P95', 'P25–P75', 'Mediana', 'Bajo', 'Dentro', 'Alto']); + expect(traces?.[5]).toMatchObject({ x: [30], y: [8], marker: { symbol: 'triangle-up' } }); + expect(fixture.nativeElement.textContent).toContain('Ver valores de la curva'); + }); + + /** Fails if a missing curve appears empty without surfacing the HTTP error and retry control. */ + it('shows a retry when a curve is unavailable', async () => { + const fixture = await create(); + fixture.detectChanges(); + http.expectOne((req) => req.url === `${baseline}/curve`).flush(null, { status: 404, statusText: 'Not Found' }); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('No se pudo cargar la curva.'); + expect(fixture.nativeElement.textContent).toContain('Reintentar'); + }); +}); diff --git a/src/app/governance/components/baseline-check/baseline-check.ts b/src/app/governance/components/baseline-check/baseline-check.ts new file mode 100644 index 0000000..c9bb553 --- /dev/null +++ b/src/app/governance/components/baseline-check/baseline-check.ts @@ -0,0 +1,74 @@ +import { Component, ElementRef, computed, inject, model, signal } from '@angular/core'; +import { rxResource } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { forkJoin } from 'rxjs'; +import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; +import { GovernanceApi } from '../../api/governance.api'; +import { TeaEegApi } from '../../api/tea-eeg.api'; +import { EegId, EegMetrics } from '../../api/tea-eeg.types'; +import { EegPicker } from '../eeg-picker/eeg-picker'; +import { baselineFigure, overlayPoints } from './baseline-figure'; + +@Component({ + selector: 'app-baseline-check', + imports: [EegPicker, FormsModule, MatButtonModule, MatTooltipModule, PlotlyChart], + templateUrl: './baseline-check.html', + styleUrls: ['../eeg-step.scss', './baseline-check.scss'], +}) +export class BaselineCheckComponent { + private readonly api = inject(TeaEegApi); + private readonly governance = inject(GovernanceApi); + private readonly host = inject>(ElementRef); + readonly scenario = signal(''); + readonly version = signal(null); + readonly metric = signal(''); + readonly selected = model([]); + readonly versions = rxResource({ + stream: () => this.governance.listModelVersions({ domain: 'tea' }), + }); + readonly eegVersions = computed(() => this.versions.hasValue() + ? this.versions.value().model_versions.filter((version) => version.tags.scenario?.startsWith('eeg-')) : []); + readonly scenarios = computed(() => [...new Set(this.eegVersions().map((version) => version.tags.scenario!))].sort()); + readonly versionOptions = computed(() => [...new Set(this.eegVersions() + .filter((version) => version.tags.scenario === this.scenario()) + .map((version) => Number(version.version)).filter((version) => Number.isSafeInteger(version) && version > 0))] + .sort((a, b) => b - a)); + readonly metrics = rxResource({ + params: () => { + const version = this.version(); + return version === null ? undefined : { scenario: this.scenario(), version }; + }, + stream: ({ params }) => this.api.baselineMetrics(params.scenario, params.version), + }); + readonly curve = rxResource({ + params: () => { + const version = this.version(); + const metric = this.metric(); + return version === null || !metric ? undefined : { scenario: this.scenario(), version, metric }; + }, + stream: ({ params }) => this.api.baselineCurve(params.scenario, params.version, params.metric), + }); + readonly eegMetrics = rxResource({ + params: () => this.selected().length && this.metric() ? this.selected() : undefined, + stream: ({ params }) => forkJoin(params.map((id) => this.api.eegMetrics(id))), + defaultValue: [] as EegMetrics[], + }); + readonly points = computed(() => overlayPoints(this.eegMetrics.hasValue() ? this.eegMetrics.value() : [], this.metric())); + readonly figure = computed(() => { + if (!this.curve.hasValue() || !this.curve.value().edad_meses.length) return null; + const style = getComputedStyle(this.host.nativeElement); + return baselineFigure(this.curve.value(), this.points(), (token) => style.getPropertyValue(`--eeg-${token}`).trim(), style.color); + }); + + chooseScenario(scenario: string): void { + this.scenario.set(scenario); + this.chooseVersion(null); + } + + chooseVersion(version: number | null): void { + this.version.set(version); + this.metric.set(''); + } +} diff --git a/src/app/governance/components/baseline-check/baseline-figure.ts b/src/app/governance/components/baseline-check/baseline-figure.ts new file mode 100644 index 0000000..b36e987 --- /dev/null +++ b/src/app/governance/components/baseline-check/baseline-figure.ts @@ -0,0 +1,53 @@ +import { PlotlyFigure } from '../../../features/indicadores/indicadores.models'; +import { BaselineCurve, EegMetrics } from '../../api/tea-eeg.types'; + +const OUTSIDE = [ + { flag: -1, label: 'Bajo', color: 'blue', symbol: 'triangle-down' }, + { flag: 0, label: 'Dentro', color: 'purple', symbol: 'circle' }, + { flag: 1, label: 'Alto', color: 'vermilion', symbol: 'triangle-up' }, + { flag: null, label: 'Sin clasificación', color: 'axis', symbol: 'diamond-open' }, +] as const; + +export function overlayPoints(eegs: EegMetrics[], metric: string) { + return eegs.flatMap((eeg) => eeg.age_months === null ? [] : eeg.metrics + .filter((item) => item.name === metric && Number.isFinite(item.value)) + .map((item) => ({ + id: eeg.eeg_id, + age: eeg.age_months!, + value: item.value, + outside: item.outside, + label: OUTSIDE.find((group) => group.flag === item.outside)?.label, + }))); +} + +export function baselineFigure( + curve: BaselineCurve, points: ReturnType, color: (token: string) => string, ink: string, +): PlotlyFigure { + const x = curve.edad_meses; + const band = (low: number[], high: number[], name: string, token: string) => ({ + type: 'scatter', mode: 'lines', name, x: [...x, ...[...x].reverse()], y: [...high, ...[...low].reverse()], + fill: 'toself', fillcolor: color(token), line: { width: 0 }, hoverinfo: 'skip', + }); + return { + data: [ + band(curve.p5, curve.p95, 'P5–P95', 'band-outer'), + band(curve.p25, curve.p75, 'P25–P75', 'band-inner'), + { type: 'scatter', mode: 'lines', name: 'Mediana', x, y: curve.mediana, line: { color: color('blue'), width: 2 } }, + ...OUTSIDE.flatMap(({ flag, label, color: token, symbol }) => { + const group = points.filter((point) => point.outside === flag); + return group.length ? [{ + type: 'scatter', mode: 'markers', name: label, + x: group.map((point) => point.age), y: group.map((point) => point.value), + text: group.map((point) => `EEG ${point.id}`), marker: { color: token === 'axis' ? ink : color(token), symbol, size: 10 }, + }] : []; + }), + ], + layout: { + autosize: true, height: 400, margin: { l: 65, r: 20, t: 20, b: 100 }, + paper_bgcolor: 'transparent', plot_bgcolor: 'transparent', font: { color: ink }, + xaxis: { title: { text: 'Edad (meses)' }, showgrid: false, zeroline: false }, + yaxis: { title: { text: curve.metric }, showgrid: false, zeroline: false }, + legend: { orientation: 'h', y: -.22 }, + }, + }; +} diff --git a/src/app/governance/components/cluster-health-card/cluster-health-card.html b/src/app/governance/components/cluster-health-card/cluster-health-card.html new file mode 100644 index 0000000..dbb7c60 --- /dev/null +++ b/src/app/governance/components/cluster-health-card/cluster-health-card.html @@ -0,0 +1,35 @@ +
+
+

Estado del clúster

+ + + @if (latencyMs() != null) { + Latencia: {{ latencyMs() }} ms + } @else { + Latencia: sin datos + } + + + +
+ + @if (loadError(); as error) { + + } + +
    + @for (row of rows(); track row.key) { +
  • + + {{ estados[row.state] }} + + {{ row.label }} + {{ row.detail }} +
  • + } +
+
diff --git a/src/app/governance/components/cluster-health-card/cluster-health-card.scss b/src/app/governance/components/cluster-health-card/cluster-health-card.scss new file mode 100644 index 0000000..34c7791 --- /dev/null +++ b/src/app/governance/components/cluster-health-card/cluster-health-card.scss @@ -0,0 +1,102 @@ +.health { + border: 1px solid var(--mat-sys-outline-variant); + display: flex; + flex-direction: column; + gap: var(--space-3); + padding: var(--space-3); +} + +.health__toolbar { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.health__title { + font: var(--mat-sys-title-small); + margin: 0; +} + +.health__spacer { + flex: 1; +} + +.health__latency { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.health__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.health__rows { + display: flex; + flex-direction: column; + gap: var(--space-1); + list-style: none; + margin: 0; + padding: 0; +} + +.health__row { + align-items: center; + border-left: 3px solid var(--mat-sys-outline); + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + padding: var(--space-1) var(--space-2); +} + +.health__check { + align-items: center; + display: inline-flex; + font: var(--mat-sys-label-medium); + gap: var(--space-1); + min-width: 96px; +} + +.health__row--ok { + border-left-color: var(--mat-sys-primary); +} + +.health__row--ok .health__check { + color: var(--mat-sys-primary); +} + +.health__row--warn { + border-left-color: #9a6a00; +} + +.health__row--warn .health__check { + color: #9a6a00; +} + +.health__row--fail { + border-left-color: var(--mat-sys-error); +} + +.health__row--fail .health__check { + color: var(--mat-sys-error); +} + +.health__row--unknown .health__check { + color: var(--mat-sys-on-surface-variant); +} + +.health__label { + font: var(--mat-sys-body-medium); + min-width: 160px; +} + +.health__detail { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} diff --git a/src/app/governance/components/cluster-health-card/cluster-health-card.spec.ts b/src/app/governance/components/cluster-health-card/cluster-health-card.spec.ts new file mode 100644 index 0000000..f84a06c --- /dev/null +++ b/src/app/governance/components/cluster-health-card/cluster-health-card.spec.ts @@ -0,0 +1,193 @@ +/** + * Covers the cluster health card's reading of `ClusterStatus`: one labelled row per check with green / + * amber / red states, the dashboard button gating and its tooltip, the manual re-check, re-checking on + * a cluster change, and the 30 s polling that skips a hidden page. Fixtures: canned `ClusterStatus` + * answers through `HttpTestingController`. + */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { MatTooltip } from '@angular/material/tooltip'; +import { By } from '@angular/platform-browser'; +import { ClusterChoice, ClusterStatus } from '../../api/tea-eeg.types'; +import { ClusterHealthCard } from './cluster-health-card'; + +const CLUSTER_URL = '/governance/tea/cluster'; + +// Base answer: everything unchecked; tests override what they pin down. +function status(partial: Partial): ClusterStatus { + return { + mode: 'auto', scheduler: null, reachable: false, workers: null, expected_workers: null, + versions_ok: null, version_error: null, dashboard_ok: null, dashboard_url: null, + reference: null, latency_ms: null, error: null, ...partial, + }; +} + +const OK = status({ + mode: 'remote', scheduler: 'tcp://equipo:8786', reachable: true, workers: 4, expected_workers: 4, + versions_ok: true, dashboard_ok: true, dashboard_url: 'http://equipo:8787/status', + reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42, +}); + +describe('ClusterHealthCard', () => { + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + function expectCluster() { + return http.expectOne((r) => r.url === CLUSTER_URL); + } + + function create(choice: ClusterChoice = { mode: 'auto' }): ComponentFixture { + const fixture = TestBed.createComponent(ClusterHealthCard); + fixture.componentRef.setInput('choice', choice); + fixture.detectChanges(); + expectCluster().flush(OK); + fixture.detectChanges(); + return fixture; + } + + function rows(fixture: ComponentFixture): { state: string; text: string }[] { + const states = ['ok', 'warn', 'fail', 'unknown']; + return Array.from(fixture.nativeElement.querySelectorAll('.health__row')).map((el) => ({ + state: states.find((s) => el.classList.contains(`health__row--${s}`)) ?? 'none', + // The icon's ligature would glue onto the label, so text nodes are read apart from it. + text: ['.health__check', '.health__label', '.health__detail'] + .map((sel) => + Array.from(el.querySelector(sel)!.childNodes) + .filter((node) => node.nodeType === Node.TEXT_NODE) + .map((node) => node.textContent ?? '') + .join('') + .replace(/\s+/g, ' ') + .trim(), + ) + .join(' '), + })); + } + + function dashboardTooltip(fixture: ComponentFixture): MatTooltip { + return fixture.debugElement.query(By.css('.health__dashboard'))!.injector.get(MatTooltip); + } + + function dashboardButton(fixture: ComponentFixture): HTMLButtonElement { + return Array.from(fixture.nativeElement.querySelectorAll('button')).find((b) => + b.textContent?.includes('Abrir dashboard de Dask'), + )!; + } + + // Fails if an unreachable scheduler stops failing the scheduler row while the other checks go + // unknown instead of pretending a result. + it('shows an unreachable cluster as a failed scheduler and unchecked rows', () => { + const fixture = TestBed.createComponent(ClusterHealthCard); + fixture.detectChanges(); + expectCluster().flush(status({ reachable: false, error: 'Conexión rechazada' })); + fixture.detectChanges(); + + expect(rows(fixture)).toEqual([ + { state: 'fail', text: 'Error Scheduler Conexión rechazada' }, + { state: 'unknown', text: 'Sin datos Trabajadores Sin datos' }, + { state: 'unknown', text: 'Sin datos Versiones Sin datos' }, + { state: 'unknown', text: 'Sin datos Dashboard No aplica en este modo' }, + { state: 'unknown', text: 'Sin datos Volumen de referencia No verificado' }, + ]); + expect(fixture.nativeElement.textContent).toContain('Latencia: sin datos'); + }); + + // Fails if a version mismatch stops failing the versions row with the server's message, or a short + // worker count stops being a warning. + it('flags a version mismatch and a short worker count, and keeps the rest green', () => { + const fixture = create(); + const mismatch = status({ + mode: 'remote', scheduler: 'tcp://equipo:8786', reachable: true, workers: 3, expected_workers: 4, + versions_ok: false, version_error: 'cliente 2026.9 vs trabajadores 2026.8', + dashboard_ok: true, dashboard_url: 'http://equipo:8787/status', + reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42, + }); + fixture.componentInstance.status.set(mismatch); + fixture.detectChanges(); + + expect(rows(fixture)).toEqual([ + { state: 'ok', text: 'Correcto Scheduler tcp://equipo:8786' }, + { state: 'warn', text: 'Aviso Trabajadores 3 de 4 esperados' }, + { state: 'fail', text: 'Error Versiones cliente 2026.9 vs trabajadores 2026.8' }, + { state: 'ok', text: 'Correcto Dashboard http://equipo:8787/status' }, + { state: 'ok', text: 'Correcto Volumen de referencia referencia_2026 · 120 EDF' }, + ]); + expect(fixture.nativeElement.textContent).toContain('Latencia: 42 ms'); + }); + + // Fails if every check is not green on a healthy cluster, or the latency line disappears. + it('shows a healthy cluster all green with its latency', () => { + const fixture = create(); + expect(rows(fixture).every((r) => r.state === 'ok')).toBe(true); + expect(fixture.nativeElement.textContent).toContain('Latencia: 42 ms'); + }); + + // Fails if the dashboard button opens while the dashboard doesn't answer, or loses its why-tooltip. + it('opens the dashboard only when it answers, with a tooltip that says why otherwise', () => { + const fixture = create(); + const button = dashboardButton(fixture); + expect(button.disabled).toBe(false); + expect(dashboardTooltip(fixture).message).toContain('pestaña nueva'); + + fixture.componentInstance.status.set(status({ reachable: true, mode: 'local', dashboard_ok: null })); + fixture.detectChanges(); + expect(dashboardButton(fixture).disabled).toBe(true); + expect(dashboardTooltip(fixture).message).toContain('no está disponible'); + + fixture.componentInstance.status.set(status({ + reachable: true, mode: 'remote', scheduler: 'tcp://equipo:8786', dashboard_ok: false, + })); + fixture.detectChanges(); + expect(dashboardButton(fixture).disabled).toBe(true); + expect(dashboardTooltip(fixture).message).toContain('no responde'); + }); + + // Fails if the Verificar button stops asking for a fresh status, or the answer doesn't replace the rows. + it('re-checks on demand with the Verificar button', () => { + const fixture = create(); + const button = Array.from(fixture.nativeElement.querySelectorAll('button')).find((b) => + b.textContent?.includes('Verificar'), + )!; + button.click(); + expectCluster().flush(status({ reachable: false, error: 'Se cayó el scheduler' })); + fixture.detectChanges(); + expect(rows(fixture)[0]).toEqual({ state: 'fail', text: 'Error Scheduler Se cayó el scheduler' }); + }); + + // Fails if changing the picked cluster stops triggering a new check with the new params. + it('re-checks with the params when the picked cluster changes', () => { + const fixture = create({ mode: 'auto' }); + http.expectNone(() => true); + + fixture.componentRef.setInput('choice', { mode: 'remote', scheduler: 'tcp://equipo:8786' }); + fixture.detectChanges(); + const req = expectCluster(); + expect(req.request.params.get('mode')).toBe('remote'); + expect(req.request.params.get('scheduler')).toBe('tcp://equipo:8786'); + req.flush(OK); + }); + + // Fails if the 30 s polling is dropped, or stops skipping while the page is hidden. + it('re-checks every 30 s while visible and stays quiet while hidden', () => { + vi.useFakeTimers(); + try { + const fixture = create(); + vi.advanceTimersByTime(30000); + expectCluster().flush(OK); + + const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'hidden'); + Object.defineProperty(document, 'hidden', { configurable: true, value: true }); + vi.advanceTimersByTime(30000); + http.expectNone(() => true); + Object.defineProperty(document, 'hidden', descriptor ?? { configurable: true, value: false }); + fixture.destroy(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/src/app/governance/components/cluster-health-card/cluster-health-card.ts b/src/app/governance/components/cluster-health-card/cluster-health-card.ts new file mode 100644 index 0000000..9e035c0 --- /dev/null +++ b/src/app/governance/components/cluster-health-card/cluster-health-card.ts @@ -0,0 +1,153 @@ +import { NgClass } from '@angular/common'; +import { Component, DestroyRef, effect, inject, input, signal, computed } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { timer } from 'rxjs'; +import { apiErrorMessage } from '../../../connect/api/api.types'; +import { TeaEegApi } from '../../api/tea-eeg.api'; +import { ClusterChoice, ClusterStatus } from '../../api/tea-eeg.types'; + +/** Milliseconds between health checks while the page is visible. */ +export const REFRESCO_MS = 30000; + +export type CheckState = 'ok' | 'warn' | 'fail' | 'unknown'; + +/** Text label per state, so the row never relies on colour alone. */ +export const ESTADO_ETIQUETA: Record = { + ok: 'Correcto', + warn: 'Aviso', + fail: 'Error', + unknown: 'Sin datos', +}; + +const ICONOS: Record = { + ok: 'check_circle', + warn: 'warning', + fail: 'error', + unknown: 'help', +}; + +/** One row of the health card: a check, its state and a text detail. */ +export interface HealthCheckRow { + key: 'scheduler' | 'workers' | 'versions' | 'dashboard' | 'reference'; + label: string; + state: CheckState; + detail: string; +} + +/** + * The picked cluster's health: scheduler reachability, worker count against the expected one, version + * match, dashboard and the reference volume seen from a worker. Re-checked on demand and every 30 s + * while the page is visible; the dashboard opens in its own tab only when it answers. + */ +@Component({ + selector: 'app-cluster-health-card', + imports: [MatButtonModule, MatIconModule, MatTooltipModule, NgClass], + templateUrl: './cluster-health-card.html', + styleUrl: './cluster-health-card.scss', +}) +export class ClusterHealthCard { + private readonly api = inject(TeaEegApi); + private readonly destroyRef = inject(DestroyRef); + + /** The cluster to check; changing it re-checks. */ + readonly choice = input({ mode: 'auto' }); + readonly status = signal(null); + readonly loadError = signal(null); + readonly loading = signal(false); + + readonly rows = computed(() => { + const s = this.status(); + if (!s) return []; + return [schedulerRow(s), workersRow(s), versionsRow(s), dashboardRow(s), referenceRow(s)]; + }); + /** Enabled only when the dashboard answers; the tooltip says why otherwise. */ + readonly dashboardEnabled = computed(() => !!clusterDashboardUrl(this.status())); + readonly latencyMs = computed(() => this.status()?.latency_ms ?? null); + readonly dashboardTooltip = computed(() => { + const s = this.status(); + if (s?.dashboard_ok === true) return 'Abrir el dashboard de Dask en una pestaña nueva'; + if (s?.dashboard_ok === false) return 'El dashboard no responde; no se puede abrir'; + return 'El dashboard no está disponible en este modo'; + }); + + constructor() { + effect(() => { + this.choice(); + this.refresh(); + }); + timer(REFRESCO_MS, REFRESCO_MS) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + if (!document.hidden) this.refresh(); + }); + } + + refresh(): void { + this.loading.set(true); + this.api.clusterStatus(this.choice()).subscribe({ + next: (status) => { + this.loading.set(false); + this.status.set(status); + this.loadError.set(null); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudo consultar el estado del clúster.')); + }, + }); + } + + openDashboard(): void { + const url = clusterDashboardUrl(this.status()); + if (!url) return; + window.open(url, '_blank', 'noopener'); + } + + iconFor(state: CheckState): string { + return ICONOS[state]; + } + + protected readonly estados = ESTADO_ETIQUETA; +} + +export function clusterDashboardUrl(status: ClusterStatus | null): string | null { + return status?.dashboard_ok === true ? status.dashboard_url : null; +} + +function schedulerRow(s: ClusterStatus): HealthCheckRow { + if (!s.reachable) { + return { key: 'scheduler', label: 'Scheduler', state: 'fail', detail: s.error ?? 'No responde' }; + } + return { key: 'scheduler', label: 'Scheduler', state: 'ok', detail: s.scheduler ?? 'Clúster local' }; +} + +function workersRow(s: ClusterStatus): HealthCheckRow { + if (s.workers === null) return { key: 'workers', label: 'Trabajadores', state: 'unknown', detail: 'Sin datos' }; + if (s.expected_workers === null) { + return { key: 'workers', label: 'Trabajadores', state: 'ok', detail: `${s.workers}` }; + } + if (s.workers >= s.expected_workers) { + return { key: 'workers', label: 'Trabajadores', state: 'ok', detail: `${s.workers} de ${s.expected_workers}` }; + } + return { key: 'workers', label: 'Trabajadores', state: 'warn', detail: `${s.workers} de ${s.expected_workers} esperados` }; +} + +function versionsRow(s: ClusterStatus): HealthCheckRow { + if (s.versions_ok === null) return { key: 'versions', label: 'Versiones', state: 'unknown', detail: 'Sin datos' }; + if (s.versions_ok) return { key: 'versions', label: 'Versiones', state: 'ok', detail: 'Cliente y trabajadores coinciden' }; + return { key: 'versions', label: 'Versiones', state: 'fail', detail: s.version_error ?? 'No coinciden' }; +} + +function dashboardRow(s: ClusterStatus): HealthCheckRow { + if (s.dashboard_ok === null) return { key: 'dashboard', label: 'Dashboard', state: 'unknown', detail: 'No aplica en este modo' }; + if (s.dashboard_ok) return { key: 'dashboard', label: 'Dashboard', state: 'ok', detail: s.dashboard_url ?? 'Disponible' }; + return { key: 'dashboard', label: 'Dashboard', state: 'fail', detail: 'No responde' }; +} + +function referenceRow(s: ClusterStatus): HealthCheckRow { + if (!s.reference) return { key: 'reference', label: 'Volumen de referencia', state: 'unknown', detail: 'No verificado' }; + return { key: 'reference', label: 'Volumen de referencia', state: 'ok', detail: `${s.reference.name} · ${s.reference.edfs} EDF` }; +} diff --git a/src/app/governance/components/cluster-selector/cluster-selector.html b/src/app/governance/components/cluster-selector/cluster-selector.html new file mode 100644 index 0000000..0ed0cb9 --- /dev/null +++ b/src/app/governance/components/cluster-selector/cluster-selector.html @@ -0,0 +1,13 @@ +
+ + @for (modo of modos; track modo[0]) { + {{ modo[1] }} + } + + @if (choice().mode === 'remote') { + + Dirección del scheduler + + + } +
diff --git a/src/app/governance/components/cluster-selector/cluster-selector.scss b/src/app/governance/components/cluster-selector/cluster-selector.scss new file mode 100644 index 0000000..c917ca4 --- /dev/null +++ b/src/app/governance/components/cluster-selector/cluster-selector.scss @@ -0,0 +1,10 @@ +.cluster-selector { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.cluster-selector__scheduler { + min-width: 280px; +} diff --git a/src/app/governance/components/cluster-selector/cluster-selector.spec.ts b/src/app/governance/components/cluster-selector/cluster-selector.spec.ts new file mode 100644 index 0000000..d8b6417 --- /dev/null +++ b/src/app/governance/components/cluster-selector/cluster-selector.spec.ts @@ -0,0 +1,58 @@ +/** + * Covers the cluster selector's model: the toggle picks the mode, choosing remote exposes a scheduler + * field whose text joins the choice, and leaving remote drops the scheduler again. The component does + * no HTTP, so fixtures are only the rendered component. + */ +import { TestBed } from '@angular/core/testing'; +import { ClusterSelector } from './cluster-selector'; + +describe('ClusterSelector', () => { + function create() { + TestBed.configureTestingModule({ imports: [ClusterSelector] }); + const fixture = TestBed.createComponent(ClusterSelector); + fixture.detectChanges(); + return fixture; + } + + // Fails if the initial mode stops being 'auto', or the scheduler field shows before remote is picked. + it('starts on auto with the scheduler field hidden', () => { + const fixture = create(); + expect(fixture.componentInstance.choice()).toEqual({ mode: 'auto' }); + expect(fixture.nativeElement.querySelector('.cluster-selector__scheduler')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('Remoto'); + }); + + // Fails if picking remote stops asking for the scheduler, or its text stops joining the choice. + it('adds the scheduler address to the choice only while remote is selected', () => { + const fixture = create(); + const selector = fixture.componentInstance; + + selector.setMode('remote'); + fixture.detectChanges(); + expect(selector.choice()).toEqual({ mode: 'remote' }); + expect(fixture.nativeElement.querySelector('.cluster-selector__scheduler')).not.toBeNull(); + + selector.scheduler.setValue('tcp://equipo:8786'); + expect(selector.choice()).toEqual({ mode: 'remote', scheduler: 'tcp://equipo:8786' }); + + selector.setMode('local'); + fixture.detectChanges(); + expect(selector.choice()).toEqual({ mode: 'local' }); + expect(fixture.nativeElement.querySelector('.cluster-selector__scheduler')).toBeNull(); + }); + + // Fails if the typed address is lost on a round trip, or an empty one is sent as an empty string. + it('keeps the typed address across modes and drops it when empty', () => { + const fixture = create(); + const selector = fixture.componentInstance; + + selector.setMode('remote'); + selector.scheduler.setValue('tcp://equipo:8786'); + selector.setMode('sync'); + selector.setMode('remote'); + expect(selector.choice()).toEqual({ mode: 'remote', scheduler: 'tcp://equipo:8786' }); + + selector.scheduler.setValue(' '); + expect(selector.choice()).toEqual({ mode: 'remote' }); + }); +}); diff --git a/src/app/governance/components/cluster-selector/cluster-selector.ts b/src/app/governance/components/cluster-selector/cluster-selector.ts new file mode 100644 index 0000000..e318028 --- /dev/null +++ b/src/app/governance/components/cluster-selector/cluster-selector.ts @@ -0,0 +1,44 @@ +import { Component, DestroyRef, inject, model } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { ClusterChoice, ClusterMode } from '../../api/tea-eeg.types'; + +export const MODO_ETIQUETA: Record = { + auto: 'Auto', + local: 'Local', + remote: 'Remoto', + sync: 'Sync', +}; + +/** Where the TEA·EEG work runs. Remote asks for the scheduler address; the address is kept while + * another mode is selected so switching back doesn't lose it. */ +@Component({ + selector: 'app-cluster-selector', + imports: [MatButtonToggleModule, MatFormFieldModule, MatInputModule, ReactiveFormsModule], + templateUrl: './cluster-selector.html', + styleUrl: './cluster-selector.scss', +}) +export class ClusterSelector { + private readonly destroyRef = inject(DestroyRef); + + /** The picked mode and, for 'remote', the scheduler address. */ + readonly choice = model({ mode: 'auto' }); + readonly modos = (Object.entries(MODO_ETIQUETA) as [ClusterMode, string][]); + readonly scheduler = new FormControl('', { nonNullable: true }); + + constructor() { + this.scheduler.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((value) => this.applyScheduler(value)); + } + + setMode(mode: ClusterMode): void { + this.choice.set(mode === 'remote' ? { mode, scheduler: this.scheduler.value.trim() || undefined } : { mode }); + } + + private applyScheduler(value: string): void { + if (this.choice().mode !== 'remote') return; + this.choice.set({ mode: 'remote', scheduler: value.trim() || undefined }); + } +} diff --git a/src/app/governance/components/eeg-picker/eeg-picker.spec.ts b/src/app/governance/components/eeg-picker/eeg-picker.spec.ts new file mode 100644 index 0000000..d73cbaf --- /dev/null +++ b/src/app/governance/components/eeg-picker/eeg-picker.spec.ts @@ -0,0 +1,39 @@ +/** Pins paging and retained EEG choices with mocked catalog pages and a failed request. */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { EegPicker } from './eeg-picker'; + +describe('EegPicker', () => { + /** Fails if a page exceeds 50 rows, a new page loses selections, or a failed page cannot be retried. */ + it('keeps checked EEGs through paging and offers retry on failure', async () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const http = TestBed.inject(HttpTestingController); + const fixture = TestBed.createComponent(EegPicker); + fixture.detectChanges(); + const first = http.expectOne('/governance/tea/eeg?limit=50&offset=0'); + // A full first page permits forward navigation. + first.flush(Array.from({ length: 50 }, (_, id) => ({ + id, lab_id: 'LAB-' + id, study_date: null, patient_id: null, valid: null, analysed: false, + }))); + await fixture.whenStable(); + fixture.detectChanges(); + fixture.nativeElement.querySelector('input').click(); + const next = Array.from(fixture.nativeElement.querySelectorAll('button') as NodeListOf) + .find((button) => button.textContent?.includes('Siguiente'))!; + next.click(); + fixture.detectChanges(); + http.expectOne('/governance/tea/eeg?limit=50&offset=50').flush(null, { status: 500, statusText: 'Server Error' }); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.componentInstance.selected()).toEqual([0]); + expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('No se pudieron cargar los EEGs.'); + fixture.nativeElement.querySelector('button').click(); + fixture.detectChanges(); + http.expectOne('/governance/tea/eeg?limit=50&offset=50').flush([]); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay EEGs en esta página.'); + http.verify(); + }); +}); diff --git a/src/app/governance/components/eeg-picker/eeg-picker.ts b/src/app/governance/components/eeg-picker/eeg-picker.ts new file mode 100644 index 0000000..3e9d452 --- /dev/null +++ b/src/app/governance/components/eeg-picker/eeg-picker.ts @@ -0,0 +1,60 @@ +import { DatePipe } from '@angular/common'; +import { Component, inject, input, linkedSignal, model } from '@angular/core'; +import { rxResource } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { EegId } from '../../api/tea-eeg.types'; +import { TeaEegApi } from '../../api/tea-eeg.api'; + +@Component({ + selector: 'app-eeg-picker', + imports: [DatePipe, MatButtonModule], + styleUrl: '../eeg-step.scss', + template: ` + @if (page.isLoading()) {

Cargando EEGs…

} + @else if (page.error()) { +

No se pudieron cargar los EEGs.

+ + } @else if (!page.value()?.length) {

No hay EEGs en esta página.

} + @if (page.hasValue() && page.value().length) { +
+ + + + @for (eeg of page.value(); track eeg.id) { + + + + + + + } + +
ElegirID de laboratorioPacienteFechaVálidoAnalizado
{{ eeg.lab_id ?? '—' }}{{ eeg.patient_id ?? '—' }}{{ (eeg.study_date | date: 'mediumDate') ?? '—' }}{{ eeg.valid === null ? '—' : eeg.valid ? 'Sí' : 'No' }}{{ eeg.analysed ? 'Sí' : 'No' }}
+
+ } +
+ + Página {{ index() + 1 }} · {{ selected().length }} elegidos + +
+ `, +}) +export class EegPicker { + private readonly api = inject(TeaEegApi); + readonly selected = model([]); + readonly disabled = input(false); + readonly revision = input(0); + readonly pageSize = 50; + readonly index = linkedSignal({ source: this.revision, computation: () => 0 }); + readonly page = rxResource({ + params: () => ({ offset: this.index() * this.pageSize, revision: this.revision() }), + stream: ({ params }) => this.api.eegList(this.pageSize, params.offset), + }); + + select(id: EegId, event: Event): void { + const checked = (event.target as HTMLInputElement).checked; + this.selected.update((ids) => checked ? [...ids, id] : ids.filter((item) => item !== id)); + } +} diff --git a/src/app/governance/components/eeg-step.scss b/src/app/governance/components/eeg-step.scss new file mode 100644 index 0000000..50a5a2d --- /dev/null +++ b/src/app/governance/components/eeg-step.scss @@ -0,0 +1,8 @@ +:host { display: block; padding-block: .75rem; min-width: 0; } +.controls { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-block: .75rem; } +.controls label { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; } +select, input { font: inherit; color: inherit; background: var(--mat-sys-surface); } +[role="alert"] { color: var(--mat-sys-error); } +table { border-collapse: collapse; width: 100%; text-align: start; } +th, td { padding: .4rem; border-bottom: 1px solid var(--mat-sys-outline-variant); text-align: start; } +.table-scroll { overflow-x: auto; } diff --git a/src/app/governance/components/governance-page/governance-page.html b/src/app/governance/components/governance-page/governance-page.html index 80537eb..9e012f6 100644 --- a/src/app/governance/components/governance-page/governance-page.html +++ b/src/app/governance/components/governance-page/governance-page.html @@ -27,5 +27,12 @@ + @if (puedeVerTea()) { + +
+ +
+
+ } diff --git a/src/app/governance/components/governance-page/governance-page.spec.ts b/src/app/governance/components/governance-page/governance-page.spec.ts new file mode 100644 index 0000000..28a9fc8 --- /dev/null +++ b/src/app/governance/components/governance-page/governance-page.spec.ts @@ -0,0 +1,97 @@ +/** + * Covers the governance page's fifth tab: the "TEA · EEG" wizard shows for accounts that reach the TEA + * domain and is absent for the rest. Fixtures: stubs of the panels' APIs (no HTTP happens) and an + * `AuthService` double whose `puedeVer` answers per domain; the wizard's own health check answers + * immediately. + */ +import { TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { AuthService } from '../../../auth/auth.service'; +import { GovernanceApi } from '../../api/governance.api'; +import { RiskBatchesApi } from '../../api/risk-batches.api'; +import { TeaEegApi } from '../../api/tea-eeg.api'; +import { ClusterStatus } from '../../api/tea-eeg.types'; +import { GovernancePage } from './governance-page'; + +// A healthy cluster, for the wizard's first check when the tab renders. +const STATUS: ClusterStatus = { + mode: 'auto', scheduler: null, reachable: true, workers: null, expected_workers: null, + versions_ok: null, version_error: null, dashboard_ok: null, dashboard_url: null, + reference: null, latency_ms: null, error: null, +}; + +describe('GovernancePage TEA · EEG tab', () => { + function mount(puedeVerTea: boolean) { + TestBed.configureTestingModule({ + imports: [GovernancePage], + providers: [ + { + provide: AuthService, + useValue: { puedeVer: (dominio: string) => (dominio === 'tea' ? puedeVerTea : true) }, + }, + { + provide: GovernanceApi, + useValue: { + listModelVersions: () => of({ model_versions: [] }), + trainableScenarios: () => of({ scenarios: [] }), + trainingJobs: () => of({ jobs: [] }), + listExperiments: () => of({ experiments: [] }), + listOcrJobs: () => of({ jobs: [] }), + checks: () => of({ ready: true, checks: [] }), + }, + }, + { provide: RiskBatchesApi, useValue: { listPending: () => of([]) } }, + { + provide: TeaEegApi, + useValue: { + clusterStatus: () => of(STATUS), + listReferenceCohorts: () => of([]), + baselinesExportUrl: () => '/governance/tea/baselines/export?environment=prod', + }, + }, + ], + }); + const fixture = TestBed.createComponent(GovernancePage); + fixture.detectChanges(); + return fixture; + } + + function tabLabels(fixture: ReturnType): string[] { + return Array.from(fixture.nativeElement.querySelectorAll('.mat-mdc-tab')).map((tab) => + (tab.textContent ?? '').replace(/\s+/g, ' ').trim(), + ); + } + + // Fails if the wizard tab stops rendering for a TEA account, or its stepper loses the nine titles. + it('shows the wizard as the fifth tab for an account that reaches TEA', () => { + const fixture = mount(true); + const labels = tabLabels(fixture); + expect(labels).toEqual([ + 'Versiones de modelo', 'Notebooks', 'Revisión de OCR', 'Lotes de riesgo', 'TEA · EEG', + ]); + + // Tab bodies build on first activation, so open the tab before looking inside. + const tab = Array.from(fixture.nativeElement.querySelectorAll('.mat-mdc-tab')).find((el) => + (el.textContent ?? '').includes('TEA · EEG'), + )!; + tab.dispatchEvent(new MouseEvent('click', { bubbles: true })); + fixture.detectChanges(); + + const wizard = fixture.nativeElement.querySelector('app-tea-eeg-panel mat-stepper'); + expect(wizard).not.toBeNull(); + const steps = Array.from(fixture.nativeElement.querySelectorAll('.mat-step-text-label')).map( + (el) => (el.textContent ?? '').trim(), + ); + expect(steps).toEqual([ + 'Clúster', 'Datos de referencia', 'Entrenar', 'Líneas base', 'Reportes', + 'Promover', 'Verificar línea base', 'Analizar', 'Resultado', + ]); + }); + + // Fails if the wizard tab starts showing for accounts the TEA domain is closed to. + it('hides the wizard tab for an account that cannot see TEA', () => { + const fixture = mount(false); + expect(tabLabels(fixture)).toEqual(['Versiones de modelo', 'Notebooks', 'Revisión de OCR', 'Lotes de riesgo']); + expect(fixture.nativeElement.querySelector('app-tea-eeg-panel')).toBeNull(); + }); +}); diff --git a/src/app/governance/components/governance-page/governance-page.ts b/src/app/governance/components/governance-page/governance-page.ts index 9a28107..fa6c224 100644 --- a/src/app/governance/components/governance-page/governance-page.ts +++ b/src/app/governance/components/governance-page/governance-page.ts @@ -1,20 +1,28 @@ -import { Component } from '@angular/core'; +import { Component, computed, inject } from '@angular/core'; import { MatTabsModule } from '@angular/material/tabs'; import { MatToolbarModule } from '@angular/material/toolbar'; +import { AuthService } from '../../../auth/auth.service'; import { ExperimentsPanel } from '../experiments-panel/experiments-panel'; import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel'; import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel'; import { RiskBatchesPanel } from '../risk-batches-panel/risk-batches-panel'; +import { TeaEegPanel } from '../tea-eeg-panel/tea-eeg-panel'; /** * The "Gobernanza de modelos" page (route `/gobernanza`): model versions, * notebooks run on cohort builds, the OCR review queue and pending risk batches, one tab each. Every tab is a - * self-contained panel that loads its own data. + * self-contained panel that loads its own data. The TEA · EEG wizard is a fifth tab, only for accounts + * that reach the TEA domain. */ @Component({ selector: 'app-governance-page', - imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel, RiskBatchesPanel], + imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel, RiskBatchesPanel, TeaEegPanel], templateUrl: './governance-page.html', styleUrl: './governance-page.scss', }) -export class GovernancePage {} +export class GovernancePage { + private readonly auth = inject(AuthService); + + /** Only accounts that reach the TEA domain get the TEA · EEG wizard. */ + readonly puedeVerTea = computed(() => this.auth.puedeVer('tea')); +} diff --git a/src/app/governance/components/result-step/result-step.html b/src/app/governance/components/result-step/result-step.html new file mode 100644 index 0000000..5947fc1 --- /dev/null +++ b/src/app/governance/components/result-step/result-step.html @@ -0,0 +1,23 @@ + +

Resumen de EEGs

+@if (summary.isLoading()) {

Cargando resumen de EEGs…

} +@else if (summary.error()) {

No se pudo cargar el resumen de EEGs.

} +@if (summary.hasValue()) { + @let totals = summary.value(); + @if (!totals.eegs) {

Todavía no hay EEGs registrados.

} +
+ @for (card of cards; track card.key) { +
{{ card.label }}
{{ totals[card.key] }}
+ } +
+} +

Ciclo de indicadores TEA

+@if (indicators.hasValue() && indicators.value(); as status) { +

{{ states[status.estado] }} · Pendiente: {{ status.pendiente ? 'Sí' : 'No' }}

+ @if (status.error; as error) {

{{ error.mensaje }}

} +} @else if (indicators.isLoading()) {

Consultando ciclo de indicadores…

} +@else if (!indicators.error()) {

Sin información del ciclo de indicadores.

} +@if (indicators.error()) {

No se pudo consultar el ciclo de indicadores.

} diff --git a/src/app/governance/components/result-step/result-step.scss b/src/app/governance/components/result-step/result-step.scss new file mode 100644 index 0000000..80430a9 --- /dev/null +++ b/src/app/governance/components/result-step/result-step.scss @@ -0,0 +1,3 @@ +.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 9rem), 1fr)); gap: .5rem; } +.cards div { border: 1px solid var(--mat-sys-outline-variant); border-radius: .4rem; padding: .75rem; } +.cards dd { margin: .25rem 0 0; font-size: 1.4rem; font-weight: 600; font-variant-numeric: tabular-nums; } diff --git a/src/app/governance/components/result-step/result-step.spec.ts b/src/app/governance/components/result-step/result-step.spec.ts new file mode 100644 index 0000000..ba9b43f --- /dev/null +++ b/src/app/governance/components/result-step/result-step.spec.ts @@ -0,0 +1,88 @@ +/** Pins EEG totals and visible-step polling with HTTP fixtures and a fake clock. */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { ResultStepComponent } from './result-step'; + +const summary = '/governance/tea/eeg/summary'; +const indicators = '/reportes/indicadores'; + +describe('ResultStepComponent', () => { + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + /** Fails if totals disappear or status stops refreshing at five seconds or continues on a closed step. */ + it('refreshes indicators while active and shows EEG and FHIR counts', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false); + try { + const fixture = TestBed.createComponent(ResultStepComponent); + fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + http.expectOne(summary).flush({ + eegs: 6, analysed: 5, valid: 3, not_valid: 1, failed: 1, metrics: 12, + metrics_with_z: 10, high: 2, low: 1, fhir_eegs: 5, fhir_metrics: 12, + }); + http.expectOne(indicators).flush({ tea: { estado: 'en_curso', pendiente: true } }); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelectorAll('dd')).toHaveLength(11); + expect(fixture.nativeElement.textContent).toContain('En curso · Pendiente: Sí'); + + vi.advanceTimersByTime(5000); + fixture.detectChanges(); + http.expectOne(indicators).flush({ tea: { estado: 'ok', pendiente: false } }); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Actualizado · Pendiente: No'); + + hidden.mockReturnValue(true); + document.dispatchEvent(new Event('visibilitychange')); + fixture.detectChanges(); + vi.advanceTimersByTime(5000); + http.expectNone(indicators); + hidden.mockReturnValue(false); + document.dispatchEvent(new Event('visibilitychange')); + fixture.detectChanges(); + http.expectOne(indicators).flush({ tea: { estado: 'ok', pendiente: false } }); + + fixture.componentRef.setInput('active', false); + fixture.detectChanges(); + vi.advanceTimersByTime(5000); + http.expectNone(indicators); + fixture.destroy(); + } finally { + hidden.mockRestore(); + vi.useRealTimers(); + } + }); + + /** Fails if failures hide the refresh control or refreshing skips one of the two endpoints. */ + it('shows load failures and lets both requests be retried', async () => { + const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false); + try { + const fixture = TestBed.createComponent(ResultStepComponent); + fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + http.expectOne(summary).flush(null, { status: 500, statusText: 'Server Error' }); + http.expectOne(indicators).flush(null, { status: 500, statusText: 'Server Error' }); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelectorAll('[role=alert]')).toHaveLength(2); + fixture.nativeElement.querySelector('button').click(); + fixture.detectChanges(); + http.expectOne(summary).flush({ eegs: 0 }); + http.expectOne(indicators).flush({ tea: { estado: 'sin_correr', pendiente: true } }); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Todavía no hay EEGs registrados.'); + } finally { + hidden.mockRestore(); + } + }); +}); diff --git a/src/app/governance/components/result-step/result-step.ts b/src/app/governance/components/result-step/result-step.ts new file mode 100644 index 0000000..0d01508 --- /dev/null +++ b/src/app/governance/components/result-step/result-step.ts @@ -0,0 +1,64 @@ +import { DOCUMENT } from '@angular/common'; +import { Component, computed, inject, input, signal } from '@angular/core'; +import { rxResource, takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { RouterLink } from '@angular/router'; +import { EMPTY, fromEvent, map, switchMap, timer } from 'rxjs'; +import { ReportsApi, RecomputeStatus } from '../../../reportes/reportes.api'; +import { TeaEegApi } from '../../api/tea-eeg.api'; +import { EegSummary } from '../../api/tea-eeg.types'; + +@Component({ + selector: 'app-result-step', + imports: [MatButtonModule, RouterLink], + templateUrl: './result-step.html', + styleUrls: ['../eeg-step.scss', './result-step.scss'], +}) +export class ResultStepComponent { + private readonly api = inject(TeaEegApi); + private readonly reports = inject(ReportsApi); + private readonly document = inject(DOCUMENT); + readonly active = input(false); + private readonly visible = signal(!this.document.hidden); + private readonly shown = computed(() => this.active() && this.visible()); + private readonly refreshCount = signal(0); + readonly summary = rxResource({ + params: () => this.active() ? this.refreshCount() : undefined, + stream: () => this.api.eegSummary(), + }); + readonly indicators = rxResource({ + params: () => this.shown() ? this.refreshCount() : undefined, + stream: () => this.reports.indicatorStatus().pipe(map((status) => status.tea ?? null)), + }); + readonly states: Record = { + en_curso: 'En curso', ok: 'Actualizado', error: 'Error en el cálculo', sin_correr: 'Sin ejecutar', + }; + readonly cards: { key: keyof EegSummary; label: string }[] = [ + { key: 'eegs', label: 'EEGs' }, + { key: 'analysed', label: 'Analizados' }, + { key: 'valid', label: 'Válidos' }, + { key: 'not_valid', label: 'No válidos' }, + { key: 'failed', label: 'Fallidos' }, + { key: 'metrics', label: 'Métricas' }, + { key: 'metrics_with_z', label: 'Con puntuación z' }, + { key: 'high', label: 'Altas' }, + { key: 'low', label: 'Bajas' }, + { key: 'fhir_eegs', label: 'Filas FHIR de EEGs' }, + { key: 'fhir_metrics', label: 'Filas FHIR de métricas' }, + ]; + + constructor() { + fromEvent(this.document, 'visibilitychange').pipe(takeUntilDestroyed()).subscribe(() => this.visible.set(!this.document.hidden)); + toObservable(this.shown).pipe( + switchMap((shown) => shown ? timer(5000, 5000) : EMPTY), + takeUntilDestroyed(), + ).subscribe(() => { + if (this.shown() && !this.indicators.isLoading()) this.indicators.reload(); + }); + } + + refresh(): void { + if (this.summary.isLoading() || this.indicators.isLoading()) return; + this.refreshCount.update((count) => count + 1); + } +} diff --git a/src/app/governance/components/run-monitor/run-monitor.html b/src/app/governance/components/run-monitor/run-monitor.html new file mode 100644 index 0000000..150045e --- /dev/null +++ b/src/app/governance/components/run-monitor/run-monitor.html @@ -0,0 +1,61 @@ +
+ @if (message(); as status) {

{{ status }}

} + @if (sample(); as progress) { +

+ {{ progress.phase }} · {{ progress.done }}/{{ progress.total }} + · Tiempo transcurrido {{ duration(progress.elapsed_s) }} · Tiempo restante {{ eta() }} + @if (stale()) { sin señal } +

+ + @if (progress.cluster; as cluster) { +

Clúster · CPU {{ fixed(cluster.cpu_pct) }} % · RAM {{ fixed(cluster.memory_pct) }} %

+
+ @for (worker of cluster.workers; track worker.name) { +
+ {{ worker.name }} + + @let usage = ram(worker); + @if (usage !== null) { + + } @else { RAM {{ worker.memory_bytes }} bytes · sin límite informado } +
+ } @empty {

Sin trabajadores.

} +
+ @if (cluster.mode === 'remote') { + @if (dashboard(); as url) { + Abrir dashboard de Dask + } @else { + + } + } + } + @if (progress.tasks; as tasks) { +

Tareas · En proceso {{ tasks.processing }} · En espera {{ tasks.waiting }} + · En memoria {{ tasks.memory }} · Con error {{ tasks.erred }}

+ } + @if (progress.history.length) { + +
+ Ver historial de mediciones + + + + @for (point of progress.history; track $index) { + + } + +
Tiempo (s)CPU (%)RAM (%)Procesados
{{ fixed(point.t) }}{{ fixed(point.cpu_pct) }}{{ fixed(point.memory_pct) }}{{ point.done }}
+
+ } + } +
diff --git a/src/app/governance/components/run-monitor/run-monitor.scss b/src/app/governance/components/run-monitor/run-monitor.scss new file mode 100644 index 0000000..7d61cbc --- /dev/null +++ b/src/app/governance/components/run-monitor/run-monitor.scss @@ -0,0 +1,11 @@ +:host { display: block; margin-block: .75rem; } +.stale { border: 1px solid currentColor; border-radius: .35rem; padding: .15rem .4rem; } +.workers, .trends { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr)); gap: .5rem; margin-block: .75rem; } +.worker, figure { border: 1px solid var(--mat-sys-outline-variant); border-radius: .4rem; padding: .5rem; margin: 0; } +.worker { display: grid; gap: .25rem; min-width: 0; overflow-wrap: anywhere; font-size: .8rem; } +meter { display: block; width: 100%; height: .55rem; accent-color: var(--eeg-blue); } +meter::-webkit-meter-optimum-value { background: var(--eeg-blue); } +meter::-moz-meter-bar { background: var(--eeg-blue); } +svg { display: block; width: 100%; max-height: 3.5rem; } +polyline { stroke: var(--eeg-blue); stroke-width: 2; stroke-linecap: round; fill: none; } +table { border-spacing: .5rem; text-align: end; } diff --git a/src/app/governance/components/run-monitor/run-monitor.spec.ts b/src/app/governance/components/run-monitor/run-monitor.spec.ts new file mode 100644 index 0000000..a63502a --- /dev/null +++ b/src/app/governance/components/run-monitor/run-monitor.spec.ts @@ -0,0 +1,103 @@ +/** Pins progress rendering and polling against a mocked HTTP endpoint and clock. */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { RunProgress } from '../../api/tea-eeg.types'; +import { RunMonitorComponent } from './run-monitor'; + +const url = '/governance/tea/jobs/train/t1/progress'; + +describe('RunMonitorComponent', () => { + beforeEach(() => { + vi.useFakeTimers(); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + }); + afterEach(() => { + TestBed.inject(HttpTestingController).verify(); + vi.useRealTimers(); + }); + + /** Fails if a first 404 appears as a failure or a finished job keeps polling after its last read. */ + it('waits for the first measurement and performs one final read', () => { + const fixture = TestBed.createComponent(RunMonitorComponent); + const http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('kind', 'train'); + fixture.componentRef.setInput('jobId', 't1'); + fixture.componentRef.setInput('running', true); + fixture.detectChanges(); + http.expectOne(url).flush(null, { status: 404, statusText: 'Not Found' }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Esperando la primera medición'); + + vi.advanceTimersByTime(2000); + // A remote cluster sample with a concrete estimate and worker counters. + const sample: RunProgress = { + updated_at: new Date().toISOString(), phase: 'midiendo', done: 4, total: 10, + elapsed_s: 40, eta_s: 200, tasks: { processing: 2, waiting: 4, memory: 4, erred: 0 }, + cluster: { + mode: 'remote', scheduler: 'tcp://equipo:8786', cpu_pct: 60, memory_pct: 25, + workers: [{ name: 'equipo', cpu_pct: 60, memory_bytes: 1024, memory_limit: 4096, executing: 2, threads: 4 }], + }, + history: [{ t: 0, done: 0, cpu_pct: 0, memory_pct: 0 }, { t: 40, done: 4, cpu_pct: 60, memory_pct: 25 }], + }; + http.expectOne(url).flush(sample); + fixture.detectChanges(); + http.expectOne((req) => req.url === '/governance/tea/cluster').flush({ + dashboard_ok: true, dashboard_url: 'http://equipo:8787/status', + }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('≈ 3 min 20 s'); + expect(fixture.nativeElement.querySelectorAll('meter')).toHaveLength(2); + expect(fixture.nativeElement.querySelectorAll('polyline')).toHaveLength(3); + expect(fixture.nativeElement.querySelector('a').href).toBe('http://equipo:8787/status'); + + fixture.componentRef.setInput('running', false); + fixture.detectChanges(); + http.expectOne(url).flush({ ...sample, done: 10 }); + vi.advanceTimersByTime(6000); + http.expectNone(url); + fixture.destroy(); + }); + + /** Fails if a sample over 10 seconds old stays fresh, or a null ETA is displayed as zero. */ + it('marks stale samples during a run and labels a missing ETA', () => { + const fixture = TestBed.createComponent(RunMonitorComponent); + const http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('kind', 'train'); + fixture.componentRef.setInput('jobId', 't1'); + fixture.componentRef.setInput('running', true); + fixture.detectChanges(); + http.expectOne(url).flush({ + updated_at: new Date(Date.now() - 10_000).toISOString(), phase: 'midiendo', done: 0, total: 10, + elapsed_s: 1, eta_s: null, tasks: null, cluster: null, history: [], + }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('calculando…'); + expect(fixture.nativeElement.textContent).not.toContain('sin señal'); + vi.advanceTimersByTime(1000); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('sin señal'); + fixture.destroy(); + }); + + /** Fails if the cluster totals show raw floating-point readings instead of at most one decimal. */ + it('rounds the cluster readings it shows', () => { + const fixture = TestBed.createComponent(RunMonitorComponent); + const http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('kind', 'train'); + fixture.componentRef.setInput('jobId', 't1'); + fixture.componentRef.setInput('running', false); + fixture.detectChanges(); + http.expectOne(url).flush({ + updated_at: new Date().toISOString(), phase: 'midiendo', done: 4, total: 10, elapsed_s: 40, eta_s: 200, + tasks: null, + cluster: { mode: 'local', scheduler: null, cpu_pct: 99.96666, memory_pct: 11.779874913832721, workers: [] }, + history: [{ t: 0, done: 0, cpu_pct: 0, memory_pct: 0 }, { t: 40.123456, done: 4, cpu_pct: 99.96666, memory_pct: 11.779874913832721 }], + } satisfies RunProgress); + fixture.detectChanges(); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('CPU 100 % · RAM 11.8 %'); + expect(text).not.toContain('11.7798'); + expect(text).not.toContain('40.1234'); + }); +}); diff --git a/src/app/governance/components/run-monitor/run-monitor.ts b/src/app/governance/components/run-monitor/run-monitor.ts new file mode 100644 index 0000000..e3712fb --- /dev/null +++ b/src/app/governance/components/run-monitor/run-monitor.ts @@ -0,0 +1,117 @@ +import { Component, computed, effect, inject, input, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { catchError, exhaustMap, of, startWith, timer } from 'rxjs'; +import { TeaEegApi } from '../../api/tea-eeg.api'; +import { RunProgress, WorkerSample } from '../../api/tea-eeg.types'; +import { clusterDashboardUrl } from '../cluster-health-card/cluster-health-card'; + +export function formatDuration(seconds: number): string { + const whole = Math.max(0, Math.round(seconds)); + const minutes = Math.floor(whole / 60); + return minutes ? `${minutes} min ${whole % 60} s` : `${whole} s`; +} + +@Component({ + selector: 'app-run-monitor', + imports: [MatButtonModule, MatProgressBarModule, MatTooltipModule], + templateUrl: './run-monitor.html', + styleUrl: './run-monitor.scss', +}) +export class RunMonitorComponent { + private readonly api = inject(TeaEegApi); + readonly kind = input.required<'train' | 'analyze'>(); + readonly jobId = input.required(); + readonly running = input(false); + readonly sample = signal(null); + readonly message = signal('Cargando progreso…'); + readonly dashboard = signal(null); + private readonly clock = signal(Date.now()); + private key = ''; + readonly stale = computed(() => { + const sample = this.sample(); + return this.running() && sample !== null && this.clock() - Date.parse(sample.updated_at) > 10_000; + }); + readonly eta = computed(() => { + const seconds = this.sample()?.eta_s; + return seconds == null ? 'calculando…' : `≈ ${formatDuration(seconds)}`; + }); + readonly duration = formatDuration; + readonly trends = [ + { key: 'cpu_pct', label: 'CPU (%)' }, + { key: 'memory_pct', label: 'RAM (%)' }, + { key: 'done', label: 'Procesados' }, + ] as const; + + constructor() { + effect((cleanup) => { + const kind = this.kind(); + const id = this.jobId(); + const running = this.running(); + const key = `${kind}/${id}`; + if (this.key !== key) { + this.key = key; + this.sample.set(null); + this.message.set('Cargando progreso…'); + } + const read = () => this.api.runProgress(kind, id).pipe(catchError((error) => { + const missing = running ? 'Esperando la primera medición' : 'Sin mediciones disponibles.'; + this.message.set(error.status === 404 && !this.sample() ? missing : 'No se pudo consultar el progreso.'); + return of(null); + })); + this.clock.set(Date.now()); + const subscription = (running ? timer(2000, 2000).pipe(startWith(0), exhaustMap(read)) : read()).subscribe((sample) => { + this.clock.set(Date.now()); + if (sample) { + this.sample.set(sample); + this.message.set(''); + } + }); + const clock = running ? timer(1000, 1000).subscribe(() => this.clock.set(Date.now())) : undefined; + cleanup(() => { + subscription.unsubscribe(); + clock?.unsubscribe(); + }); + }); + + const remote = computed(() => { + const cluster = this.sample()?.cluster; + return cluster?.mode === 'remote' ? cluster.scheduler ?? '' : null; + }); + effect((cleanup) => { + const scheduler = remote(); + this.dashboard.set(null); + if (scheduler === null) return; + const request = this.api.clusterStatus({ mode: 'remote', scheduler: scheduler || undefined }).subscribe({ + next: (status) => this.dashboard.set(clusterDashboardUrl(status)), + error: () => this.dashboard.set(null), + }); + cleanup(() => request.unsubscribe()); + }); + } + + /** A reading with at most one decimal, for display. */ + fixed(value: number): number { + return Math.round(value * 10) / 10; + } + + percent(value: number): number { + return Math.max(0, Math.min(100, value)); + } + + ram(worker: WorkerSample): number | null { + return worker.memory_limit ? this.percent(100 * worker.memory_bytes / worker.memory_limit) : null; + } + + workerDetails(worker: WorkerSample): string { + return `${worker.executing}/${worker.threads} hilos ejecutando · ${worker.memory_bytes} / ${worker.memory_limit ?? 'sin límite'} bytes`; + } + + sparkline(history: RunProgress['history'], key: 'cpu_pct' | 'memory_pct' | 'done', total: number): string { + const start = history[0]?.t ?? 0; + const span = Math.max(1, (history.at(-1)?.t ?? start) - start); + const max = Math.max(1, key === 'done' ? total : 100, ...history.map((point) => point[key])); + return history.map((point) => `${2 + 116 * (point.t - start) / span},${30 - 28 * point[key] / max}`).join(' '); + } +} diff --git a/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.html b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.html new file mode 100644 index 0000000..82440a3 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.html @@ -0,0 +1,72 @@ +
+
+

Exportar

+
+ + Incluir las versiones promovidas a producción + + + Exportar + +
+ @if (exportClicked()) { +

La huella sha256 del paquete viene en la cabecera X-Baselines-Sha256 de la respuesta.

+
+ + @if (hash(); as result) { + sha256: {{ result.sha256 }} + @if (result.matches === true) { + Coincide con la cabecera + } + @if (result.matches === false) { + No coincide con la cabecera X-Baselines-Sha256 + } + } +
+ @if (hashError(); as error) { + + } + } +
+ +
+

Importar

+
+ + +
+ @if (importing()) { + + } + @if (importError(); as error) { + + } + @if (importResult(); as result) { +

sha256: {{ result.sha256 }}

+ @if (result.imported.length) { + + + + + + + + + + + +
Escenario{{ row.scenario }}Versión{{ row.version }}
+ } @else { +

El paquete no traía líneas base.

+ } + } +
+
diff --git a/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.scss b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.scss new file mode 100644 index 0000000..ab404cf --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.scss @@ -0,0 +1,81 @@ +.base { + display: flex; + flex-direction: column; + gap: var(--space-4); + max-width: 860px; +} + +.base__block { + display: flex; + flex-direction: column; + gap: var(--space-2); +} + +.base__title { + font: var(--mat-sys-title-small); + margin: 0; +} + +.base__row { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.base__muted { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + margin: 0; + + code { + font-family: monospace; + } +} + +.base__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.base__hash { + font-family: monospace; + margin: 0; + word-break: break-all; +} + +.base__ok { + align-items: center; + color: var(--mat-sys-primary); + display: inline-flex; + gap: var(--space-1); +} + +.base__warn { + align-items: center; + color: #9a6a00; + display: inline-flex; + gap: var(--space-1); +} + +.base__file { + color: var(--mat-sys-on-surface-variant); + display: flex; + flex-direction: column; + font: var(--mat-sys-body-small); + gap: var(--space-1); + + input { + color: var(--mat-sys-on-surface); + font: var(--mat-sys-body-medium); + } +} + +.base__table { + width: 100%; +} diff --git a/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.spec.ts b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.spec.ts new file mode 100644 index 0000000..e9b96d1 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.spec.ts @@ -0,0 +1,108 @@ +/** + * Covers the baselines step: the export link points at the contract's URL (with `production=0` when the + * production versions are excluded), clicking it offers the hash check whose button downloads the blob and + * renders the computed sha256 against `X-Baselines-Sha256`, and the import posts the zip and renders the + * sha256 and scenario/version table or the 400/409 message. Fixtures: `HttpTestingController`; the digest + * is stubbed so no real hashing runs. + */ +import { HttpEventType } from '@angular/common/http'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { BaselinesStep } from './baselines-step'; + +const EXPORT_URL = '/governance/tea/baselines/export'; +const IMPORT_URL = '/governance/tea/baselines/import'; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +describe('BaselinesStep', () => { + let http: HttpTestingController; + let fixture: ComponentFixture; + + beforeEach(() => { + vi.stubGlobal('crypto', { + subtle: { digest: vi.fn().mockResolvedValue(new Uint8Array([0xab, 0xcd]).buffer) }, + }); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + fixture = TestBed.createComponent(BaselinesStep); + fixture.detectChanges(); + }); + afterEach(() => { + http.verify(); + vi.unstubAllGlobals(); + }); + + function link(): HTMLAnchorElement { + return fixture.nativeElement.querySelector('a[download]'); + } + + function buttonByText(text: string): HTMLButtonElement { + return Array.from(fixture.nativeElement.querySelectorAll('button')).find((b) => + b.textContent?.includes(text), + )!; + } + + // Fails if the export link loses the environment, or the checkbox stops toggling production=0. + it('links the export of environment prod, honoring the production checkbox', () => { + expect(link().href).toContain(`${EXPORT_URL}?environment=prod`); + expect(link().href).not.toContain('production=0'); + + fixture.componentInstance.includeProduction.set(false); + fixture.detectChanges(); + expect(link().href).toContain('production=0'); + }); + + // Fails if the note or the hash button stop appearing after the click, if the blob isn't hashed, or if + // the header comparison is dropped. + it('computes the sha256 of the downloaded blob after the export click', async () => { + link().click(); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('X-Baselines-Sha256'); + + buttonByText('Calcular huella').click(); + const req = http.expectOne((r) => r.url.startsWith(EXPORT_URL)); + expect(req.request.responseType).toBe('blob'); + req.flush(new Blob(['zip']), { headers: { 'X-Baselines-Sha256': 'abcd' } }); + await flush(); + await flush(); + fixture.detectChanges(); + + expect(fixture.nativeElement.textContent).toContain('sha256: abcd'); + expect(fixture.nativeElement.textContent).toContain('Coincide con la cabecera'); + }); + + // Fails if the import stops posting the zip under the import route, or the result table loses columns. + it('imports the zip and lists the sha256 and the imported scenario/version pairs', () => { + const step = fixture.componentInstance; + step.importFile.set(new File(['zip'], 'baselines.zip')); + step.import(); + fixture.detectChanges(); + + const req = http.expectOne(IMPORT_URL); + expect(req.request.method).toBe('POST'); + expect(((req.request.body as FormData).get('file') as File).name).toBe('baselines.zip'); + req.event({ type: HttpEventType.UploadProgress, loaded: 1, total: 2 }); + req.flush({ sha256: 'f0f0', imported: [{ scenario: 'tea-eeg-nsr', version: 3 }, { scenario: 'tea-eeg-alpha', version: 2 }] }); + fixture.detectChanges(); + + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('sha256: f0f0'); + expect(text).toContain('tea-eeg-nsr'); + expect(text).toContain('tea-eeg-alpha'); + }); + + // Fails if the 400/409 message is replaced by a generic one, or a failed import still shows results. + it('shows the server message when the import is rejected', () => { + const step = fixture.componentInstance; + step.importFile.set(new File(['zip'], 'baselines.zip')); + step.import(); + http.expectOne(IMPORT_URL).flush({ error: 'El paquete ya fue importado' }, { status: 409, statusText: 'Conflict' }); + fixture.detectChanges(); + + expect(fixture.nativeElement.textContent).toContain('El paquete ya fue importado'); + expect(step.importResult()).toBeNull(); + expect(buttonByText('Importar').disabled).toBe(false); + }); +}); diff --git a/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.ts b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.ts new file mode 100644 index 0000000..cdbce56 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/baselines-step/baselines-step.ts @@ -0,0 +1,107 @@ +import { HttpClient, HttpEventType } from '@angular/common/http'; +import { Component, DestroyRef, computed, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { apiErrorMessage } from '../../../../connect/api/api.types'; +import { TeaEegApi } from '../../../api/tea-eeg.api'; +import { BaselineImport } from '../../../api/tea-eeg.types'; + +/** Hex of a digest, lowercase. */ +export function sha256Hex(digest: ArrayBuffer): string { + return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join(''); +} + +/** + * The baselines step: the promoted baselines download as a zip from the export route (optionally without + * the production versions), and the import route reads a bundle back, showing its sha256 and the imported + * scenario/version pairs. After exporting, the sha256 can be recomputed from the downloaded bytes and + * compared with the response's `X-Baselines-Sha256` header. + */ +@Component({ + selector: 'app-baselines-step', + imports: [MatButtonModule, MatCheckboxModule, MatIconModule, MatProgressBarModule, MatTableModule], + templateUrl: './baselines-step.html', + styleUrl: './baselines-step.scss', +}) +export class BaselinesStep { + private readonly tea = inject(TeaEegApi); + private readonly http = inject(HttpClient); + private readonly destroyRef = inject(DestroyRef); + + /** Checked: the zip includes the production versions; unchecked asks for `production=0`. */ + readonly includeProduction = signal(true); + readonly exportUrl = computed(() => this.tea.baselinesExportUrl('prod', this.includeProduction() ? undefined : false)); + readonly exportClicked = signal(false); + readonly hashing = signal(false); + readonly hash = signal<{ sha256: string; matches: boolean | null } | null>(null); + readonly hashError = signal(null); + readonly importFile = signal(null); + readonly importing = signal(false); + readonly importResult = signal(null); + readonly importError = signal(null); + readonly displayedColumns = ['scenario', 'version']; + + onExportClicked(): void { + this.exportClicked.set(true); + } + + /** Downloads the same zip and hashes it, to compare against the header the export answers with. */ + computeHash(): void { + this.hashing.set(true); + this.hashError.set(null); + this.http + .get(this.exportUrl(), { responseType: 'blob', observe: 'response' }) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (response) => void this.digest(response.body!, response.headers.get('X-Baselines-Sha256')), + error: (error) => { + this.hashing.set(false); + this.hashError.set(apiErrorMessage(error, 'No se pudo descargar el paquete.')); + }, + }); + } + + private async digest(blob: Blob, header: string | null): Promise { + try { + const digest = await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()); + this.hash.set({ sha256: sha256Hex(digest), matches: header ? header === sha256Hex(digest) : null }); + } catch { + this.hashError.set('No se pudo calcular la huella en este navegador.'); + } + this.hashing.set(false); + } + + onImportPicked(event: Event): void { + const input = event.target as HTMLInputElement; + this.importFile.set(input.files?.[0] ?? null); + this.importResult.set(null); + this.importError.set(null); + } + + import(): void { + const file = this.importFile(); + if (!file || this.importing()) return; + this.importing.set(true); + this.importError.set(null); + this.importResult.set(null); + this.tea + .importBaselines(file) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (event) => { + if (event.type === HttpEventType.Response) { + this.importing.set(false); + this.importResult.set(event.body!); + } + }, + error: (error) => { + this.importing.set(false); + this.importError.set(apiErrorMessage(error, 'No se pudo importar el paquete.')); + }, + }); + } +} diff --git a/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.html b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.html new file mode 100644 index 0000000..05aeab8 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.html @@ -0,0 +1,92 @@ +
+
+

Requisitos y promoción

+ + +
+ + @if (loading()) { + + } + @if (loadError(); as error) { + + } + @if (!loading() && !loadError()) { + @if (rows().length) { + + + + + + + + + + + + + + + +
Versión + {{ row.version.name }}:{{ row.version.version }} + + Requisitos + @if (row.checksError) { + {{ row.checksError }} + } @else if (row.checks === null) { + Cargando requisitos… + } @else if (!row.checks.length) { + Sin requisitos registrados. + } @else { +
    + @for (check of row.checks; track check.code) { +
  • + + {{ check.requirement }} + @if (check.detail) { + {{ check.detail }} + } +
  • + } +
+ } + @if (row.status === 'failed') { + @if (row.failing?.length) { +
    + @for (check of row.failing; track check.code) { +
  • + + No pasó: {{ check.requirement }} + @if (check.detail) { + {{ check.detail }} + } +
  • + } +
+ } @else { +

{{ row.error }}

+ } + } +
Estado + @if (row.status === 'promoting') { + Promoviendo… + } @else if (row.status === 'promoted') { + Promovida + } @else if (row.status === 'failed') { + Falló + } @else { + Pendiente + } +
+ } @else { +

No hay versiones eeg-* candidatas.

+ } + } + @if (summary(); as line) { +

{{ line }}

+ } +
diff --git a/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.scss b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.scss new file mode 100644 index 0000000..0b7fd05 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.scss @@ -0,0 +1,95 @@ +.promote { + display: flex; + flex-direction: column; + gap: var(--space-3); + max-width: 960px; +} + +.promote__toolbar { + align-items: center; + display: flex; + gap: var(--space-2); +} + +.promote__title { + font: var(--mat-sys-title-small); + margin: 0; +} + +.promote__spacer { + flex: 1; +} + +.promote__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.promote__muted { + align-items: center; + color: var(--mat-sys-on-surface-variant); + display: inline-flex; + gap: var(--space-1); + margin: 0; +} + +.promote__table { + width: 100%; +} + +.promote__label { + font-family: monospace; + margin-right: var(--space-2); +} + +.promote__checks { + display: flex; + flex-direction: column; + gap: 2px; + list-style: none; + margin: 0 0 var(--space-1); + padding: 0; + + li { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-1); + font: var(--mat-sys-body-small); + } + + mat-icon { + font-size: 16px; + height: 16px; + width: 16px; + } +} + +.promote__ok { + align-items: center; + color: var(--mat-sys-primary); + display: inline-flex; + gap: var(--space-1); +} + +.promote__fail { + align-items: center; + color: var(--mat-sys-error); + display: inline-flex; + flex-wrap: wrap; + gap: var(--space-1); + margin: 0; +} + +.promote__detail { + color: var(--mat-sys-on-surface-variant); +} + +.promote__bar { + width: 120px; +} diff --git a/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.spec.ts b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.spec.ts new file mode 100644 index 0000000..3c49f77 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.spec.ts @@ -0,0 +1,119 @@ +/** + * Covers the promotion step: the candidate table loads each version's promotion checks, "Promover todas" + * POSTs one promotion at a time with the button disabled while it runs, a 409 shows that version's + * failing checks, and a closing line sums up the outcome. Fixtures: canned `ModelVersion[]` and checks + * answers plus promote requests through `HttpTestingController`. + */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ModelVersion, PromotionCheck } from '../../../api/governance.types'; +import { PromoteStep } from './promote-step'; + +const VERSIONS_URL = '/governance/model-versions'; + +function version(scenario: string, v: string): ModelVersion { + return { + name: `tea-${scenario}`, version: v, run_id: 'r1', + tags: { domain: 'tea', scenario }, metrics: {}, created_at: '2026-11-09T00:00:00+00:00', status: 'candidata', + }; +} + +const CHECKS: PromotionCheck[] = [ + { code: 'MLD-01', requirement: 'Informes de validación', passed: true, detail: '' }, + { code: 'MLD-02', requirement: 'Huella de la cohorte', passed: false, detail: 'falta el armado' }, +]; + +describe('PromoteStep', () => { + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + function create(): ComponentFixture { + const fixture = TestBed.createComponent(PromoteStep); + fixture.detectChanges(); + http.expectOne((r) => r.url === VERSIONS_URL).flush({ model_versions: [version('eeg-alpha', '2'), version('eeg-nsr', '3')] }); + http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg-alpha/2/checks').flush({ ready: false, checks: CHECKS }); + http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg-nsr/3/checks').flush({ ready: true, checks: [] }); + fixture.detectChanges(); + return fixture; + } + + // Fails if the checks stop rendering per version, or the failing one loses its detail. + it('lists every candidate with its promotion checks', () => { + const fixture = create(); + const rows = fixture.componentInstance.rows(); + expect(rows.map((r) => r.key)).toEqual(['eeg-alpha:2', 'eeg-nsr:3']); + expect(rows[0].checks).toEqual(CHECKS); + + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('Informes de validación'); + expect(text).toContain('Huella de la cohorte'); + expect(text).toContain('falta el armado'); + }); + + // Fails if promotions stop being sequential, the button stays enabled mid-run, or a 409's failing + // checks are not shown. + it('promotes one version at a time, disabling the button, and surfaces a 409 checks', () => { + const fixture = create(); + const step = fixture.componentInstance; + const button = Array.from(fixture.nativeElement.querySelectorAll('button')).find((b) => + b.textContent?.includes('Promover todas'), + )!; + step.promoteAll(); + fixture.detectChanges(); + expect(button.disabled).toBe(true); + + const first = http.expectOne('/governance/model-versions/tea/eeg-alpha/2/promote'); + http.expectNone('/governance/model-versions/tea/eeg-nsr/3/promote'); + first.flush({}); + expect(step.rows()[0].status).toBe('promoted'); + + http.expectOne('/governance/model-versions/tea/eeg-nsr/3/promote').flush( + { checks: CHECKS }, + { status: 409, statusText: 'Conflict' }, + ); + fixture.detectChanges(); + + expect(step.rows()[1].status).toBe('failed'); + expect(step.rows()[1].failing).toEqual([CHECKS[1]]); + expect(button.disabled).toBe(false); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('No pasó: Huella de la cohorte'); + expect(text).toContain('Promovidas 1 de 2; 1 fallaron.'); + }); + + // Fails if a non-409 failure hides its message, or the summary claims everything was promoted. + it('shows the error of a failed promotion without checks', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.promoteAll(); + http.expectOne('/governance/model-versions/tea/eeg-alpha/2/promote').flush({ error: 'MLflow no responde' }, { status: 503, statusText: 'Service Unavailable' }); + http.expectOne('/governance/model-versions/tea/eeg-nsr/3/promote').flush({}); + fixture.detectChanges(); + + expect(step.rows()[0]).toMatchObject({ status: 'failed', error: 'MLflow no responde', failing: null }); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('MLflow no responde'); + expect(text).toContain('Promovidas 1 de 2; 1 fallaron.'); + }); + + // Fails if the step keeps the list it read when the page opened, so versions imported or trained in an earlier + // step never show up for promotion until the page is reloaded. + it('lists the versions again when the step becomes active', () => { + const fixture = create(); + fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + http.expectOne((r) => r.url === VERSIONS_URL).flush({ model_versions: [version('eeg-alpha', '2'), version('eeg-nsr', '3'), version('eeg-theta', '1')] }); + for (const scenario of ['eeg-alpha/2', 'eeg-nsr/3', 'eeg-theta/1']) { + http.expectOne((r) => r.url === `/governance/model-versions/tea/${scenario}/checks`).flush({ ready: true, checks: [] }); + } + fixture.detectChanges(); + expect(fixture.componentInstance.rows()).toHaveLength(3); + fixture.destroy(); + }); +}); diff --git a/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.ts b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.ts new file mode 100644 index 0000000..2838ee2 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/promote-step/promote-step.ts @@ -0,0 +1,146 @@ +import { Component, DestroyRef, OnInit, effect, inject, input, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { finalize } from 'rxjs'; +import { apiErrorMessage } from '../../../../connect/api/api.types'; +import { GovernanceApi } from '../../../api/governance.api'; +import { ModelVersion, PromotionCheck } from '../../../api/governance.types'; +import { ModelStatusChip } from '../../model-status-chip/model-status-chip'; +import { teaCandidates, versionKey } from '../tea-candidates'; + +/** One candidate version with its promotion checks and how its promotion went. */ +export interface PromoteRow { + key: string; + version: ModelVersion; + checks: PromotionCheck[] | null; + checksError: string | null; + status: 'pending' | 'promoting' | 'promoted' | 'failed'; + failing: PromotionCheck[] | null; + error: string | null; +} + +/** + * The promotion step: the current eeg-* candidates with the checklist each must pass, and a button that + * promotes them one request at a time. A 409 answers with the failing checks of that version, which are + * shown next to it; a closing line sums up how many were promoted. + */ +@Component({ + selector: 'app-promote-step', + imports: [MatButtonModule, MatIconModule, MatProgressBarModule, MatTableModule, ModelStatusChip], + templateUrl: './promote-step.html', + styleUrl: './promote-step.scss', +}) +export class PromoteStep implements OnInit { + private readonly api = inject(GovernanceApi); + private readonly destroyRef = inject(DestroyRef); + + readonly rows = signal([]); + readonly loading = signal(false); + readonly loadError = signal(null); + readonly promoting = signal(false); + readonly summary = signal(null); + readonly displayedColumns = ['version', 'checks', 'status']; + + /** True while the step is the one on screen: each time it turns true the versions are listed again. */ + readonly active = input(false); + + constructor() { + effect(() => { + if (this.active() && !untracked(() => this.promoting())) untracked(() => this.load()); + }); + } + + ngOnInit(): void { + this.load(); + } + + private load(): void { + this.loading.set(true); + this.api + .listModelVersions({ domain: 'tea' }) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ model_versions }) => { + this.loading.set(false); + const rows = teaCandidates(model_versions).map((v) => ({ + key: versionKey(v), + version: v, + checks: null, + checksError: null, + status: 'pending' as const, + failing: null, + error: null, + })); + this.rows.set(rows); + rows.forEach((row) => this.loadChecks(row.key)); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones.')); + }, + }); + } + + private loadChecks(key: string): void { + const row = this.rows().find((r) => r.key === key)!; + this.api + .checks('tea', row.version.tags.scenario!, row.version.version) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ checks }) => this.patch(key, { checks }), + error: (error) => this.patch(key, { checksError: apiErrorMessage(error, 'No se pudieron cargar los requisitos.') }), + }); + } + + /** Promotes every row, one request at a time; a failure doesn't stop the rest. */ + promoteAll(): void { + if (this.promoting() || !this.rows().length) return; + this.promoting.set(true); + this.summary.set(null); + this.promoteNext(0); + } + + private promoteNext(index: number): void { + const rows = this.rows(); + if (index >= rows.length) { + this.promoting.set(false); + const promoted = rows.filter((r) => r.status === 'promoted').length; + this.summary.set( + promoted === rows.length + ? `Promovidas ${promoted} de ${rows.length}.` + : `Promovidas ${promoted} de ${rows.length}; ${rows.length - promoted} fallaron.`, + ); + return; + } + const row = rows[index]; + this.patch(row.key, { status: 'promoting' }); + this.api + .promoteModelVersion('tea', row.version.tags.scenario!, row.version.version) + .pipe( + takeUntilDestroyed(this.destroyRef), + finalize(() => this.promoteNext(index + 1)), + ) + .subscribe({ + next: () => this.patch(row.key, { status: 'promoted' }), + error: (error) => + this.patch(row.key, { + status: 'failed', + error: apiErrorMessage(error, 'No se pudo promover la versión.'), + failing: failingChecks(error), + }), + }); + } + + private patch(key: string, partial: Partial): void { + this.rows.set(this.rows().map((r) => (r.key === key ? { ...r, ...partial } : r))); + } +} + +/** The checks a 409 answers with, limited to the ones that didn't pass. */ +function failingChecks(error: unknown): PromotionCheck[] | null { + const checks = (error as { error?: { checks?: PromotionCheck[] } })?.error?.checks; + return checks ? checks.filter((check) => !check.passed) : null; +} diff --git a/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.html b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.html new file mode 100644 index 0000000..48e152d --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.html @@ -0,0 +1,72 @@ +
+

Cohortes en el volumen de referencia

+ @if (loading()) { + + } + @if (loadError(); as error) { + + } + + @if (!loading() && !loadError()) { + @if (cohorts().length) { + + + + + + + + + + + + + + + + + + + +
Nombre{{ c.name }}EDF{{ c.edfs | number }}Tamaño{{ tamano(c.size_bytes) }}Edades{{ c.has_ages ? 'Sí' : 'No' }}
+ } @else { +

Aún no hay cohortes; sube la primera abajo.

+ } + } + + @if (choice().mode === 'remote') { +

En modo remoto los archivos subidos quedan en este servidor, no en el volumen que ven los trabajadores.

+ } + +
+ + Nombre de la cohorte + + @if (name.hasError('pattern') || name.hasError('required')) { + 1 a 64 caracteres: letras, dígitos, punto, guion o guion bajo. + } + + + +
+ + @if (uploads().length) { +
    + @for (item of uploads(); track item.fileName) { +
  • + + {{ item.fileName }} + @if (item.status === 'uploading') { + + } + {{ item.detail }} +
  • + } +
+ } +
diff --git a/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.scss b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.scss new file mode 100644 index 0000000..9fd1b1a --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.scss @@ -0,0 +1,89 @@ +.ref { + display: flex; + flex-direction: column; + gap: var(--space-3); + max-width: 860px; +} + +.ref__title { + font: var(--mat-sys-title-small); + margin: 0; +} + +.ref__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.ref__muted { + color: var(--mat-sys-on-surface-variant); + margin: 0; +} + +.ref__table { + width: 100%; +} + +.ref__note { + align-items: center; + background: var(--mat-sys-tertiary-container); + color: var(--mat-sys-on-tertiary-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.ref__upload { + align-items: flex-start; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.ref__files { + color: var(--mat-sys-on-surface-variant); + display: flex; + flex-direction: column; + font: var(--mat-sys-body-small); + gap: var(--space-1); + + input { + color: var(--mat-sys-on-surface); + font: var(--mat-sys-body-medium); + } +} + +.ref__results { + display: flex; + flex-direction: column; + gap: var(--space-1); + list-style: none; + margin: 0; + padding: 0; + + li { + align-items: center; + display: grid; + gap: var(--space-2); + grid-template-columns: auto minmax(120px, auto) 1fr auto; + } +} + +.ref__result--error { + color: var(--mat-sys-error); +} + +.ref__file { + font-family: monospace; +} + +.ref__detail { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} diff --git a/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.spec.ts b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.spec.ts new file mode 100644 index 0000000..784c1a9 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.spec.ts @@ -0,0 +1,129 @@ +/** + * Covers the reference step: the cohort table renders sizes as MB/GB and ages as Sí/No, files upload one + * request at a time with progress and a per-file result, the table reloads when the batch ends, a 503 + * disables the upload, a bad cohort name blocks it, and a failed file doesn't stop the rest. Fixtures: + * canned `ReferenceCohort[]` answers and multipart uploads through `HttpTestingController`. + */ +import { HttpEventType } from '@angular/common/http'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ReferenceCohort } from '../../../api/tea-eeg.types'; +import { ReferenceStep, tamano } from './reference-step'; + +const LIST_URL = '/governance/tea/reference-cohorts'; +const UPLOAD_URL = '/governance/tea/reference-cohorts/referencia_2026/files'; + +const COHORTS: ReferenceCohort[] = [ + { name: 'referencia_2026', edfs: 120, size_bytes: 2.4e9, has_ages: true, path: '/ref/referencia_2026' }, + { name: 'otra', edfs: 3, size_bytes: 5.2e6, has_ages: false, path: '/ref/otra' }, +]; + +describe('ReferenceStep', () => { + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + function create(choice = { mode: 'auto' as const }): ComponentFixture { + const fixture = TestBed.createComponent(ReferenceStep); + fixture.componentRef.setInput('choice', choice); + fixture.detectChanges(); + http.expectOne(LIST_URL).flush(COHORTS); + fixture.detectChanges(); + return fixture; + } + + function subirButton(fixture: ComponentFixture): HTMLButtonElement { + return Array.from(fixture.nativeElement.querySelectorAll('button')).find((b) => + b.textContent?.includes('Subir'), + )!; + } + + // Fails if the columns stop rendering, or sizes and ages lose their units/words. + it('lists the cohorts with their size in MB/GB and whether ages are present', () => { + const fixture = create(); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('referencia_2026'); + expect(text).toContain('120'); + expect(text).toContain('2.4 GB'); + expect(text).toContain('5.2 MB'); + expect(text).toContain('Sí'); + expect(text).toContain('No'); + expect(tamano(999e9)).toBe('999.0 GB'); + }); + + // Fails if files stop uploading one at a time, lose their progress/result, or the table doesn't reload. + it('uploads the files sequentially with progress and refreshes the table', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.name.setValue('referencia_2026'); + step.selectedFiles.set([new File(['a'], 'a.edf'), new File(['b'], 'b.edf')]); + step.upload(); + fixture.detectChanges(); + + const first = http.expectOne(UPLOAD_URL); + http.expectNone(() => true); + first.event({ type: HttpEventType.UploadProgress, loaded: 50, total: 100 }); + expect(step.uploads()[0]).toMatchObject({ fileName: 'a.edf', progress: 50, status: 'uploading', detail: '50%' }); + + first.flush({ name: 'referencia_2026', file: 'a.edf', size_bytes: 4e6 }); + expect(step.uploads()[0].status).toBe('done'); + const second = http.expectOne(UPLOAD_URL); + second.flush({ name: 'referencia_2026', file: 'b.edf', size_bytes: 8e6 }); + + const reload = http.expectOne(LIST_URL); + reload.flush([...COHORTS, { name: 'nueva', edfs: 1, size_bytes: 1e6, has_ages: false, path: '/ref/nueva' }]); + fixture.detectChanges(); + expect(step.uploads().map((u) => u.status)).toEqual(['done', 'done']); + expect(step.uploads()[1].detail).toContain('b.edf guardado'); + expect(step.cohorts().map((c) => c.name)).toEqual(['referencia_2026', 'otra', 'nueva']); + expect(step.selectedFiles()).toEqual([]); + }); + + // Fails if a 503 stops disabling the upload, or the server's message is replaced by a generic one. + it('shows the server message and disables the upload when the volume answers 503', () => { + const fixture = TestBed.createComponent(ReferenceStep); + fixture.detectChanges(); + http.expectOne(LIST_URL).flush({ error: 'TEA_REFERENCE_ROOT no está configurado' }, { status: 503, statusText: 'Service Unavailable' }); + fixture.detectChanges(); + + expect(fixture.nativeElement.textContent).toContain('TEA_REFERENCE_ROOT no está configurado'); + expect(fixture.componentInstance.rootMissing()).toBe(true); + expect(subirButton(fixture).disabled).toBe(true); + }); + + // Fails if a bad cohort name still uploads, or the pattern loosens beyond the route's. + it('blocks the upload until the cohort name matches the route pattern', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.name.setValue('nombre inválido'); + step.selectedFiles.set([new File(['a'], 'a.edf')]); + step.upload(); + http.expectNone(() => true); + + step.name.setValue('referencia_2026'); + expect(step.name.valid).toBe(true); + }); + + // Fails if a failed file stops the batch, hides its error, or skips the final reload. + it('keeps uploading after a failed file and still refreshes the table', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.name.setValue('referencia_2026'); + step.selectedFiles.set([new File(['a'], 'a.edf'), new File(['b'], 'b.edf')]); + step.upload(); + + http.expectOne(UPLOAD_URL).flush({ name: 'referencia_2026', file: 'a.edf', size_bytes: 4e6 }); + http.expectOne(UPLOAD_URL).flush({ error: 'EDF inválido' }, { status: 400, statusText: 'Bad Request' }); + http.expectOne(LIST_URL).flush(COHORTS); + fixture.detectChanges(); + + expect(step.uploads().map((u) => u.status)).toEqual(['done', 'error']); + expect(step.uploads()[1].detail).toBe('EDF inválido'); + expect(fixture.nativeElement.textContent).toContain('EDF inválido'); + }); +}); diff --git a/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.ts b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.ts new file mode 100644 index 0000000..f32d1cc --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reference-step/reference-step.ts @@ -0,0 +1,152 @@ +import { DecimalPipe } from '@angular/common'; +import { HttpEventType } from '@angular/common/http'; +import { Component, DestroyRef, OnInit, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { finalize } from 'rxjs'; +import { apiErrorMessage } from '../../../../connect/api/api.types'; +import { TeaEegApi } from '../../../api/tea-eeg.api'; +import { ClusterChoice, ReferenceCohort } from '../../../api/tea-eeg.types'; + +/** Cohort names the volume accepts; mirrors the route's `[A-Za-z0-9._-]{1,64}`. */ +export const NOMBRE_COHORTE = /^[A-Za-z0-9._-]{1,64}$/; + +export interface UploadItem { + fileName: string; + progress: number | null; + status: 'uploading' | 'done' | 'error'; + detail: string; +} + +/** Human size of a cohort folder. */ +export function tamano(bytes: number): string { + if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`; + return `${(bytes / 1e6).toFixed(1)} MB`; +} + +/** + * The reference step: the cohorts already on the shared volume with their EDF count, size and whether + * ages are present, and the upload of more files. Files go up one request at a time with a progress bar + * and a per-file result; the table refreshes when the batch ends. A 503 means `TEA_REFERENCE_ROOT` is + * not configured and disables the upload. + */ +@Component({ + selector: 'app-reference-step', + imports: [ + DecimalPipe, + MatButtonModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressBarModule, + MatTableModule, + ReactiveFormsModule, + ], + templateUrl: './reference-step.html', + styleUrl: './reference-step.scss', +}) +export class ReferenceStep implements OnInit { + private readonly api = inject(TeaEegApi); + private readonly destroyRef = inject(DestroyRef); + + /** The picked cluster; 'remote' uploads don't reach the workers' volume. */ + readonly choice = input({ mode: 'auto' }); + readonly cohorts = signal([]); + readonly loading = signal(false); + readonly loadError = signal(null); + /** The volume isn't configured (503); nothing to list or upload. */ + readonly rootMissing = signal(false); + readonly name = new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.pattern(NOMBRE_COHORTE)] }); + readonly selectedFiles = signal([]); + readonly uploads = signal([]); + readonly uploading = signal(false); + readonly displayedColumns = ['name', 'edfs', 'size', 'ages']; + protected readonly tamano = tamano; + + ngOnInit(): void { + this.load(); + } + + load(): void { + this.loading.set(true); + this.api + .listReferenceCohorts() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (cohorts) => { + this.loading.set(false); + this.cohorts.set(cohorts); + this.loadError.set(null); + }, + error: (error) => { + this.loading.set(false); + if (error?.status === 503) this.rootMissing.set(true); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las cohortes de referencia.')); + }, + }); + } + + onFilesPicked(event: Event): void { + const input = event.target as HTMLInputElement; + this.selectedFiles.set(Array.from(input.files ?? [])); + } + + upload(): void { + if (this.name.invalid || !this.selectedFiles().length || this.rootMissing()) return; + const cohort = this.name.value.trim(); + const items: UploadItem[] = this.selectedFiles().map((file) => ({ + fileName: file.name, + progress: null, + status: 'uploading', + detail: 'En espera', + })); + this.uploads.set(items); + this.uploading.set(true); + this.run(cohort, this.selectedFiles(), items, 0); + } + + /** One file after another; the table reloads when the last one settles. */ + private run(cohort: string, files: File[], items: UploadItem[], index: number): void { + if (index >= files.length) { + this.uploading.set(false); + this.selectedFiles.set([]); + this.load(); + return; + } + this.api + .uploadReferenceFile(cohort, files[index]) + .pipe( + takeUntilDestroyed(this.destroyRef), + finalize(() => this.run(cohort, files, items, index + 1)), + ) + .subscribe({ + next: (event) => { + const item = items[index]; + if (event.type === HttpEventType.UploadProgress) { + item.progress = event.total ? Math.round((event.loaded / event.total) * 100) : null; + item.detail = item.progress === null ? 'Subiendo…' : `${item.progress}%`; + } else if (event.type === HttpEventType.Response && event.body) { + item.status = 'done'; + item.progress = 100; + item.detail = `${event.body.file} guardado (${tamano(event.body.size_bytes)})`; + } + this.uploads.set([...items]); + }, + error: (error) => { + if (error?.status === 503) this.rootMissing.set(true); + items[index] = { + ...items[index], + status: 'error', + detail: apiErrorMessage(error, 'No se pudo subir el archivo.'), + }; + this.uploads.set([...items]); + }, + }); + } +} diff --git a/src/app/governance/components/tea-eeg-panel/report-fields.ts b/src/app/governance/components/tea-eeg-panel/report-fields.ts new file mode 100644 index 0000000..ee2d1ae --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/report-fields.ts @@ -0,0 +1,17 @@ +/** The three validation report fields with the labels the model version dialog shows. */ +import { ReportField } from '../../api/governance.types'; + +export const REPORT_FIELDS: { field: ReportField; label: string }[] = [ + { field: 'technical_validation_report_uri', label: 'Pruebas técnicas (MLD-01)' }, + { field: 'clinical_validation_report_uri', label: 'Validación clínica (MLD-01b)' }, + { field: 'interpretability_report_uri', label: 'Interpretabilidad (MLD-03)' }, +]; + +/** The PATCH body from the form values; empty fields clear the tag. */ +export function reportsBody(values: Record): Partial> { + return { + technical_validation_report_uri: values.technical_validation_report_uri.trim() || null, + clinical_validation_report_uri: values.clinical_validation_report_uri.trim() || null, + interpretability_report_uri: values.interpretability_report_uri.trim() || null, + }; +} diff --git a/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.html b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.html new file mode 100644 index 0000000..6955d9b --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.html @@ -0,0 +1,59 @@ +
+

Versiones candidatas de TEA

+ @if (loading()) { + + } + @if (loadError(); as error) { + + } + @if (!loading() && !loadError()) { + @if (rows().length) { + + + + + + + + + + + + + + + +
Aplicar + + Versión{{ row.label }}Estado + @if (row.status === 'applying') { + Aplicando… + } @else if (row.status === 'done') { + Aplicado + } @else if (row.status === 'error') { + {{ row.error }} + } @else { + Pendiente + } +
+ } @else { +

No hay versiones eeg-* candidatas.

+ } + } + +

Reportes de validación

+
+ @for (field of fields; track field.field) { + + {{ field.label }} + + + } + +
+ @if (result(); as line) { +

{{ line }}

+ } +
diff --git a/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.scss b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.scss new file mode 100644 index 0000000..ed1058c --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.scss @@ -0,0 +1,59 @@ +.reports { + display: flex; + flex-direction: column; + gap: var(--space-3); + max-width: 860px; +} + +.report__title { + font: var(--mat-sys-title-small); + margin: 0; +} + +.report__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.report__muted { + color: var(--mat-sys-on-surface-variant); + margin: 0; +} + +.report__table { + width: 100%; +} + +.report__status { + align-items: center; + display: inline-flex; + font: var(--mat-sys-body-small); + gap: var(--space-1); +} + +.report__status--ok { + color: var(--mat-sys-primary); +} + +.report__status--fail { + color: var(--mat-sys-error); +} + +.report__bar { + width: 120px; +} + +.report__form { + display: grid; + gap: var(--space-2); + grid-template-columns: 1fr; + + button { + justify-self: start; + } +} diff --git a/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.spec.ts b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.spec.ts new file mode 100644 index 0000000..ccc0125 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.spec.ts @@ -0,0 +1,145 @@ +/** + * Covers the reports step: the candidate table lists the latest non-retired eeg-* version of each + * scenario, all ticked, and applying PATCHes the three report URIs onto every ticked version one request + * at a time (empty fields become null) with a per-version status; a failed PATCH doesn't stop the rest. + * Fixtures: canned `ModelVersion[]` answers and PATCH requests through `HttpTestingController`. + */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ModelVersion } from '../../../api/governance.types'; +import { ReportsStep } from './reports-step'; + +const VERSIONS_URL = '/governance/model-versions'; + +function version(scenario: string, v: string, created_at: string, status: ModelVersion['status'] = 'candidata'): ModelVersion { + return { name: `tea-${scenario}`, version: v, run_id: 'r1', tags: { domain: 'tea', scenario }, metrics: {}, created_at, status }; +} + +// Seven eeg-* scenarios; eeg-alpha has a newer retirada that must not be the candidate, and riesgo_tea +// must stay out of the table. +const VERSIONS: ModelVersion[] = [ + version('eeg-alpha', '2', '2026-11-02T00:00:00+00:00'), + version('eeg-alpha', '3', '2026-11-03T00:00:00+00:00', 'retirada'), + version('eeg-beta', '1', '2026-11-04T00:00:00+00:00'), + version('eeg-coherence', '1', '2026-11-05T00:00:00+00:00'), + version('eeg-fractal', '1', '2026-11-06T00:00:00+00:00'), + version('eeg-nsr', '3', '2026-11-07T00:00:00+00:00'), + version('eeg-ratios', '1', '2026-11-08T00:00:00+00:00'), + version('eeg-theta', '1', '2026-11-09T00:00:00+00:00'), + version('riesgo_tea', '9', '2026-11-10T00:00:00+00:00'), +]; + +const EXPECTED_URLS = ['eeg-alpha/2', 'eeg-beta/1', 'eeg-coherence/1', 'eeg-fractal/1', 'eeg-nsr/3', 'eeg-ratios/1', 'eeg-theta/1'].map( + (path) => `/governance/model-versions/tea/${path}/reports`, +); + +describe('ReportsStep', () => { + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + function create(): ComponentFixture { + const fixture = TestBed.createComponent(ReportsStep); + fixture.detectChanges(); + const req = http.expectOne((r) => r.url === VERSIONS_URL); + expect(req.request.params.get('domain')).toBe('tea'); + req.flush({ model_versions: VERSIONS }); + fixture.detectChanges(); + return fixture; + } + + // Fails if the candidate selection changes (retirada wins, non-eeg rows appear), or boxes stop being + // ticked by default. + it('lists the latest non-retired eeg-* version of each scenario, all ticked', () => { + const fixture = create(); + const rows = fixture.componentInstance.rows(); + expect(rows.map((r) => `${r.scenario}:${r.version}`)).toEqual([ + 'eeg-alpha:2', 'eeg-beta:1', 'eeg-coherence:1', 'eeg-fractal:1', 'eeg-nsr:3', 'eeg-ratios:1', 'eeg-theta:1', + ]); + expect(rows.every((r) => r.checked)).toBe(true); + expect(fixture.nativeElement.textContent).not.toContain('riesgo_tea'); + }); + + // Fails if the PATCHes stop being sequential, lose the trimmed/null body, or skip the summary line. + it('applies the report URIs to every ticked version sequentially', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.reports.setValue({ + technical_validation_report_uri: ' file:///informes/pruebas.pdf ', + clinical_validation_report_uri: ' ', + interpretability_report_uri: '', + }); + step.apply(); + fixture.detectChanges(); + + for (const [i, url] of EXPECTED_URLS.entries()) { + const req = http.expectOne((r) => r.url === url); + expect(req.request.method).toBe('PATCH'); + expect(req.request.body).toEqual({ + technical_validation_report_uri: 'file:///informes/pruebas.pdf', + clinical_validation_report_uri: null, + interpretability_report_uri: null, + }); + req.flush({}); + expect(step.rows()[i].status).toBe('done'); + } + fixture.detectChanges(); + expect(step.applying()).toBe(false); + expect(fixture.nativeElement.textContent).toContain('Reportes aplicados a 7 de 7 versiones.'); + }); + + // Fails if the step keeps the list it read when the page opened, so versions imported or trained in an earlier + // step never show up for their reports until the page is reloaded. + it('lists the versions again when the step becomes active', () => { + const fixture = create(); + fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + const req = http.expectOne((r) => r.url === VERSIONS_URL); + req.flush({ model_versions: VERSIONS.slice(0, 2) }); + fixture.detectChanges(); + expect(fixture.componentInstance.rows().length).toBeLessThanOrEqual(2); + fixture.destroy(); + }); + + // Fails if the apply button works with every address blank, which would send null reports to all versions. + it('keeps the apply button disabled until a report address is typed', () => { + const fixture = create(); + const step = fixture.componentInstance; + const button = () => fixture.nativeElement.querySelector('button[type=submit]') as HTMLButtonElement; + expect(button().disabled).toBe(true); + step.reports.patchValue({ clinical_validation_report_uri: ' ' }); + fixture.detectChanges(); + expect(button().disabled).toBe(true); + step.reports.patchValue({ clinical_validation_report_uri: 'file:///informes/clinica.pdf' }); + fixture.detectChanges(); + expect(button().disabled).toBe(false); + }); + + // Fails if an unticked version still gets the PATCH, or a failed one stops the batch. + it('skips unticked versions and keeps going after a failure', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.toggle(step.rows()[0]); + step.apply(); + + const first = http.expectOne(EXPECTED_URLS[1]); + http.expectNone(EXPECTED_URLS[0]); + first.flush({}); + const failing = http.expectOne(EXPECTED_URLS[2]); + failing.flush({ error: 'La versión está retirada' }, { status: 409, statusText: 'Conflict' }); + http.expectOne(EXPECTED_URLS[3]).flush({}); + for (const url of EXPECTED_URLS.slice(4)) http.expectOne(url).flush({}); + fixture.detectChanges(); + + expect(step.rows()[0].status).toBe('pending'); + expect(step.rows()[2]).toMatchObject({ status: 'error', error: 'La versión está retirada' }); + expect(step.rows().filter((r) => r.status === 'done')).toHaveLength(5); + expect(fixture.nativeElement.textContent).toContain('La versión está retirada'); + expect(fixture.nativeElement.textContent).toContain('Reportes aplicados a 5 de 7 versiones.'); + }); +}); diff --git a/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.ts b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.ts new file mode 100644 index 0000000..ffad6e9 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/reports-step/reports-step.ts @@ -0,0 +1,150 @@ +import { Component, DestroyRef, OnInit, computed, effect, inject, input, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTableModule } from '@angular/material/table'; +import { finalize } from 'rxjs'; +import { apiErrorMessage } from '../../../../connect/api/api.types'; +import { GovernanceApi } from '../../../api/governance.api'; +import { ReportField } from '../../../api/governance.types'; +import { REPORT_FIELDS, reportsBody } from '../report-fields'; +import { teaCandidates, versionKey } from '../tea-candidates'; + +/** One candidate version and how its PATCH is doing. */ +export interface ReportRow { + key: string; + scenario: string; + version: string; + label: string; + checked: boolean; + status: 'pending' | 'applying' | 'done' | 'error'; + error: string | null; +} + +/** + * The reports step: the latest non-retired eeg-* version of every scenario (the current production + * candidates) with a checkbox each, and one form for the three validation report URIs. Applying PATCHes + * the reports onto every ticked version, one request at a time, with a per-version status. + */ +@Component({ + selector: 'app-reports-step', + imports: [ + MatButtonModule, + MatCheckboxModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressBarModule, + MatTableModule, + ReactiveFormsModule, + ], + templateUrl: './reports-step.html', + styleUrl: './reports-step.scss', +}) +export class ReportsStep implements OnInit { + private readonly api = inject(GovernanceApi); + private readonly destroyRef = inject(DestroyRef); + + readonly rows = signal([]); + readonly loading = signal(false); + readonly loadError = signal(null); + readonly applying = signal(false); + readonly result = signal(null); + readonly fields = REPORT_FIELDS; + readonly displayedColumns = ['apply', 'version', 'status']; + + readonly reports = inject(FormBuilder).nonNullable.group({ + technical_validation_report_uri: [''], + clinical_validation_report_uri: [''], + interpretability_report_uri: [''], + }); + + private readonly values = toSignal(this.reports.valueChanges, { initialValue: this.reports.getRawValue() }); + /** True once at least one report address is typed; applying nothing would claim a change that never happened. */ + readonly hasReports = computed(() => Object.values(this.values()).some((value) => (value ?? '').trim() !== '')); + + /** True while the step is the one on screen: each time it turns true the versions are listed again. */ + readonly active = input(false); + + constructor() { + effect(() => { + if (this.active() && !untracked(() => this.applying())) untracked(() => this.load()); + }); + } + + ngOnInit(): void { + this.load(); + } + + private load(): void { + this.loading.set(true); + this.api + .listModelVersions({ domain: 'tea' }) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: ({ model_versions }) => { + this.loading.set(false); + this.rows.set( + teaCandidates(model_versions).map((v) => ({ + key: versionKey(v), + scenario: v.tags.scenario!, + version: v.version, + label: `${v.name}:${v.version}`, + checked: true, + status: 'pending' as const, + error: null, + })), + ); + }, + error: (error) => { + this.loading.set(false); + this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones.')); + }, + }); + } + + toggle(row: ReportRow): void { + if (this.applying()) return; + this.rows.set(this.rows().map((r) => (r.key === row.key ? { ...r, checked: !r.checked } : r))); + } + + /** PATCHes the reports onto every ticked version, sequentially; a failure doesn't stop the rest. */ + apply(): void { + const targets = this.rows().filter((r) => r.checked); + if (!targets.length || this.applying()) return; + this.applying.set(true); + this.result.set(null); + this.applyNext(targets, this.reports.getRawValue() as Record, 0); + } + + private applyNext(targets: ReportRow[], values: Record, index: number): void { + if (index >= targets.length) { + this.applying.set(false); + const done = this.rows().filter((r) => r.status === 'done').length; + this.result.set(`Reportes aplicados a ${done} de ${this.rows().length} versiones.`); + return; + } + const row = targets[index]; + this.patch(row.key, { status: 'applying' }); + this.api + .attachReports('tea', row.scenario, row.version, reportsBody(values)) + .pipe( + takeUntilDestroyed(this.destroyRef), + finalize(() => this.applyNext(targets, values, index + 1)), + ) + .subscribe({ + next: () => this.patch(row.key, { status: 'done' }), + error: (error) => + this.patch(row.key, { status: 'error', error: apiErrorMessage(error, 'No se pudieron aplicar los reportes.') }), + }); + } + + private patch(key: string, partial: Partial): void { + this.rows.set(this.rows().map((r) => (r.key === key ? { ...r, ...partial } : r))); + } +} diff --git a/src/app/governance/components/tea-eeg-panel/tea-candidates.ts b/src/app/governance/components/tea-eeg-panel/tea-candidates.ts new file mode 100644 index 0000000..a622c42 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/tea-candidates.ts @@ -0,0 +1,20 @@ +/** The eeg-* versions the reports and promotion steps act on. */ +import { ModelVersion } from '../../api/governance.types'; + +/** Latest non-retired version of each `eeg-*` scenario, sorted by scenario; the current production + * candidate of every TEA·EEG model. */ +export function teaCandidates(versions: ModelVersion[]): ModelVersion[] { + const latest = new Map(); + for (const version of versions) { + const scenario = version.tags.scenario; + if (!scenario?.startsWith('eeg-') || version.status === 'retirada') continue; + const current = latest.get(scenario); + if (!current || version.created_at > current.created_at) latest.set(scenario, version); + } + return [...latest.values()].sort((a, b) => a.tags.scenario!.localeCompare(b.tags.scenario!)); +} + +/** Stable key of a version within the step tables. */ +export function versionKey(version: ModelVersion): string { + return `${version.tags.scenario}:${version.version}`; +} diff --git a/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.html b/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.html new file mode 100644 index 0000000..9bfcf0f --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.html @@ -0,0 +1,32 @@ + + +
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.scss b/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.scss new file mode 100644 index 0000000..d0e7ac9 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.scss @@ -0,0 +1,15 @@ +.tea-eeg__cluster { + display: flex; + flex-direction: column; + gap: var(--space-3); + max-width: 760px; +} + +.tea-eeg app-reference-step, +.tea-eeg app-training-step, +.tea-eeg app-baselines-step, +.tea-eeg app-reports-step, +.tea-eeg app-promote-step { + display: block; + padding-top: var(--space-3); +} diff --git a/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.ts b/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.ts new file mode 100644 index 0000000..57b4e4f --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/tea-eeg-panel.ts @@ -0,0 +1,36 @@ +import { Component, signal } from '@angular/core'; +import { MatStepperModule } from '@angular/material/stepper'; +import { ClusterChoice } from '../../api/tea-eeg.types'; +import { AnalyzeStepComponent } from '../analyze-step/analyze-step'; +import { BaselineCheckComponent } from '../baseline-check/baseline-check'; +import { ResultStepComponent } from '../result-step/result-step'; +import { ClusterHealthCard } from '../cluster-health-card/cluster-health-card'; +import { ClusterSelector } from '../cluster-selector/cluster-selector'; +import { BaselinesStep } from './baselines-step/baselines-step'; +import { PromoteStep } from './promote-step/promote-step'; +import { ReferenceStep } from './reference-step/reference-step'; +import { ReportsStep } from './reports-step/reports-step'; +import { TrainingStep } from './training-step/training-step'; + +@Component({ + selector: 'app-tea-eeg-panel', + imports: [ + AnalyzeStepComponent, + BaselineCheckComponent, + BaselinesStep, + ClusterHealthCard, + ClusterSelector, + MatStepperModule, + PromoteStep, + ReferenceStep, + ReportsStep, + ResultStepComponent, + TrainingStep, + ], + templateUrl: './tea-eeg-panel.html', + styleUrl: './tea-eeg-panel.scss', +}) +export class TeaEegPanel { + /** The cluster the wizard's steps run on. */ + readonly choice = signal({ mode: 'auto' }); +} diff --git a/src/app/governance/components/tea-eeg-panel/training-step/training-step.html b/src/app/governance/components/tea-eeg-panel/training-step/training-step.html new file mode 100644 index 0000000..81e86f3 --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/training-step/training-step.html @@ -0,0 +1,108 @@ +
+

Parámetros del entrenamiento

+ @if (cohortsError(); as error) { + + } +
+ + Cohorte de referencia + + La que use el servidor + @for (cohort of cohorts(); track cohort.name) { + {{ cohort.name }} ({{ cohort.edfs }} EDF) + } + + + + Carpeta en el clúster + + Ruta absoluta; se usa cuando no hay cohorte elegida. + + + Tabla de edades en el clúster + + Opcional. Sin ella, la edad sale de la cabecera de cada EDF. + + + 50 Hz + 60 Hz + + Promover al terminar + +
+ @if (startError(); as error) { + + } + +

Entrenamientos

+ @if (jobsError(); as error) { + + + } + @if (jobs().length) { +
    + @for (job of jobs(); track job.id) { +
  • + + + {{ estados[job.estado] }} + + {{ job.scenario }} · {{ job.iniciado | date: 'medium' }} + @if (monitorIds().includes(job.id)) { + + } @else { +
    + Ver progreso + @if (progressOpen.get(job.id)) { } +
    + } + @if (job.salida) { +
    + Ver salida +
    {{ job.salida }}
    +
    + } +
  • + } +
+ } @else if (jobsLoading()) { + + } @else if (!jobsError()) { +

Todavía no hay entrenamientos de TEA.

+ } + + @if (versionsLoaded()) { +

Versiones eeg-* producidas

+ @if (versionsLoading()) { + + } + @if (versionsError(); as error) { + + } + @if (!versionsLoading() && !versionsError()) { + @if (versions().length) { + + + + + + + + + + + + + + + +
Versión{{ v.name }}:{{ v.version }}EstadoCreada{{ v.created_at | date: 'medium' }}
+ } @else { +

El entrenamiento no produjo versiones eeg-*.

+ } + } + } +
diff --git a/src/app/governance/components/tea-eeg-panel/training-step/training-step.scss b/src/app/governance/components/tea-eeg-panel/training-step/training-step.scss new file mode 100644 index 0000000..3c94d4d --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/training-step/training-step.scss @@ -0,0 +1,96 @@ +.train { + display: flex; + flex-direction: column; + gap: var(--space-3); + max-width: 860px; +} + +.train__title { + font: var(--mat-sys-title-small); + margin: 0; +} + +.train__alert { + align-items: center; + background: var(--mat-sys-error-container); + color: var(--mat-sys-on-error-container); + display: flex; + gap: var(--space-2); + margin: 0; + padding: var(--space-2) var(--space-3); +} + +.train__muted { + color: var(--mat-sys-on-surface-variant); + margin: 0; +} + +.train__form { + align-items: flex-start; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + + mat-form-field { + min-width: 240px; + } + + mat-checkbox { + align-self: center; + } + + button { + align-self: center; + } +} + +.train__jobs { + display: flex; + flex-direction: column; + gap: var(--space-2); + list-style: none; + margin: 0; + padding: 0; + + li { + display: flex; + flex-direction: column; + gap: var(--space-1); + } +} + +.train__state { + align-items: center; + display: inline-flex; + font: var(--mat-sys-label-medium); + gap: var(--space-1); +} + +.train__state--run { + color: var(--mat-sys-primary); +} + +.train__meta { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); +} + +.train__output { + summary { + cursor: pointer; + font: var(--mat-sys-body-small); + } + + pre { + background: var(--mat-sys-surface-container); + font: var(--mat-sys-body-small); + margin: 4px 0 0; + max-height: 240px; + overflow: auto; + padding: 8px; + } +} + +.train__table { + width: 100%; +} diff --git a/src/app/governance/components/tea-eeg-panel/training-step/training-step.spec.ts b/src/app/governance/components/tea-eeg-panel/training-step/training-step.spec.ts new file mode 100644 index 0000000..b03b1cd --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/training-step/training-step.spec.ts @@ -0,0 +1,148 @@ +/** + * Covers the training step: the form builds the train body (cohorte or cluster folder, line Hz, promote, + * picked cluster), the TEA jobs are polled every 3 s while one runs, the ended job lists the eeg-* + * versions it produced, and a 409 surfaces the message plus the running job. Fixtures: a real + * `HttpClient` answered by `HttpTestingController` for both the TEA and the governance routes. + */ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ModelVersion, TrainingJob } from '../../../api/governance.types'; +import { TrainingStep } from './training-step'; + +const COHORTS_URL = '/governance/tea/reference-cohorts'; +const JOBS_URL = '/governance/training-jobs'; +const TRAIN_URL = '/governance/model-versions/tea/eeg/train-jobs'; +const PROGRESS_URL = '/governance/tea/jobs/train/t1/progress'; +const VERSIONS_URL = '/governance/model-versions'; + +const job = (estado: TrainingJob['estado']): TrainingJob => ({ + id: 't1', domain: 'tea', scenario: 'eeg', iniciado: '2026-11-20T10:00:00+00:00', + estado, codigo: estado === 'fallido' ? 1 : 0, salida: 'trained: version 3', error: '', +}); + +// Seven eeg-* versions plus one TEA version of another scenario that must stay out of the list. +const VERSIONS: ModelVersion[] = [ + ...['eeg-alpha', 'eeg-beta', 'eeg-coherence', 'eeg-fractal', 'eeg-nsr', 'eeg-ratios', 'eeg-theta'].map( + (scenario, i): ModelVersion => ({ + name: `tea-${scenario}`, version: String(i + 1), run_id: 'r1', + tags: { domain: 'tea', scenario, environment: 'prod' }, metrics: {}, + created_at: `2026-11-2${i}T00:00:00+00:00`, status: 'produccion', + }), + ), + { name: 'tea-riesgo', version: '9', run_id: 'r9', tags: { domain: 'tea', scenario: 'riesgo_tea' }, metrics: {}, created_at: '2026-11-29T00:00:00+00:00', status: 'produccion' }, +]; + +describe('TrainingStep', () => { + let http: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + + function create(choice = { mode: 'remote' as const, scheduler: 'tcp://equipo:8786' }): ComponentFixture { + const fixture = TestBed.createComponent(TrainingStep); + fixture.componentRef.setInput('choice', choice); + fixture.detectChanges(); + http.expectOne(COHORTS_URL).flush([{ name: 'referencia_2026', edfs: 120, size_bytes: 1e9, has_ages: true, path: '/ref' }]); + http.expectOne(JOBS_URL).flush({ jobs: [] }); + fixture.detectChanges(); + return fixture; + } + + function expectVersions() { + const req = http.expectOne((r) => r.url === VERSIONS_URL); + expect(req.request.params.get('domain')).toBe('tea'); + return req; + } + + // Fails if the form stops mapping to the train body, or the cluster choice doesn't reach it. + it('starts the training with the form values and the picked cluster', () => { + const fixture = create(); + fixture.componentInstance.form.setValue({ reference_name: 'referencia_2026', reference_dir: '', reference_ages: '', line_hz: 50, promote: false }); + fixture.componentInstance.train(); + + const req = http.expectOne(TRAIN_URL); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual({ + reference_name: 'referencia_2026', line_hz: 50, promote: false, + cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' }, + }); + req.flush({ job: job('en_curso') }); + http.expectOne(JOBS_URL).flush({ jobs: [job('en_curso')] }); + }); + + // Fails if the 3 s polling is dropped, the state label/output disappear, or the ended job stops + // listing the eeg-* versions. + it('polls while the job runs and lists the eeg-* versions when it ends', () => { + vi.useFakeTimers(); + try { + const fixture = create(); + const step = fixture.componentInstance; + step.form.setValue({ reference_name: '', reference_dir: '/datos/tea/referencia', reference_ages: '', line_hz: 60, promote: true }); + step.train(); + http.expectOne(TRAIN_URL).flush({ job: job('en_curso') }); + http.expectOne(JOBS_URL).flush({ jobs: [job('en_curso')] }); + fixture.detectChanges(); + http.expectOne(PROGRESS_URL).flush(null, { status: 404, statusText: 'Not Found' }); + expect(fixture.nativeElement.textContent).toContain('En curso'); + expect(fixture.nativeElement.textContent).toContain('trained: version 3'); + + vi.advanceTimersByTime(2000); + http.expectOne(PROGRESS_URL).flush(null, { status: 404, statusText: 'Not Found' }); + vi.advanceTimersByTime(1000); + http.expectOne(JOBS_URL).flush({ jobs: [job('completado')] }); + expectVersions().flush({ model_versions: VERSIONS }); + fixture.detectChanges(); + + http.expectOne(PROGRESS_URL).flush(null, { status: 404, statusText: 'Not Found' }); + expect(step.running()).toBe(false); + expect(step.versions()).toHaveLength(7); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('Entrenamiento terminado'); + expect(text).not.toContain('promovido'); + expect(text).toContain('tea-eeg-nsr:5'); + expect(text).not.toContain('tea-riesgo'); + fixture.destroy(); + } finally { + vi.useRealTimers(); + } + }); + + // Fails if a 409 stops refreshing the jobs, or the server's message is not shown. + it('answers a 409 with the message and the running job', () => { + const fixture = create(); + fixture.componentInstance.train(); + http.expectOne(TRAIN_URL).flush({ error: 'Ya hay un entrenamiento en curso' }, { status: 409, statusText: 'Conflict' }); + http.expectOne(JOBS_URL).flush({ jobs: [job('en_curso')] }); + fixture.detectChanges(); + + http.expectOne(PROGRESS_URL).flush(null, { status: 404, statusText: 'Not Found' }); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('Ya hay un entrenamiento en curso'); + expect(text).toContain('En curso'); + }); + + // Fails if a cluster-side ages table typed in the form stops reaching the training request, which leaves the + // workers reading ages from EDF headers that the reference files may not carry. + it('sends the cluster-side ages table with the folder', () => { + const fixture = create(); + const step = fixture.componentInstance; + step.form.setValue({ + reference_name: '', reference_dir: ' /referencia/helsinki ', reference_ages: ' /referencia/helsinki/edades.csv ', + line_hz: 50, promote: false, + }); + step.train(); + const request = http.expectOne(TRAIN_URL); + expect(request.request.body).toMatchObject({ + reference_dir: '/referencia/helsinki', reference_ages: '/referencia/helsinki/edades.csv', line_hz: 50, + }); + request.flush({ job: job('en_curso') }); + http.expectOne(JOBS_URL).flush({ jobs: [job('en_curso')] }); + fixture.detectChanges(); + http.expectOne(PROGRESS_URL).flush(null, { status: 404, statusText: 'Not Found' }); + fixture.destroy(); + }); +}); diff --git a/src/app/governance/components/tea-eeg-panel/training-step/training-step.ts b/src/app/governance/components/tea-eeg-panel/training-step/training-step.ts new file mode 100644 index 0000000..18c1e6b --- /dev/null +++ b/src/app/governance/components/tea-eeg-panel/training-step/training-step.ts @@ -0,0 +1,163 @@ +import { DatePipe } from '@angular/common'; +import { Component, DestroyRef, OnInit, computed, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { MatTableModule } from '@angular/material/table'; +import { finalize, timer } from 'rxjs'; +import { apiErrorMessage } from '../../../../connect/api/api.types'; +import { GovernanceApi } from '../../../api/governance.api'; +import { ModelVersion, TrainingJob } from '../../../api/governance.types'; +import { TeaEegApi } from '../../../api/tea-eeg.api'; +import { ClusterChoice, ReferenceCohort, TeaTrainBody } from '../../../api/tea-eeg.types'; +import { RunMonitorComponent } from '../../run-monitor/run-monitor'; +import { ModelStatusChip } from '../../model-status-chip/model-status-chip'; +import { ESTADOS, SONDEO_MS } from '../../model-versions-panel/model-versions-panel'; + +/** + * The training step: pick the reference cohort (or a cluster-side folder), the line frequency and + * whether to promote, then start the job on the picked cluster. The TEA jobs are polled every few + * seconds while one runs; when it ends the eeg-* versions it produced are listed. + */ +@Component({ + selector: 'app-training-step', + imports: [ + DatePipe, + MatButtonModule, + MatButtonToggleModule, + MatCheckboxModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatProgressBarModule, + MatSelectModule, + MatTableModule, + ModelStatusChip, + ReactiveFormsModule, + RunMonitorComponent, + ], + templateUrl: './training-step.html', + styleUrl: './training-step.scss', +}) +export class TrainingStep implements OnInit { + private readonly tea = inject(TeaEegApi); + private readonly governance = inject(GovernanceApi); + private readonly destroyRef = inject(DestroyRef); + + /** The picked cluster; it goes in the train body. */ + readonly choice = input({ mode: 'auto' }); + readonly cohorts = signal([]); + readonly cohortsError = signal(null); + readonly jobs = signal([]); + readonly jobsLoading = signal(false); + readonly jobsError = signal(null); + readonly progressOpen = new Map(); + readonly monitorIds = signal([]); + readonly running = computed(() => this.jobs().some((j) => j.estado === 'en_curso')); + readonly starting = signal(false); + readonly startError = signal(null); + readonly versions = signal([]); + readonly versionsLoading = signal(false); + readonly versionsError = signal(null); + readonly versionsLoaded = signal(false); + /** A finished run is only "trained" here: promotion is its own step and may not have been requested. */ + readonly estados = { ...ESTADOS, completado: 'Entrenamiento terminado' }; + readonly displayedColumns = ['version', 'status', 'created']; + + readonly form = inject(FormBuilder).nonNullable.group({ + reference_name: [''], + reference_dir: [''], + reference_ages: [''], + line_hz: 60 as 50 | 60, + promote: true, + }); + + ngOnInit(): void { + this.loadCohorts(); + this.refreshJobs(); + timer(SONDEO_MS, SONDEO_MS) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + if (this.running()) this.refreshJobs(); + }); + } + + private loadCohorts(): void { + this.tea.listReferenceCohorts().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: (cohorts) => this.cohorts.set(cohorts), + error: (error) => this.cohortsError.set(apiErrorMessage(error, 'No se pudieron cargar las cohortes.')), + }); + } + + /** The TEA jobs, newest first; when one that was running has ended, the versions are read. */ + refreshJobs(): void { + if (this.jobsLoading()) return; + const wasRunning = this.running(); + this.jobsLoading.set(true); + this.governance.trainingJobs().pipe( + takeUntilDestroyed(this.destroyRef), finalize(() => this.jobsLoading.set(false)), + ).subscribe({ + next: ({ jobs }) => { + this.jobsError.set(null); + const recent = jobs.filter((j) => j.domain === 'tea').slice(0, 5); + this.jobs.set(recent); + this.monitorIds.update((ids) => recent + .filter((job) => job.estado === 'en_curso' || ids.includes(job.id)).map((job) => job.id)); + if (wasRunning && !this.running()) this.loadVersions(); + }, + error: (error) => this.jobsError.set(apiErrorMessage(error, 'No se pudieron cargar los entrenamientos.')), + }); + } + + train(): void { + if (this.starting() || this.running() || this.jobsLoading()) return; + const value = this.form.getRawValue(); + const body: TeaTrainBody = { + ...(value.reference_name ? { reference_name: value.reference_name } : {}), + ...(value.reference_dir.trim() ? { reference_dir: value.reference_dir.trim() } : {}), + ...(value.reference_ages.trim() ? { reference_ages: value.reference_ages.trim() } : {}), + line_hz: value.line_hz, + promote: value.promote, + cluster: this.choice(), + }; + this.starting.set(true); + this.startError.set(null); + this.tea + .startTeaTraining(body) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: () => { + this.starting.set(false); + this.refreshJobs(); + }, + error: (error) => { + this.starting.set(false); + this.startError.set(apiErrorMessage(error, 'No se pudo iniciar el entrenamiento.')); + if (error?.status === 409) this.refreshJobs(); + }, + }); + } + + private loadVersions(): void { + this.versionsLoading.set(true); + this.versionsError.set(null); + this.versionsLoaded.set(true); + this.governance.listModelVersions({ domain: 'tea' }).subscribe({ + next: ({ model_versions }) => { + this.versionsLoading.set(false); + this.versions.set(model_versions.filter((v) => v.tags.scenario?.startsWith('eeg-'))); + }, + error: (error) => { + this.versionsLoading.set(false); + this.versionsError.set(apiErrorMessage(error, 'No se pudieron cargar las versiones.')); + }, + }); + } +} diff --git a/src/styles.scss b/src/styles.scss index b94de85..9b6be39 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -156,3 +156,11 @@ body { html, body, .app-shell, .app-shell--workspace, .app-main { display: block !important; height: auto !important; min-height: 0 !important; overflow: visible !important; } body { background: #fff; } } + +:root { + --eeg-blue: #1678ad; + --eeg-vermilion: #ba463f; + --eeg-purple: #995296; + --eeg-band-outer: rgba(22, 120, 173, .18); + --eeg-band-inner: rgba(22, 120, 173, .34); +} -- 2.53.0