import { Signal, computed, signal } from '@angular/core'; import { Observable, catchError, finalize, map, of, tap } from 'rxjs'; import { CommitSourceResult, ImportSourcePayload, PreviewResponse, RowError, SourceColumn, TargetField, TargetMeta, ValidationResult, apiErrorMessage, } from '../api/api.types'; import { SourceGateway } from '../api/source-gateway'; import { SourceTable } from './data-source'; import { MappingSet } from './mapping-set'; export type FlowStatus = 'loading' | 'error' | 'incomplete' | 'ready' | 'validating' | 'valid' | 'invalid' | 'loaded'; export interface FieldQuality { field: string; total: number; errors: number; /** 0..1 */ errorRate: number; } /** The part of the imports API that `validate`/`commit` use, kept narrow so tests can fake it. */ export interface Validator { validate(source: ImportSourcePayload): Observable; } let sequence = 0; /** * One source table flowing into one destination entity: the unit the user * composes the database from. A workspace can feed several tables into one * entity or one file into several entities. * * Owns its mapping (`MappingSet`), per-field default values, the latest * preview and validation, and derives its own status. Any change to what * would be sent clears the previous validation, so a stale result is not * shown. */ export class ImportFlow { readonly id = `flow-${++sequence}`; readonly mapping = new MappingSet(); private readonly _preview = signal(null); private readonly _loading = signal(false); private readonly _error = signal(null); private readonly _defaults = signal>({}); private readonly _validation = signal(null); private readonly _validating = signal(false); private readonly _result = signal(null); readonly preview: Signal = this._preview.asReadonly(); readonly loading: Signal = this._loading.asReadonly(); readonly error: Signal = this._error.asReadonly(); readonly defaults: Signal> = this._defaults.asReadonly(); readonly validation: Signal = this._validation.asReadonly(); readonly validating: Signal = this._validating.asReadonly(); readonly result: Signal = this._result.asReadonly(); readonly sourceColumns = computed(() => this._preview()?.columns ?? []); readonly totalRows = computed(() => this._preview()?.total_rows ?? null); /** A field is covered when a column feeds it or it has a default value. */ readonly missingRequired = computed(() => { const mapped = this.mapping.byField(); const defaults = this._defaults(); return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim()); }); readonly unmappedColumns = computed(() => { const used = this.mapping.bySource(); return this.sourceColumns().filter((column) => !used.has(column.name)); }); readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length); readonly status = computed(() => { if (this._loading()) return 'loading'; if (this._error() || !this._preview()) return 'error'; if (this._result()) return 'loaded'; if (this._validating()) return 'validating'; if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) { return 'incomplete'; } const validation = this._validation(); if (!validation) return 'ready'; return validation.error_count > 0 ? 'invalid' : 'valid'; }); /** Row errors indexed by `":"` for the data grid's cell highlighting. */ readonly errorsByCell = computed(() => { const index = new Map(); for (const error of this._validation()?.errors ?? []) { const key = `${error.row_index}:${error.field}`; index.set(key, [...(index.get(key) ?? []), error]); } return index; }); /** Per destination field: how many rows failed on it (Power Query-style column quality). */ readonly quality = computed(() => { const validation = this._validation(); const qualities = new Map(); if (!validation) return qualities; const failingRows = new Map>(); for (const error of validation.errors) { if (!failingRows.has(error.field)) failingRows.set(error.field, new Set()); failingRows.get(error.field)!.add(error.row_index); } for (const field of this.target.fields) { const errors = failingRows.get(field.name)?.size ?? 0; const total = validation.total_rows; qualities.set(field.name, { field: field.name, total, errors, errorRate: total ? errors / total : 0 }); } return qualities; }); constructor( readonly table: SourceTable, readonly target: TargetMeta, ) {} get label(): string { return this.table.label; } /** Complete enough to validate. */ get canSubmit(): boolean { return !['loading', 'error', 'incomplete'].includes(this.status()); } /** Complete and not yet written; editing a loaded flow clears its result and makes it pending again. */ get pendingLoad(): boolean { return this.canSubmit && this.status() !== 'loaded'; } /** Fetches the preview against this flow's target and seeds the mapping from the server's suggestions. */ load(gateway: SourceGateway): Observable { this._loading.set(true); this._error.set(null); return this.table.preview(gateway, this.target.key).pipe( tap((preview) => { this._preview.set(preview); this.mapping.seed(preview.suggested_mapping); }), map(() => undefined), catchError((error) => { this._error.set(apiErrorMessage(error, 'No se pudo leer la fuente.')); return of(undefined); }), finalize(() => this._loading.set(false)), ); } // Every mapping edit invalidates the last validation. map(source: string, field: string): void { this.mapping.assign(source, field); this.touch(); } unmapField(field: string): void { this.mapping.releaseField(field); this.touch(); } unmapSource(source: string): void { this.mapping.releaseSource(source); this.touch(); } confirmSuggestion(field: string): void { this.mapping.confirm(field); } /** Re-applies the server's suggestions to whatever is still unmapped. Returns how many were added. */ autoMap(): number { const added = this.mapping.fillFrom(this._preview()?.suggested_mapping ?? []); if (added) this.touch(); return added; } clearMapping(): void { this.mapping.clear(); this._defaults.set({}); this.touch(); } setDefault(field: string, value: string | null): void { this._defaults.update((defaults) => { const next = { ...defaults }; if (value === null || value === '') delete next[field]; else next[field] = value; return next; }); this.touch(); } activeDefaults(): Record { return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== '')); } async toPayload(): Promise { const locator = await this.table.locator(this.target.key); const defaults = this.activeDefaults(); return { ...locator, target: this.target.key, label: this.label, column_mapping: this.mapping.toRecord(), ...(Object.keys(defaults).length ? { defaults } : {}), }; } validate(validator: Validator): Promise { this._validating.set(true); return this.toPayload() .then( (payload) => new Promise((resolve) => { validator.validate(payload).subscribe({ next: (result) => { this._validation.set(result); this._error.set(null); resolve(); }, error: (error) => { this._error.set(apiErrorMessage(error, 'No se pudo validar la fuente.')); resolve(); }, }); }), ) .finally(() => this._validating.set(false)); } recordResult(result: CommitSourceResult): void { this._result.set(result); // The commit re-validated every row server-side; its errors are the freshest view. this._validation.set({ total_rows: result.total, valid_count: result.created + result.updated, error_count: result.rejected, errors: result.errors, }); } private touch(): void { this._validation.set(null); this._result.set(null); } }