Conectar dialog by kind of source; plain-language canvas; login page and guard; loading indicators as the old app; survival curves of her clinical scenarios in the CaMa record

This commit is contained in:
Roberto Treviño
2026-11-28 09:30:00 -06:00
parent cc22840c3c
commit 198aae59da
72 changed files with 4122 additions and 116 deletions
+33 -7
View File
@@ -29,7 +29,9 @@
</span>
@if (pipelineId()) {
@for (k of kinds; track k[0]) {
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
<button mat-stroked-button (click)="add(k[0])" [matTooltip]="help[k[0]]">
<mat-icon>add</mat-icon>{{ k[1] }}
</button>
}
<span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button>
@@ -70,6 +72,7 @@
<mat-icon>delete</mat-icon>
</button>
</div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
@@ -86,12 +89,35 @@
} @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
@if (guided(d); as g) {
<div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)">
Avanzado (para personal técnico)
</mat-slide-toggle>
} @else if (d.kind === 'source') {
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con ayuda
</button>
}
@if (!guided(d) || advanced()) {
@if (guided(d)) {
<p class="muted">Si cambia algo aquí, la fuente deja de editarse con ayuda.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
}
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
+31
View File
@@ -109,3 +109,34 @@ h2 {
width: auto;
}
}
.help {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.source-summary {
align-items: center;
background: var(--color-background, #f7f8f6);
border: 1px solid var(--color-border);
border-radius: 8px;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
justify-content: space-between;
margin-bottom: var(--space-2);
padding: var(--space-2);
p {
align-items: center;
display: flex;
font-weight: 500;
gap: 6px;
margin: 0;
}
p mat-icon {
color: var(--color-success, #2e7d32);
}
}
+77 -10
View File
@@ -6,7 +6,10 @@ 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 { MatSlideToggleModule } from '@angular/material/slide-toggle';
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';
@@ -24,6 +27,7 @@ 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']>;
@@ -47,16 +51,29 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
/** 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',
read: 'Leer',
route: 'Filtrar',
map: 'Mapear',
extract: 'Extraer',
fhir: 'FHIR',
join: 'Unir',
link: 'Vincular',
target: 'Destino',
source: 'Fuente de datos',
read: 'Leer documentos',
route: 'Separar por tipo',
map: 'Traducir códigos',
extract: 'Sacar datos',
fhir: 'Leer FHIR',
join: 'Juntar',
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: 'Saca 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: 'Toma de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee paquetes FHIR que un sistema envió y saca de ellos los estudios.',
join: 'Junta dos entradas que hablan de lo mismo; 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_]*$/;
@@ -73,7 +90,9 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule,
MatInputModule,
MatListModule,
MatSlideToggleModule,
MatTableModule,
MatTooltipModule,
Vflow,
ConceptMapEditor,
],
@@ -85,7 +104,11 @@ const ID = /^[a-z][a-z0-9_]*$/;
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;
/** The raw form of a source drawn with the dialog ("Avanzado"). */
protected readonly advanced = signal(false);
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -158,10 +181,47 @@ export class Conectar {
}
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: [] } as unknown as Doc;
const doc = { id, kind, inputs: [], ...fields } as unknown as Doc;
this.docs.update((ds) => [...ds, doc]);
this.nodes.update((ns) => [
...ns,
@@ -204,6 +264,12 @@ export class Conectar {
);
this.form = new UntypedFormGroup({});
this.preview.set(undefined);
this.advanced.set(false);
}
/** 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. */
@@ -213,6 +279,7 @@ export class Conectar {
const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
);
if (this.advanced()) delete values['guided']; // drawn by hand from here on
this.update(
id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
+369
View File
@@ -0,0 +1,369 @@
@if (!type()) {
<h2 mat-dialog-title>¿Dónde están los datos?</h2>
<mat-dialog-content>
@if (catalog.isLoading()) {
<div class="loading" role="status">
<mat-spinner diameter="32" /> <span>Cargando opciones…</span>
</div>
}
@for (g of groups(); track g.id) {
<section class="group">
<h3>{{ g.title }}</h3>
<p class="hint">{{ g.description }}</p>
<div class="types">
@for (t of g.types; track t.id) {
<button type="button" class="type" (click)="pick(t.id)" [attr.data-type]="t.id">
<mat-icon>{{ icon(t.icon) }}</mat-icon>
<span class="type-title">{{ t.title }}</span>
<span class="type-text">{{ t.description }}</span>
</button>
}
</div>
</section>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Cancelar</button>
</mat-dialog-actions>
} @else {
<h2 mat-dialog-title class="with-icon">
<mat-icon>{{ icon(type()!.icon) }}</mat-icon> {{ type()!.title }}
</h2>
<mat-dialog-content>
<p class="hint">{{ type()!.description }}</p>
<ng-template #field let-name let-f="f">
@switch (f.type === 'server_file' ? 'folder' : f.type) {
@case ('password') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[type]="showPassword()[name] ? 'text' : 'password'"
[ngModel]="isMasked(name) ? '' : text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="isMasked(name) ? 'Guardada (escriba para cambiarla)' : f.placeholder"
[attr.data-field]="name"
autocomplete="off"
/>
<button
mat-icon-button
matSuffix
type="button"
(click)="togglePassword(name)"
[attr.aria-label]="showPassword()[name] ? 'Ocultar' : 'Mostrar'"
>
<mat-icon>{{ showPassword()[name] ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('number') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
type="number"
[ngModel]="text(name)"
(ngModelChange)="setNumber(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('select') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select [ngModel]="value(name)" (ngModelChange)="set(name, $event)">
@for (o of f.options; track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('format') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
>
@for (o of formats(); track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('table') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
@if (tables().length) {
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event); test()"
[attr.data-field]="name"
>
@for (t of tables(); track t) {
<mat-option [value]="t">{{ t }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
}
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('folder') {
<div class="picker">
<mat-form-field appearance="outline" class="grow">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
<button mat-stroked-button type="button" (click)="openFolder(name, text(name) || null)">
<mat-icon>folder_open</mat-icon> Examinar…
</button>
</div>
@if (browsing(); as b) {
@if (b.field === name) {
<div class="browser" role="group" aria-label="Carpetas del servidor">
<div class="browser-head">
@if (b.at.path) {
<button
mat-icon-button
type="button"
(click)="openFolder(name, b.at.parent)"
aria-label="Subir"
>
<mat-icon>arrow_upward</mat-icon>
</button>
<code>{{ b.at.path }}</code>
} @else {
<span class="hint">Carpetas habilitadas en el servidor</span>
}
</div>
<ul>
@for (e of b.at.entries; track e.path) {
<li>
@if (e.kind === 'folder') {
<button type="button" class="entry" (click)="openFolder(name, e.path)">
<mat-icon>folder</mat-icon> {{ e.name }}
</button>
} @else if (browsingFiles()) {
<button type="button" class="entry" (click)="chooseFile(e.path)">
<mat-icon>description</mat-icon> {{ e.name }}
</button>
} @else {
<span class="entry file"
><mat-icon>description</mat-icon> {{ e.name }}</span
>
}
</li>
} @empty {
<li class="hint">Vacía.</li>
}
</ul>
<div class="browser-actions">
<button mat-button type="button" (click)="browsing.set(undefined)">Cerrar</button>
@if (!browsingFiles()) {
<button
mat-flat-button
type="button"
[disabled]="!b.at.path"
(click)="chooseFolder()"
>
Elegir esta carpeta
</button>
}
</div>
</div>
}
}
}
@case ('upload') {
<div
class="drop"
(dragover)="$event.preventDefault()"
(drop)="dropped(name, $event)"
[attr.data-field]="name"
>
<mat-icon>cloud_upload</mat-icon>
<p>Arrastre aquí los archivos, o</p>
<div class="drop-buttons">
<button mat-stroked-button type="button" (click)="files.click()">
Elegir archivos
</button>
<button mat-stroked-button type="button" (click)="folder.click()">
Elegir una carpeta
</button>
</div>
<input #files type="file" multiple hidden (change)="upload(name, files.files)" />
<input
#folder
type="file"
webkitdirectory
hidden
(change)="upload(name, folder.files)"
/>
@if (uploading(); as u) {
@if (u.field === name) {
<mat-progress-bar mode="determinate" [value]="u.percent" />
<span class="hint">Subiendo… {{ u.percent }} %</span>
}
}
@if (uploaded()[name]?.length) {
<p class="ok">
<mat-icon>check_circle</mat-icon> {{ uploaded()[name].length }} archivos subidos
</p>
} @else if (text(name)) {
<p class="ok"><mat-icon>check_circle</mat-icon> Archivos ya subidos</p>
}
</div>
}
@case ('oauth') {
<div class="signin">
@if (account(name); as who) {
<p class="ok"><mat-icon>check_circle</mat-icon> Conectado como {{ who }}</p>
<button mat-button type="button" (click)="signIn(name, f.provider)">
Usar otra cuenta
</button>
} @else {
<button mat-flat-button type="button" (click)="signIn(name, f.provider)">
<mat-icon>login</mat-icon>
Iniciar sesión con {{ catalog.value()?.providers?.[f.provider]?.title }}
</button>
}
@if (f.help) {
<p class="hint">{{ f.help }}</p>
}
</div>
}
@default {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="f.placeholder"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
}
</ng-template>
<div class="fields">
@for (e of fields(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
@if (more().length) {
<mat-expansion-panel class="more">
<mat-expansion-panel-header>Más opciones</mat-expansion-panel-header>
<div class="fields">
@for (e of more(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
</mat-expansion-panel>
}
<div class="test">
<button
mat-stroked-button
type="button"
(click)="test()"
[disabled]="testing() || missing().length > 0"
>
<mat-icon>network_check</mat-icon> Probar conexión
</button>
@if (testing()) {
<mat-spinner diameter="24" /> <span role="status">Conectando…</span>
} @else if (missing().length) {
<span class="hint">Falta: {{ missing().join(', ') }}</span>
}
</div>
@if (problem()) {
<p class="error" role="alert"><mat-icon>error</mat-icon> {{ problem() }}</p>
}
@if (tested(); as t) {
<div class="result" [class.bad]="!t.ok" role="status">
<p>
<mat-icon>{{ t.ok ? 'check_circle' : 'error' }}</mat-icon> {{ t.message }}
</p>
@if (t.detail) {
<details>
<summary>Lo que respondió el sistema</summary>
<pre>{{ t.detail }}</pre>
</details>
}
@if (t.tables?.length) {
<p class="hint">Elija una tabla arriba para ver sus primeras filas.</p>
}
@if (t.rows?.length) {
<p class="hint">
{{
t.rows!.length === 1
? 'La primera fila:'
: 'Las primeras ' + t.rows!.length + ' filas:'
}}
</p>
<div class="rows">
<table mat-table [dataSource]="t.rows!">
@for (c of columns(); track c) {
<ng-container [matColumnDef]="c">
<th mat-header-cell *matHeaderCellDef>{{ c }}</th>
<td mat-cell *matCellDef="let row">{{ cell(row[c]) }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
<tr mat-row *matRowDef="let row; columns: columns()"></tr>
</table>
</div>
}
</div>
}
<mat-form-field appearance="outline" class="full name">
<mat-label>Nombre de esta fuente</mat-label>
<input matInput [ngModel]="label()" (ngModelChange)="label.set($event)" />
<mat-hint>Cómo se verá en el diagrama.</mat-hint>
</mat-form-field>
</mat-dialog-content>
<mat-dialog-actions>
@if (!data.guided) {
<button mat-button type="button" (click)="back()">
<mat-icon>arrow_back</mat-icon> Otro tipo
</button>
}
<span class="spacer"></span>
<button mat-button mat-dialog-close>Cancelar</button>
<button mat-flat-button type="button" (click)="save()" [disabled]="!ready()">Guardar</button>
</mat-dialog-actions>
}
+230
View File
@@ -0,0 +1,230 @@
:host {
display: block;
}
.with-icon {
align-items: center;
display: flex;
gap: var(--space-2);
}
.hint {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.loading,
.test {
align-items: center;
display: flex;
gap: var(--space-2);
margin: var(--space-2) 0;
}
.group h3 {
font-size: 15px;
font-weight: 600;
margin: var(--space-3) 0 2px;
}
.types {
display: grid;
gap: var(--space-2);
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
}
.type {
align-items: start;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 10px;
cursor: pointer;
display: grid;
font: inherit;
gap: 2px 10px;
grid-template-columns: auto 1fr;
padding: 12px;
text-align: left;
&:hover,
&:focus-visible {
border-color: var(--color-primary);
box-shadow: 0 0 0 1px var(--color-primary);
}
mat-icon {
color: var(--color-primary);
grid-row: span 2;
}
}
.type-title {
font-weight: 600;
}
.type-text {
color: var(--color-text-secondary);
font-size: 12.5px;
line-height: 1.35;
}
.fields {
display: flex;
flex-direction: column;
gap: 12px;
}
.full,
.grow {
width: 100%;
}
.picker {
align-items: start;
display: flex;
gap: var(--space-2);
.grow {
flex: 1;
}
button {
margin-top: 10px;
}
}
.browser {
border: 1px solid var(--color-border);
border-radius: 8px;
padding: var(--space-2);
ul {
list-style: none;
margin: 0;
max-height: 220px;
overflow-y: auto;
padding: 0;
}
}
.browser-head,
.browser-actions {
align-items: center;
display: flex;
gap: var(--space-2);
}
.browser-actions {
justify-content: flex-end;
}
.entry {
align-items: center;
background: none;
border: 0;
cursor: pointer;
display: flex;
font: inherit;
gap: 6px;
padding: 4px 2px;
text-align: left;
width: 100%;
&.file {
color: var(--color-text-secondary);
cursor: default;
}
&:not(.file):hover {
color: var(--color-primary);
}
}
.drop {
align-items: center;
border: 2px dashed var(--color-border);
border-radius: 10px;
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
padding: var(--space-3);
text-align: center;
mat-progress-bar {
width: 100%;
}
}
.drop-buttons {
display: flex;
gap: var(--space-2);
}
.signin {
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
align-items: flex-start;
}
.ok,
.error,
.result p {
align-items: center;
display: flex;
gap: 6px;
margin: var(--space-1, 4px) 0;
}
.ok mat-icon,
.result mat-icon {
color: var(--color-success, #2e7d32);
}
.error,
.result.bad p {
color: var(--color-error, #b3261e);
mat-icon {
color: inherit;
}
}
.result {
border: 1px solid var(--color-border);
border-radius: 8px;
margin-top: var(--space-2);
padding: var(--space-2);
pre {
font-size: 12px;
white-space: pre-wrap;
}
}
.rows {
max-height: 260px;
overflow: auto;
td,
th {
font-size: 12px;
max-width: 260px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.more {
margin: var(--space-2) 0;
}
.name {
margin-top: var(--space-3);
}
.spacer {
flex: 1;
}
+349
View File
@@ -0,0 +1,349 @@
import { NgTemplateOutlet } from '@angular/common';
import { HttpClient, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { Component, computed, inject, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
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 { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTableModule } from '@angular/material/table';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { browse } from '../api/fn/ingest/browse';
import { oauthStart } from '../api/fn/ingest/oauth-start';
import { sourceTypes } from '../api/fn/ingest/source-types';
import { testSource } from '../api/fn/ingest/test-source';
import type { Browsed } from '../api/models/browsed';
import type { FieldSpec } from '../api/models/field-spec';
import type { Guided } from '../api/models/guided';
import type { SourceType } from '../api/models/source-type';
import type { Tested } from '../api/models/tested';
import type { Uploaded } from '../api/models/uploaded';
/** What the dialog is opened with: the source being edited, if any. */
export interface SourceDialogData {
pipeline?: string;
node?: string;
guided?: Guided | null;
label?: string;
}
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult {
guided: Guided;
label: string;
}
/** The catalog's generic icon words, as Material Symbols. */
const ICONS: Record<string, string> = {
database: 'database',
upload: 'upload_file',
folder: 'folder_open',
link: 'link',
'folder-network': 'lan',
server: 'dns',
cloud: 'cloud',
onedrive: 'cloud',
sharepoint: 'groups',
'google-drive': 'add_to_drive',
web: 'api',
fhir: 'local_hospital',
};
const MASK = '********';
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
@Component({
selector: 'app-source-dialog',
imports: [
FormsModule,
NgTemplateOutlet,
MatButtonModule,
MatDialogModule,
MatExpansionModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSlideToggleModule,
MatTableModule,
],
templateUrl: './source-dialog.html',
styleUrl: './source-dialog.scss',
})
export class SourceDialog {
private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
private readonly ref = inject(MatDialogRef<SourceDialog, SourceDialogResult>);
protected readonly data = inject<SourceDialogData>(MAT_DIALOG_DATA, { optional: true }) ?? {};
protected readonly catalog = resource({ loader: () => this.api.invoke(sourceTypes) });
protected readonly groups = computed(() => {
const c = this.catalog.value();
if (!c) return [];
return Object.entries(c.groups).map(([id, g]) => ({
id,
...g,
types: Object.entries(c.types)
.filter(([, t]) => t.group === id)
.map(([tid, t]) => ({ id: tid, ...t })),
}));
});
protected readonly typeId = signal<string | undefined>(this.data.guided?.type);
protected readonly type = computed<SourceType | undefined>(() => {
const id = this.typeId();
return id ? this.catalog.value()?.types[id] : undefined;
});
protected readonly answers = signal<Record<string, unknown>>({
...(this.data.guided?.answers ?? {}),
});
protected readonly label = signal(this.data.label ?? '');
protected readonly fields = computed(() => entries(this.type()).filter(([, f]) => !f.advanced));
protected readonly more = computed(() => entries(this.type()).filter(([, f]) => f.advanced));
protected readonly showPassword = signal<Record<string, boolean>>({});
protected readonly testing = signal(false);
/** The tables the last listing found: kept while one is picked and its rows shown. */
protected readonly tableList = signal<string[]>([]);
protected readonly tested = signal<Tested | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
protected readonly browsing = signal<{ field: string; at: Browsed } | undefined>(undefined);
protected readonly uploading = signal<{ field: string; percent: number } | undefined>(undefined);
protected readonly uploaded = signal<Record<string, string[]>>({});
protected readonly problem = signal('');
icon(name: string): string {
return ICONS[name] ?? 'input';
}
protected pick(id: string): void {
const t = this.catalog.value()!.types[id];
this.typeId.set(id);
this.answers.set(
Object.fromEntries(
Object.entries(t.fields)
.filter(([, f]) => f.default !== null && f.default !== undefined)
.map(([k, f]) => [k, f.default]),
),
);
if (!this.label()) this.label.set(t.title);
this.tested.set(undefined);
this.problem.set('');
}
protected back(): void {
this.typeId.set(undefined);
this.tested.set(undefined);
this.problem.set('');
}
protected value(name: string): unknown {
return this.answers()[name];
}
protected text(name: string): string {
const v = this.answers()[name];
return v === null || v === undefined ? '' : String(v);
}
protected set(name: string, value: unknown): void {
this.answers.update((a) => ({ ...a, [name]: value }));
if (this.type()?.fields[name]?.type === 'table') return;
this.tested.set(undefined); // another connection: test again
this.tableList.set([]);
}
protected setNumber(name: string, value: string): void {
this.set(name, value === '' ? null : Number(value));
}
protected togglePassword(name: string): void {
this.showPassword.update((s) => ({ ...s, [name]: !s[name] }));
}
protected isMasked(name: string): boolean {
return this.answers()[name] === MASK;
}
protected formats() {
return this.catalog.value()?.formats ?? [];
}
protected account(name: string): string | undefined {
const a = this.answers()[name] as { user?: string } | undefined;
return a ? (a.user ?? 'cuenta conectada') : undefined;
}
/** "Probar conexión": what the source holds, in plain words. */
protected async test(): Promise<void> {
const type = this.typeId();
if (!type) return;
this.testing.set(true);
this.problem.set('');
try {
const found = await this.api.invoke(testSource, {
limit: 20,
body: {
type,
answers: this.cleaned(),
pipeline: this.data.pipeline,
node: this.data.node,
},
});
this.tested.set(found);
if (found.tables?.length) this.tableList.set(found.tables);
} catch (e) {
this.problem.set(message(e));
} finally {
this.testing.set(false);
}
}
/** The tables a database listed, for its table field. */
protected tables(): string[] {
return this.tableList();
}
/** Server folders, under the roots the operator mounted. */
protected async openFolder(field: string, path?: string | null): Promise<void> {
try {
const at = await this.api.invoke(browse, path ? { path } : {});
this.browsing.set({ field, at });
} catch (e) {
this.problem.set(message(e));
}
}
protected chooseFolder(): void {
const b = this.browsing();
if (b?.at.path) this.set(b.field, b.at.path);
this.browsing.set(undefined);
}
protected chooseFile(path: string): void {
const b = this.browsing();
if (b) this.set(b.field, path);
this.browsing.set(undefined);
}
/** Whether the field being browsed takes a file (else a folder). */
protected readonly browsingFiles = computed(() => {
const b = this.browsing();
return !!b && this.type()?.fields[b.field]?.type === 'server_file';
});
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
* subfolders. More files can be added to the same set. */
protected upload(field: string, list: FileList | null): void {
if (!list?.length) return;
const body = new FormData();
for (const file of Array.from(list)) {
body.append('files', file, file.webkitRelativePath || file.name);
}
const folder = this.answers()[field];
if (typeof folder === 'string' && folder) body.append('folder', folder);
this.uploading.set({ field, percent: 0 });
this.problem.set('');
this.http
.post<Uploaded>(`${this.root}/ingest/uploads`, body, {
reportProgress: true,
observe: 'events',
})
.subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
this.uploading.set({ field, percent: Math.round((100 * event.loaded) / event.total) });
} else if (event.type === HttpEventType.Response && event.body) {
this.set(field, event.body.bucket_url);
this.uploaded.update((u) => ({
...u,
[field]: [...(u[field] ?? []), ...event.body!.files],
}));
}
},
error: (e) => {
this.uploading.set(undefined);
this.problem.set(message(e));
},
complete: () => this.uploading.set(undefined),
});
}
protected dropped(field: string, event: DragEvent): void {
event.preventDefault();
this.upload(field, event.dataTransfer?.files ?? null);
}
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
protected async signIn(field: string, provider: string): Promise<void> {
this.problem.set('');
let started;
try {
started = await this.api.invoke(oauthStart, { provider, origin: location.origin });
} catch (e) {
this.problem.set(message(e));
return;
}
const popup = window.open(started.url, 'isssteleon-oauth', 'width=520,height=680');
const listen = (event: MessageEvent) => {
const m = event.data as { type?: string; state?: string; account?: unknown; error?: string };
if (event.origin !== location.origin || m?.type !== 'isssteleon-oauth') return;
if (m.state !== started.state) return;
window.removeEventListener('message', listen);
if (m.error) this.problem.set(m.error);
else this.set(field, m.account);
popup?.close();
};
window.addEventListener('message', listen);
}
protected cell(v: unknown): string {
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
}
/** Answers without empty ones (a default takes their place on the server). */
private cleaned(): Record<string, unknown> {
return Object.fromEntries(
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
);
}
protected readonly missing = computed(() =>
entries(this.type())
.filter(([k, f]) => f.required && f.type !== 'table' && isEmpty(this.answers()[k]))
.filter(([, f]) => f.default === null || f.default === undefined)
.map(([, f]) => f.label),
);
protected readonly ready = computed(
() =>
!this.missing().length &&
entries(this.type())
.filter(([, f]) => f.type === 'table' && f.required)
.every(([k]) => !isEmpty(this.answers()[k])),
);
protected save(): void {
const type = this.typeId();
if (!type || !this.ready()) return;
this.ref.close({
guided: { type, answers: this.cleaned() },
label: this.label() || this.type()!.title,
});
}
}
function entries(t: SourceType | undefined): [string, FieldSpec][] {
return Object.entries(t?.fields ?? {});
}
function isEmpty(v: unknown): boolean {
return v === '' || v === null || v === undefined;
}
function message(e: unknown): string {
if (e instanceof HttpErrorResponse) {
const d = e.error?.detail;
if (typeof d === 'string') return d;
if (e.status === 0) return 'No hay conexión con la plataforma. Intente de nuevo.';
return JSON.stringify(d ?? e.message);
}
return String(e);
}