490 lines
18 KiB
TypeScript
490 lines
18 KiB
TypeScript
import { HttpErrorResponse } from '@angular/common/http';
|
|
import {
|
|
Component,
|
|
computed,
|
|
effect,
|
|
inject,
|
|
resource,
|
|
signal,
|
|
WritableSignal,
|
|
} from '@angular/core';
|
|
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } 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 { MatListModule } from '@angular/material/list';
|
|
import { MatDialog } from '@angular/material/dialog';
|
|
import { MatTabsModule } from '@angular/material/tabs';
|
|
import { MatTableModule } from '@angular/material/table';
|
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
|
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
|
|
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
|
|
import { withFormlyMaterial } from '@ngx-formly/material';
|
|
import { Connection, NodeChange, Vflow } from 'ngx-vflow';
|
|
import { Api } from '../api/api';
|
|
import { nodeRows } from '../api/fn/ingest/node-rows';
|
|
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
|
|
import { pipelines } from '../api/fn/ingest/pipelines';
|
|
import { savePipeline } from '../api/fn/ingest/save-pipeline';
|
|
import { schema } from '../api/fn/ingest/schema';
|
|
import { sourcePreview } from '../api/fn/ingest/source-preview';
|
|
import { startRun } from '../api/fn/ingest/start-run';
|
|
import { runStatus } from '../api/fn/runs/run-status';
|
|
import type { Pipeline } from '../api/models/pipeline';
|
|
import type { Source } from '../api/models/source';
|
|
import { ConceptMapEditor } from './concept-map-editor';
|
|
import { FORMLY_TYPES, nodeSchema } from './schema-form';
|
|
import { SourceDialog, SourceDialogData, SourceDialogResult } from './source-dialog';
|
|
|
|
type Doc = Pipeline['nodes'][number];
|
|
type Kind = NonNullable<Doc['kind']>;
|
|
interface CanvasNode {
|
|
id: string;
|
|
type: 'default';
|
|
point: WritableSignal<{ x: number; y: number }>;
|
|
text: WritableSignal<string>;
|
|
width: WritableSignal<number>;
|
|
height: WritableSignal<number>;
|
|
}
|
|
|
|
function canvasNode(id: string, point: { x: number; y: number }, label: string): CanvasNode {
|
|
return {
|
|
id,
|
|
type: 'default',
|
|
point: signal(point),
|
|
text: signal(label),
|
|
width: signal(190),
|
|
height: signal(56),
|
|
};
|
|
}
|
|
|
|
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
|
|
export const KINDS: Record<Kind, string> = {
|
|
source: 'Fuente de datos',
|
|
read: 'Leer documentos',
|
|
route: 'Separar por tipo',
|
|
map: 'Traducir códigos',
|
|
extract: 'Extraer datos',
|
|
fhir: 'Leer FHIR',
|
|
join: 'Unir',
|
|
link: 'Identificar a la persona',
|
|
target: 'Guardar en la plataforma',
|
|
};
|
|
export const HELP: Record<Kind, string> = {
|
|
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
|
|
read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
|
|
route:
|
|
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
|
|
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
|
|
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
|
|
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
|
|
join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
|
|
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
|
|
target: 'Guarda los estudios ya revisados en la plataforma.',
|
|
};
|
|
const ID = /^[a-z][a-z0-9_]*$/;
|
|
|
|
/** /conectar: an operator draws a site's pipeline on a canvas (nodes and the edges between
|
|
* them), fills each node's form, previews what it gives, saves a version and runs it. */
|
|
@Component({
|
|
selector: 'app-conectar',
|
|
imports: [
|
|
FormsModule,
|
|
ReactiveFormsModule,
|
|
FormlyForm,
|
|
MatButtonModule,
|
|
MatFormFieldModule,
|
|
MatIconModule,
|
|
MatInputModule,
|
|
MatListModule,
|
|
MatTabsModule,
|
|
MatTableModule,
|
|
MatTooltipModule,
|
|
Vflow,
|
|
ConceptMapEditor,
|
|
],
|
|
// Forms are this page's only: Formly loads with it, not with the app.
|
|
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
|
|
templateUrl: './conectar.html',
|
|
styleUrl: './conectar.scss',
|
|
})
|
|
export class Conectar {
|
|
private readonly api = inject(Api);
|
|
private readonly jsonschema = inject(FormlyJsonschema);
|
|
private readonly dialog = inject(MatDialog);
|
|
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
|
|
protected readonly help = HELP;
|
|
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
|
|
protected readonly rawDraft = signal<string | undefined>(undefined);
|
|
protected readonly rawError = signal('');
|
|
|
|
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
|
|
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
|
|
|
|
protected readonly pipelineId = signal<string | undefined>(undefined);
|
|
protected readonly version = signal<number | undefined>(undefined);
|
|
/** The drawn pipeline: node configs (positions live on the canvas nodes). */
|
|
protected readonly docs = signal<Doc[]>([]);
|
|
protected readonly nodes = signal<CanvasNode[]>([]);
|
|
protected readonly edges = computed(() =>
|
|
this.docs().flatMap((d) =>
|
|
(d.inputs ?? []).map((i) => ({ id: `${i}->${d.id}`, source: i, target: d.id })),
|
|
),
|
|
);
|
|
protected readonly selected = signal<string | undefined>(undefined);
|
|
protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected()));
|
|
protected readonly message = signal('');
|
|
protected readonly run = signal<{ id: string; status: string } | undefined>(undefined);
|
|
protected readonly running = computed(() => {
|
|
const run = this.run();
|
|
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
|
|
});
|
|
|
|
/** What the node forms share: each entity's fields by their titles (the catalog's). */
|
|
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
|
|
private readonly titles = effect(() => {
|
|
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
|
|
string,
|
|
{ properties?: Record<string, { title?: string }> }
|
|
>;
|
|
this.formOptions.formState.fields = Object.fromEntries(
|
|
Object.entries(entities).map(([e, s]) => [
|
|
e,
|
|
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
|
|
]),
|
|
);
|
|
});
|
|
protected form = new UntypedFormGroup({});
|
|
protected model: Record<string, unknown> = {};
|
|
/** The selected node's form, generated from its kind's JSON Schema. */
|
|
protected readonly fields = computed<FormlyFieldConfig[]>(() => {
|
|
const kind = this.doc()?.kind;
|
|
const pipeline = this.schema.value()?.['pipeline'];
|
|
if (!kind || !pipeline) return [];
|
|
return [this.jsonschema.toFieldConfig(nodeSchema(pipeline as never, kind))];
|
|
});
|
|
|
|
protected readonly preview = signal<Record<string, unknown>[] | undefined>(undefined);
|
|
protected readonly columns = computed(() => Object.keys(this.preview()?.[0] ?? {}));
|
|
|
|
async open(id: string): Promise<void> {
|
|
const saved = await this.api.invoke(getPipeline, { pipeline_id: id });
|
|
this.pipelineId.set(id);
|
|
this.version.set(saved.version);
|
|
this.load(saved.pipeline.nodes);
|
|
this.message.set('');
|
|
}
|
|
|
|
protected create(id: string): void {
|
|
if (!ID.test(id)) {
|
|
this.message.set('El nombre va en minúsculas, sin espacios (a-z, 0-9, _).');
|
|
return;
|
|
}
|
|
this.pipelineId.set(id);
|
|
this.version.set(undefined);
|
|
this.load([]);
|
|
this.message.set('');
|
|
}
|
|
|
|
private load(docs: Doc[]): void {
|
|
this.docs.set(docs);
|
|
const depth = depths(docs);
|
|
const row = new Map<number, number>();
|
|
this.nodes.set(
|
|
docs.map((d) => {
|
|
const level = depth.get(d.id) ?? 0;
|
|
const n = row.get(level) ?? 0;
|
|
row.set(level, n + 1);
|
|
const point = d.position ?? { x: 40 + level * 260, y: 40 + n * 90 };
|
|
return canvasNode(d.id, point, text(d));
|
|
}),
|
|
);
|
|
this.select(undefined);
|
|
}
|
|
|
|
protected add(kind: Kind): void {
|
|
if (kind === 'source') {
|
|
void this.connectSource();
|
|
return;
|
|
}
|
|
this.place(kind, {});
|
|
}
|
|
|
|
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
|
|
protected async connectSource(id?: string): Promise<void> {
|
|
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
|
|
const data: SourceDialogData = {
|
|
pipeline: this.pipelineId(),
|
|
node: doc?.id,
|
|
guided: doc?.guided ?? null,
|
|
label: doc?.label ?? '',
|
|
};
|
|
const ref = this.dialog.open<SourceDialog, SourceDialogData, SourceDialogResult>(SourceDialog, {
|
|
data,
|
|
width: '760px',
|
|
maxWidth: '96vw',
|
|
maxHeight: '92vh',
|
|
autoFocus: false,
|
|
});
|
|
const result = await new Promise<SourceDialogResult | undefined>((done) =>
|
|
ref.afterClosed().subscribe(done),
|
|
);
|
|
if (!result) return;
|
|
if (doc) {
|
|
this.update(doc.id, (d) => ({ ...d, guided: result.guided, label: result.label }) as Doc);
|
|
this.select(doc.id);
|
|
} else {
|
|
this.place('source', { guided: result.guided, label: result.label });
|
|
}
|
|
this.message.set('Fuente lista. Guarde la canalización para conservarla.');
|
|
}
|
|
|
|
private place(kind: Kind, fields: Record<string, unknown>): void {
|
|
let n = 1;
|
|
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
|
|
const id = `${kind}_${n}`;
|
|
const doc = { id, kind, inputs: [], ...fields } as unknown as Doc;
|
|
this.docs.update((ds) => [...ds, doc]);
|
|
this.nodes.update((ns) => [
|
|
...ns,
|
|
canvasNode(id, { x: 60, y: 60 + ns.length * 30 }, text(doc)),
|
|
]);
|
|
this.select(id);
|
|
}
|
|
|
|
protected remove(id: string): void {
|
|
this.docs.update((ds) =>
|
|
ds
|
|
.filter((d) => d.id !== id)
|
|
.map((d) => ({ ...d, inputs: (d.inputs ?? []).filter((i) => i !== id) })),
|
|
);
|
|
this.nodes.update((ns) => ns.filter((n) => n.id !== id));
|
|
this.select(undefined);
|
|
}
|
|
|
|
protected connect({ source, target }: Connection): void {
|
|
this.update(target, (d) => ({ ...d, inputs: [...new Set([...(d.inputs ?? []), source])] }));
|
|
}
|
|
|
|
protected disconnect(target: string, source: string): void {
|
|
this.update(target, (d) => ({ ...d, inputs: (d.inputs ?? []).filter((i) => i !== source) }));
|
|
}
|
|
|
|
protected changed(changes: NodeChange[]): void {
|
|
for (const c of changes) {
|
|
if (c.type === 'select' && c.selected) this.select(c.id);
|
|
}
|
|
}
|
|
|
|
protected select(id: string | undefined): void {
|
|
this.selected.set(id);
|
|
const doc = (this.docs().find((d) => d.id === id) ?? {}) as Record<string, unknown>;
|
|
this.model = Object.fromEntries(
|
|
Object.entries(structuredClone(doc)).filter(
|
|
([k]) => !['id', 'kind', 'inputs', 'position'].includes(k),
|
|
),
|
|
);
|
|
this.form = new UntypedFormGroup({});
|
|
this.preview.set(undefined);
|
|
this.rawDraft.set(undefined);
|
|
this.rawError.set('');
|
|
}
|
|
|
|
/** A source the dialog drew (its answers make its dlt fields). */
|
|
protected guided(d: Doc): Source['guided'] {
|
|
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
|
|
}
|
|
|
|
/** The form's values into the selected node. */
|
|
protected edited(model: Record<string, unknown>): void {
|
|
const id = this.selected();
|
|
if (!id) return;
|
|
const values = Object.fromEntries(
|
|
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
|
|
);
|
|
this.update(
|
|
id,
|
|
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
|
|
);
|
|
}
|
|
|
|
/** The node as the platform keeps it (its place on the canvas aside). */
|
|
protected raw(d: Doc): string {
|
|
const { position, ...rest } = d as Doc & { position?: unknown };
|
|
return JSON.stringify(rest, null, 2);
|
|
}
|
|
|
|
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
|
|
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
|
|
* then on (unless a catalog type makes it exactly: the platform reads it back). */
|
|
protected applyRaw(): void {
|
|
const d = this.doc();
|
|
const text = this.rawDraft();
|
|
if (!d || text === undefined) return;
|
|
let parsed: Record<string, unknown>;
|
|
try {
|
|
parsed = JSON.parse(text);
|
|
} catch {
|
|
this.rawError.set('El texto no es JSON válido.');
|
|
return;
|
|
}
|
|
if (parsed['kind'] !== d.kind) {
|
|
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
|
|
return;
|
|
}
|
|
if (d.kind === 'source') {
|
|
const dlt = ['source', 'args', 'resource', 'then'] as const;
|
|
const before = d as unknown as Record<string, unknown>;
|
|
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
|
|
delete parsed['guided'];
|
|
}
|
|
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
|
|
this.select(d.id);
|
|
}
|
|
|
|
protected rename(to: string): void {
|
|
const from = this.selected();
|
|
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
|
|
this.docs.update((ds) =>
|
|
ds.map((d) => ({
|
|
...d,
|
|
id: d.id === from ? to : d.id,
|
|
inputs: (d.inputs ?? []).map((i) => (i === from ? to : i)),
|
|
})),
|
|
);
|
|
this.nodes.update((ns) => ns.map((n) => (n.id === from ? { ...n, id: to } : n)));
|
|
this.selected.set(to);
|
|
}
|
|
|
|
private update(id: string, change: (d: Doc) => Doc): void {
|
|
this.docs.update((ds) => ds.map((d) => (d.id === id ? change(d) : d)));
|
|
const doc = this.docs().find((d) => d.id === id);
|
|
if (doc)
|
|
this.nodes()
|
|
.find((n) => n.id === id)
|
|
?.text.set(text(doc));
|
|
}
|
|
|
|
/** The drawn pipeline, each node where it sits on the canvas. */
|
|
private drawn(): Pipeline {
|
|
const at = new Map(this.nodes().map((n) => [n.id, n.point()]));
|
|
return { nodes: this.docs().map((d) => ({ ...d, position: at.get(d.id) })) } as Pipeline;
|
|
}
|
|
|
|
protected async save(): Promise<boolean> {
|
|
const id = this.pipelineId();
|
|
if (!id) return false;
|
|
try {
|
|
const { version } = await this.api.invoke(savePipeline, {
|
|
pipeline_id: id,
|
|
body: this.drawn(),
|
|
});
|
|
this.version.set(version);
|
|
this.message.set(`Versión ${version} guardada.`);
|
|
this.list.reload();
|
|
return true;
|
|
} catch (e) {
|
|
this.message.set(problem(e));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** Saves, starts the `ingest` job and follows it to its end. */
|
|
protected async start(): Promise<void> {
|
|
const id = this.pipelineId();
|
|
if (!id || !(await this.save())) return;
|
|
try {
|
|
const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
|
|
this.run.set({ id: run_id, status: 'STARTING' });
|
|
while (this.running()) {
|
|
await new Promise((r) => setTimeout(r, 2000));
|
|
this.run.set({
|
|
id: run_id,
|
|
status: (await this.api.invoke(runStatus, { run_id }))['status'],
|
|
});
|
|
}
|
|
} catch (e) {
|
|
this.message.set(problem(e));
|
|
}
|
|
}
|
|
|
|
/** What the node gives: a source's first rows, or what any other node gave in the last run. */
|
|
protected async show(): Promise<void> {
|
|
const doc = this.doc();
|
|
const id = this.pipelineId();
|
|
if (!doc || !id) return;
|
|
try {
|
|
const rows =
|
|
doc.kind === 'source'
|
|
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
|
|
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
|
|
this.preview.set(rows);
|
|
this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
|
|
} catch (e) {
|
|
this.message.set(problem(e));
|
|
}
|
|
}
|
|
|
|
/** The run in Dagster's own UI (its port beside this app's). */
|
|
protected readonly dagster = computed(() => {
|
|
const run = this.run();
|
|
return run ? `${location.protocol}//${location.hostname}:5712/runs/${run.id}` : '';
|
|
});
|
|
/** The ConceptMap a node names, if its kind takes one. */
|
|
protected conceptMap(d: Doc): string | undefined {
|
|
return 'concept_map' in d ? (d.concept_map ?? undefined) : undefined;
|
|
}
|
|
protected kindLabel(kind: Doc['kind']): string {
|
|
return KINDS[kind ?? 'source'];
|
|
}
|
|
protected cell(value: unknown): string {
|
|
return typeof value === 'object' && value !== null
|
|
? JSON.stringify(value)
|
|
: String(value ?? '');
|
|
}
|
|
}
|
|
|
|
function text(d: Doc): string {
|
|
// ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
|
|
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
|
|
const kind = KINDS[d.kind ?? 'source'];
|
|
const name = escape(d.label || d.id);
|
|
return (
|
|
`<div class="node-caption" title="${kind} · ${name}">` +
|
|
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
|
|
);
|
|
}
|
|
|
|
/** Each node's distance from the sources: its column when it has no saved position. */
|
|
function depths(docs: Doc[]): Map<string, number> {
|
|
const by = new Map(docs.map((d) => [d.id, d]));
|
|
const found = new Map<string, number>();
|
|
const depth = (id: string, seen: Set<string>): number => {
|
|
if (found.has(id)) return found.get(id)!;
|
|
if (seen.has(id)) return 0;
|
|
seen.add(id);
|
|
const inputs = by.get(id)?.inputs ?? [];
|
|
const d = inputs.length ? 1 + Math.max(...inputs.map((i) => depth(i, seen))) : 0;
|
|
found.set(id, d);
|
|
return d;
|
|
};
|
|
docs.forEach((d) => depth(d.id, new Set()));
|
|
return found;
|
|
}
|
|
|
|
function problem(e: unknown): string {
|
|
if (e instanceof HttpErrorResponse) {
|
|
const detail = e.error?.detail;
|
|
return typeof detail === 'string' ? detail : JSON.stringify(detail ?? e.message);
|
|
}
|
|
return String(e);
|
|
}
|
|
|
|
function escape(text: string): string {
|
|
return text.replace(
|
|
/[&<>"']/g,
|
|
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!,
|
|
);
|
|
}
|