bd897baa2d
rebuild's shell, auth and non-TEA pages; tea/parity's TEA pages on tea/parity's API. - Routes: rebuild's signed-in tree; the TEA risk page joins it (domainAllowed reads the route's data domain when the path has no :domain). - Indicadores: rebuild's header and its generic Resumen/Trazabilidad/Definiciones tabs (TEA as the reference page, fed by tea/parity's measures); TEA Seguimiento and Análisis de riesgo render tea/parity's tea-list inside rebuild's tab-seguimiento/tab-riesgos, which keep rebuild's CaCu/CaMa lists and patient search. rebuild's tab-riesgos-tea read rebuild's TEA Patient extensions, which are gone with its backend; tea-list already shows that list from tea/parity's FHIR search, so it is deleted rather than ported (its look is the base for T8/T9). - Paciente: rebuild's record for CaCu/CaMa; TEA delegates to tea/parity's TeaRecord. rebuild's inline TEA sections read its EEG detail endpoint and are removed. - Gobernanza: tea/parity's page (execution, models with checks/lineage, bundles, training, studies, preview) until T13; model headings use rebuild's model titles. figures.ts: rebuild's scenarios (drawn in the record) plus tea/parity's association forest. - plot.ts: rebuild's layout helpers on tea/parity's partial Plotly bundle. - Conectar: rebuild's KINDS/HELP with an entry for tea/parity's edf node. - Dead code removed: measures boxes/sankey (tea/parity's old TEA tab), eeg-labels headMap/byDeviation/LEVEL_NAMES/METRIC_NAMES (rebuild's TEA record), e2e/layout.ts. - e2e: tea/parity's TEA cases, signed in; rebuild's CaCu/CaMa/site cases need their hospitals loaded and come back with the page suite (T16). - openapi.json and src/app/api: regenerated in the next commit.
404 lines
14 KiB
TypeScript
404 lines
14 KiB
TypeScript
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
|
|
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
|
|
import { FormsModule } from '@angular/forms';
|
|
import { MatButtonModule } from '@angular/material/button';
|
|
import { RouterLink } from '@angular/router';
|
|
import { Api } from '../api/api';
|
|
import { studies } from '../api/fn/eeg/studies';
|
|
import { study } from '../api/fn/eeg/study';
|
|
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
|
import { analyze } from '../api/fn/models/analyze';
|
|
import { curve } from '../api/fn/models/curve';
|
|
import { lineage } from '../api/fn/models/lineage';
|
|
import { models } from '../api/fn/models/models';
|
|
import { promote } from '../api/fn/models/promote';
|
|
import { readReport$Any } from '../api/fn/models/read-report-any';
|
|
import { readReport$Json } from '../api/fn/models/read-report-json';
|
|
import { retire } from '../api/fn/models/retire';
|
|
import { score } from '../api/fn/models/score';
|
|
import { versionChecks } from '../api/fn/models/version-checks';
|
|
import { versions } from '../api/fn/models/versions';
|
|
import { domains } from '../api/fn/operations/domains';
|
|
import type { Domain } from '../api/models/domain';
|
|
import type { Execution as Choice } from '../api/models/execution';
|
|
import type { Run } from '../api/models/run';
|
|
import { DOMAINS } from '../app';
|
|
import { Plot } from '../plot';
|
|
import { Bundles, download } from './bundles';
|
|
import { Execution } from './execution';
|
|
import { interpretabilityFigures, studyPoints, type Centile } from './figures';
|
|
import { errorText, RunMonitor } from './run-monitor';
|
|
import { EegStudies } from './tea/studies';
|
|
import { Training } from './training';
|
|
|
|
const REPORTS: Record<string, string> = {
|
|
technical_validation: 'Validación técnica',
|
|
interpretability: 'Interpretabilidad',
|
|
clinical_validation: 'Validación clínica',
|
|
};
|
|
|
|
interface VersionKey {
|
|
name: string;
|
|
version: number;
|
|
}
|
|
|
|
interface Checks {
|
|
status: 'candidate' | 'champion' | 'retired';
|
|
promotable: boolean;
|
|
checks: { report: string; present: boolean }[];
|
|
}
|
|
|
|
interface Lineage {
|
|
params: Record<string, string>;
|
|
metrics: Record<string, number>;
|
|
tags: Record<string, string>;
|
|
imported: Record<string, string> | null;
|
|
}
|
|
|
|
export function checkActions(checks: Checks) {
|
|
return { promote: checks.promotable, retire: checks.status !== 'champion' };
|
|
}
|
|
|
|
@Component({
|
|
selector: 'app-gobernanza',
|
|
imports: [
|
|
DatePipe,
|
|
DecimalPipe,
|
|
KeyValuePipe,
|
|
FormsModule,
|
|
MatButtonModule,
|
|
RouterLink,
|
|
Plot,
|
|
Bundles,
|
|
Execution,
|
|
RunMonitor,
|
|
EegStudies,
|
|
Training,
|
|
],
|
|
templateUrl: './gobernanza.html',
|
|
styleUrl: './gobernanza.scss',
|
|
})
|
|
export class Gobernanza {
|
|
private readonly api = inject(Api);
|
|
readonly domain = input.required<string>();
|
|
protected readonly domainKey = computed(() => this.domain() as Domain);
|
|
protected readonly execution = signal<Choice | undefined>(undefined);
|
|
protected readonly labels = DOMAINS as Record<string, string>;
|
|
protected readonly reportNames = REPORTS;
|
|
protected readonly errorText = errorText;
|
|
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
|
protected readonly refreshed = signal(0);
|
|
|
|
protected refresh(): void {
|
|
this.refreshed.update((value) => value + 1);
|
|
}
|
|
protected readonly models = resource({
|
|
params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
|
|
loader: async ({ params: { domain } }) => {
|
|
const found = await this.api.invoke(models, { domain });
|
|
return Promise.all(
|
|
found.map(async ({ name, title }) => ({
|
|
name,
|
|
title,
|
|
versions: await this.api.invoke(versions, { domain, name }),
|
|
})),
|
|
);
|
|
},
|
|
});
|
|
protected readonly training = signal('');
|
|
protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>(
|
|
undefined,
|
|
);
|
|
protected readonly starting = signal(false);
|
|
protected readonly running = signal(false);
|
|
protected readonly editing = signal(false);
|
|
protected readonly message = signal('');
|
|
protected readonly chosen = signal<VersionKey | undefined>(undefined);
|
|
protected readonly checksFor = signal<VersionKey | undefined>(undefined);
|
|
protected readonly lineageFor = signal<VersionKey | undefined>(undefined);
|
|
protected readonly checks = resource({
|
|
params: () => {
|
|
const key = this.checksFor();
|
|
return key ? { ...key, domain: this.domainKey(), at: this.refreshed() } : undefined;
|
|
},
|
|
loader: async ({ params: { at, ...params } }) => this.getChecks(params.domain, params),
|
|
});
|
|
protected readonly checkActions = checkActions;
|
|
protected readonly lineage = resource({
|
|
params: () => {
|
|
const key = this.lineageFor();
|
|
return key ? { ...key, domain: this.domainKey() } : undefined;
|
|
},
|
|
loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage,
|
|
});
|
|
protected readonly candidates = signal<VersionKey[]>([]);
|
|
protected readonly report = resource({
|
|
params: () => {
|
|
const key = this.chosen();
|
|
return key ? { ...key, domain: this.domainKey() } : undefined;
|
|
},
|
|
loader: ({ params }) =>
|
|
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
|
|
});
|
|
protected readonly ageFeatures = computed<string[]>(() => {
|
|
const report = this.report.hasValue() ? this.report.value() : undefined;
|
|
return report?.kind === 'age_curves' ? Object.keys(report['curves']) : [];
|
|
});
|
|
protected readonly selectedFeature = signal('');
|
|
protected readonly feature = computed(() => {
|
|
const keys = this.ageFeatures();
|
|
return keys.includes(this.selectedFeature())
|
|
? this.selectedFeature()
|
|
: keys.includes('value')
|
|
? 'value'
|
|
: keys[0];
|
|
});
|
|
protected readonly band = resource({
|
|
params: () => {
|
|
const key = this.chosen();
|
|
const feature = this.feature();
|
|
if (!key || !feature || !this.report.hasValue()) return undefined;
|
|
if (this.report.value()['curves'][feature].kind === 'count_rate') return undefined;
|
|
return { ...key, domain: this.domainKey(), feature };
|
|
},
|
|
loader: async ({ params }) => (await this.api.invoke(curve, params)) as Centile[],
|
|
});
|
|
protected readonly overlay = signal(false);
|
|
protected readonly analysed = resource({
|
|
params: () =>
|
|
this.overlay() && this.domainKey() === 'tea' && this.feature()
|
|
? this.refreshed() + 1
|
|
: undefined,
|
|
loader: async () => {
|
|
const found = await this.api.invoke(studies);
|
|
return Promise.all(
|
|
found
|
|
.filter((entry) => entry.analysed)
|
|
.map(({ id }) => this.api.invoke(study, { eeg_id: id })),
|
|
);
|
|
},
|
|
});
|
|
protected readonly figures = computed(() => {
|
|
if (!this.report.hasValue()) return [];
|
|
const report = this.report.value();
|
|
const feature = this.feature();
|
|
const points =
|
|
this.analysed.hasValue() && feature
|
|
? studyPoints(this.analysed.value(), report['model'], feature)
|
|
: [];
|
|
return interpretabilityFigures(report, {
|
|
feature,
|
|
centiles: this.band.hasValue() ? this.band.value() : undefined,
|
|
points,
|
|
waitForCentiles: report['kind'] === 'age_curves',
|
|
});
|
|
});
|
|
|
|
constructor() {
|
|
effect(() => {
|
|
this.domain();
|
|
this.training.set('');
|
|
this.run.set(undefined);
|
|
this.running.set(false);
|
|
this.starting.set(false);
|
|
this.editing.set(false);
|
|
this.message.set('');
|
|
this.chosen.set(undefined);
|
|
this.checksFor.set(undefined);
|
|
this.lineageFor.set(undefined);
|
|
this.overlay.set(false);
|
|
});
|
|
}
|
|
|
|
protected async reportDownload(name: string, version: number, report: string): Promise<void> {
|
|
try {
|
|
const response = await this.api.invoke$Response(readReport$Any, {
|
|
domain: this.domainKey(),
|
|
name,
|
|
version,
|
|
report,
|
|
});
|
|
const filename = /filename="([^"]+)"/.exec(
|
|
response.headers.get('Content-Disposition') ?? '',
|
|
)?.[1];
|
|
download(response.body, filename ?? report);
|
|
} catch (error) {
|
|
this.message.set(errorText(error));
|
|
}
|
|
}
|
|
|
|
protected async upload(name: string, version: number, event: Event): Promise<void> {
|
|
const input = event.target as HTMLInputElement;
|
|
const file = input.files?.[0];
|
|
if (!file) return;
|
|
const domain = this.domainKey();
|
|
try {
|
|
await this.api.invoke(addClinicalValidation, {
|
|
domain,
|
|
name,
|
|
version,
|
|
body: { file: file as unknown as string },
|
|
});
|
|
input.value = '';
|
|
if (domain !== this.domainKey()) return;
|
|
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
|
|
this.refresh();
|
|
} catch (error) {
|
|
this.message.set(errorText(error));
|
|
}
|
|
}
|
|
|
|
protected showVersion(
|
|
kind: 'checks' | 'lineage',
|
|
key: VersionKey,
|
|
dialog: HTMLDialogElement,
|
|
): void {
|
|
(kind === 'checks' ? this.checksFor : this.lineageFor).set(key);
|
|
dialog.showModal();
|
|
}
|
|
|
|
protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise<void> {
|
|
const domain = this.domainKey();
|
|
this.editing.set(true);
|
|
this.message.set('');
|
|
try {
|
|
if (action === 'promote') await this.api.invoke(promote, { domain, ...key });
|
|
else await this.api.invoke(retire, { domain, ...key });
|
|
this.message.set(
|
|
`${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`,
|
|
);
|
|
this.refresh();
|
|
} catch (error) {
|
|
this.message.set(errorText(error));
|
|
} finally {
|
|
this.editing.set(false);
|
|
}
|
|
}
|
|
|
|
protected async prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
|
|
if (!this.models.hasValue()) return;
|
|
const domain = this.domainKey();
|
|
this.editing.set(true);
|
|
this.message.set('');
|
|
try {
|
|
const latest = this.models.value().flatMap(({ name, versions }) => {
|
|
const newest = versions.reduce<(typeof versions)[number] | undefined>(
|
|
(current, version) => (!current || version.version > current.version ? version : current),
|
|
undefined,
|
|
);
|
|
return newest?.status === 'candidate' ? [{ name, version: newest.version }] : [];
|
|
});
|
|
const allowed = await Promise.all(
|
|
latest.map(async (key) => (await this.getChecks(domain, key)).promotable),
|
|
);
|
|
if (domain !== this.domainKey()) return;
|
|
const found = latest.filter((_, index) => allowed[index]);
|
|
this.candidates.set(found);
|
|
if (found.length) dialog.showModal();
|
|
else this.message.set('No hay candidatas que se puedan promover.');
|
|
} catch (error) {
|
|
this.message.set(errorText(error));
|
|
} finally {
|
|
this.editing.set(false);
|
|
}
|
|
}
|
|
|
|
protected async promoteCandidates(dialog: HTMLDialogElement): Promise<void> {
|
|
this.editing.set(true);
|
|
this.message.set('');
|
|
try {
|
|
await this.promoteVersions(this.domainKey(), this.candidates());
|
|
dialog.close();
|
|
} finally {
|
|
this.editing.set(false);
|
|
}
|
|
}
|
|
|
|
protected forestHeight(rows: number): number {
|
|
return Math.max(360, rows * 24 + 72);
|
|
}
|
|
|
|
protected chooseReport(key: VersionKey): void {
|
|
this.overlay.set(false);
|
|
this.selectedFeature.set('');
|
|
this.chosen.set(key);
|
|
}
|
|
|
|
protected follow(id: string, label: string, autoPromote = false): void {
|
|
this.message.set('');
|
|
this.run.set({ id, label, autoPromote });
|
|
this.running.set(true);
|
|
}
|
|
|
|
protected async start(kind: 'score' | 'analyze'): Promise<void> {
|
|
const domain = this.domainKey();
|
|
this.starting.set(true);
|
|
this.message.set('');
|
|
try {
|
|
const { run_id } =
|
|
kind === 'score'
|
|
? await this.api.invoke(score, { domain })
|
|
: await this.api.invoke(analyze, { domain, body: { execution: this.execution() } });
|
|
if (domain === this.domainKey())
|
|
this.follow(run_id, kind === 'score' ? 'Cálculo de riesgos' : 'Análisis de EEG');
|
|
} catch (error) {
|
|
this.message.set(errorText(error));
|
|
} finally {
|
|
this.starting.set(false);
|
|
}
|
|
}
|
|
|
|
protected async finish(run: Run): Promise<void> {
|
|
const domain = this.domainKey();
|
|
const active = this.run();
|
|
if (active?.id !== run.id) return;
|
|
try {
|
|
if (!active.autoPromote) return;
|
|
if (run.state !== 'succeeded') {
|
|
this.message.set('No se promovió: el entrenamiento no terminó correctamente.');
|
|
return;
|
|
}
|
|
const newVersions = run.info.flatMap((line) => {
|
|
const match = /^train_models: tea\.(.+): version (\d+)$/.exec(line);
|
|
return match ? [{ name: match[1], version: Number(match[2]) }] : [];
|
|
});
|
|
if (newVersions.length) await this.promoteVersions(domain, newVersions);
|
|
else this.message.set('No se promovió: el entrenamiento no registró versiones nuevas.');
|
|
} finally {
|
|
if (domain === this.domainKey() && this.run()?.id === run.id) {
|
|
this.refresh();
|
|
this.running.set(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async getChecks(domain: Domain, key: VersionKey): Promise<Checks> {
|
|
return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks;
|
|
}
|
|
|
|
private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise<void> {
|
|
const messages = await Promise.all(
|
|
keys.map(async (key) => {
|
|
const label = `${key.name} v${key.version}`;
|
|
try {
|
|
const checks = await this.getChecks(domain, key);
|
|
if (!checks.promotable) {
|
|
const missing = checks.checks
|
|
.filter((check) => !check.present)
|
|
.map((check) => REPORTS[check.report] ?? check.report);
|
|
const reason = missing.length ? `faltan ${missing.join(', ')}` : checks.status;
|
|
return `No se promovió ${label}: ${reason}.`;
|
|
}
|
|
await this.api.invoke(promote, { domain, ...key });
|
|
return `${label}: en producción.`;
|
|
} catch (error) {
|
|
return `No se promovió ${label}: ${errorText(error)}`;
|
|
}
|
|
}),
|
|
);
|
|
if (domain !== this.domainKey()) return;
|
|
this.message.set(messages.join('\n'));
|
|
this.refresh();
|
|
}
|
|
}
|