import { Component, computed, inject, signal } from '@angular/core'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; 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 { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatRippleModule } from '@angular/material/core'; import { MatTooltipModule } from '@angular/material/tooltip'; import { toSignal } from '@angular/core/rxjs-interop'; import { catchError, of } from 'rxjs'; import { ConnectorInfo, SqlConnectionRef, SqlEngineInfo, apiErrorMessage } from '../../api/api.types'; import { ConnectorsApi } from '../../api/connectors.api'; import { SourceGateway } from '../../api/source-gateway'; import { connectionsFor } from '../../domain/connection-registry'; import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog'; import { DataConnection } from '../../domain/data-source'; import { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections'; import { SqlConnection } from '../../domain/sql-source'; import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url'; import { FileDropzone } from '../file-dropzone/file-dropzone'; type View = 'catalog' | 'files' | 'database'; /** * "Obtener datos": pick a connector from the gallery (as reported by the * server), then drop files or fill a database connection form. Closes * with the new, not yet loaded, `DataConnection`s. */ @Component({ selector: 'app-connector-gallery-dialog', imports: [ FileDropzone, MatButtonModule, MatCheckboxModule, MatDialogModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule, MatProgressBarModule, MatRippleModule, MatTooltipModule, ReactiveFormsModule, ], templateUrl: './connector-gallery-dialog.html', styleUrl: './connector-gallery-dialog.scss', }) export class ConnectorGalleryDialog { private readonly dialogRef = inject>(MatDialogRef); private readonly gateway = inject(SourceGateway); private readonly formBuilder = inject(FormBuilder); readonly categories = GALLERY_CATEGORIES; readonly category = signal('all'); readonly search = signal(''); readonly view = signal('catalog'); readonly entry = signal(null); readonly catalogError = signal(null); private readonly connectors = toSignal( inject(ConnectorsApi) .list() .pipe( catchError((error) => { this.catalogError.set(apiErrorMessage(error, 'No se pudo consultar los conectores del servidor.')); return of([] as ConnectorInfo[]); }), ), { initialValue: [] as ConnectorInfo[] }, ); private readonly entries = computed(() => galleryEntries(this.connectors())); readonly visibleEntries = computed(() => { const term = this.search().trim().toLowerCase(); return this.entries().filter( (entry) => (this.category() === 'all' || entry.category === this.category()) && (!term || entry.name.toLowerCase().includes(term) || entry.description.toLowerCase().includes(term)), ); }); readonly visibleCategories = computed(() => this.categories.filter((c) => c.id === 'all' || this.entries().some((entry) => entry.category === c.id)), ); readonly files = signal([]); readonly serverForm = this.formBuilder.nonNullable.group({ host: ['', Validators.required], port: [null as number | null], database: ['', Validators.required], user: [''], password: [''], }); readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] }); readonly testing = signal(false); readonly testResult = signal<{ ok: boolean; message: string } | null>(null); readonly remember = signal(false); readonly engine = computed(() => this.entry()?.engine ?? null); readonly serverEngine = computed(() => { const engine = this.engine(); return engine && engine !== 'url' ? engine : null; }); private readonly savedConnectionsAll = signal(listSavedSqlConnections()); /** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */ readonly savedConnections = computed(() => { const engineId = this.serverEngine()?.id; return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : []; }); applySaved(saved: SavedSqlConnection): void { this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user }); this.testResult.set(null); } forgetSaved(saved: SavedSqlConnection, event: Event): void { event.stopPropagation(); removeSqlConnection(saved.id); this.savedConnectionsAll.set(listSavedSqlConnections()); } pick(entry: GalleryEntry): void { if (!entry.available) return; this.entry.set(entry); this.testResult.set(null); this.remember.set(false); this.view.set(entry.engine ? 'database' : 'files'); } back(): void { this.view.set('catalog'); this.files.set([]); } onSearch(event: Event): void { this.search.set((event.target as HTMLInputElement).value); } testConnection(): void { const ref = this.connectionRef(); if (!ref) return; this.testing.set(true); this.testResult.set(null); this.gateway.sql.testConnection(ref).subscribe({ next: (response) => { this.testing.set(false); this.testResult.set({ ok: true, message: `Conexión correcta (${response.dialect}).` }); }, error: (error) => { this.testing.set(false); this.testResult.set({ ok: false, message: apiErrorMessage(error, 'No se pudo conectar.') }); }, }); } connectFiles(): void { const entry = this.entry(); if (entry) this.dialogRef.close(connectionsFor(entry.connector.kind, this.files())); } connectDatabase(): void { const ref = this.connectionRef(); if (!ref) return; if (this.remember() && 'server' in ref) { const { password: _password, ...shape } = ref.server; saveSqlConnection({ label: this.connectionLabel(), ...shape }); } this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]); } get databaseFormInvalid(): boolean { return this.engine() === 'url' ? this.urlForm.invalid : this.serverForm.invalid; } private connectionRef(): SqlConnectionRef | null { const engine = this.engine(); if (!engine) return null; if (engine === 'url') { this.urlForm.markAllAsTouched(); return this.urlForm.valid ? { connection_string: this.urlForm.getRawValue().url.trim() } : null; } this.serverForm.markAllAsTouched(); if (this.serverForm.invalid) return null; return { server: { engine: engine.id, ...this.serverForm.getRawValue() } }; } private connectionLabel(): string { const engine = this.engine(); if (engine === 'url') return describeSqlUrl(this.urlForm.getRawValue().url); return describeSqlServer({ engine: engine as SqlEngineInfo, ...this.serverForm.getRawValue() }); } }