import { Signal, computed, signal } from '@angular/core'; import { Observable, catchError, finalize, map, of, tap } from 'rxjs'; import { CommitSourceResult, DerivationRule, DocumentColumnsConfig, 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); /** The source's own preview, kept while document columns replace it. */ private _sourcePreview: PreviewResponse | null = null; private readonly _loading = signal(false); private readonly _error = signal(null); private readonly _defaults = signal>({}); private readonly _derived = signal>({}); private readonly _documents = signal(null); private readonly _catalogFallback = signal(false); 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(); /** Target fields computed from source columns (`derived`), by field. */ readonly derived: Signal> = this._derived.asReadonly(); /** Source columns read as documents, or `null` when none are. */ readonly documents: Signal = this._documents.asReadonly(); /** Whether captions the catalog knows are stored too (`catalog_fallback`); off unless chosen. */ readonly catalogFallback: Signal = this._catalogFallback.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, a rule computes it or it has * a default value. With document columns, extraction may fill any field, * so nothing is reported missing before validation says so. */ readonly missingRequired = computed(() => { if (this._documents()) return []; const mapped = this.mapping.byField(); const defaults = this._defaults(); const derived = this._derived(); return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !derived[f.name] && !defaults[f.name]?.trim()); }); /** Columns no mapping, rule or document setting reads. */ readonly unmappedColumns = computed(() => { const used = new Set([...this.mapping.bySource().keys(), ...this._documents()?.columns ?? []]); return this.sourceColumns().filter((column) => !used.has(column.name)); }); /** Columns whose sampled cells hold documents. */ readonly documentColumns = computed(() => this._preview()?.document_columns ?? []); 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'; const assigned = this.mapping.size() + Object.keys(this.activeDefaults()).length + Object.keys(this._derived()).length; if (this.missingRequired().length > 0 || (assigned === 0 && !this._documents())) { 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); if (this._derived()[field]) { this._derived.update(({ [field]: _, ...rest }) => rest); } 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._derived.set({}); this._documents.set(null); this.touch(); } /** Computes `field` with `rule`, replacing any column mapped to it; `null` removes the rule. */ setDerived(field: string, rule: DerivationRule | null): void { if (rule) this.mapping.releaseField(field); this._derived.update((derived) => { const next = { ...derived }; if (rule) next[field] = rule; else delete next[field]; return next; }); this.touch(); } setCatalogFallback(on: boolean): void { this._catalogFallback.set(on); this.touch(); } /** Reads some of the source's columns as documents; `null` stops reading them. */ setDocuments(config: DocumentColumnsConfig | null): void { this._documents.set(config && config.columns.length ? config : null); if (!this._documents()) this.useDocumentPreview(null); this.touch(); } /** * Shows, as the source's columns, its own plus every field and caption * its documents print, so they can be mapped and used in rules; `null` * goes back to the source's own columns. */ useDocumentPreview(preview: PreviewResponse | null): void { if (preview) { this._sourcePreview ??= this._preview(); this._preview.set({ ...preview, document_columns: this._sourcePreview?.document_columns ?? [] }); this.mapping.fillFrom(preview.suggested_mapping); } else if (this._sourcePreview) { this._preview.set(this._sourcePreview); this._sourcePreview = null; } } 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 } : {}), ...(Object.keys(this._derived()).length ? { derived: this._derived() } : {}), ...(this._documents() ? { documents: withoutBlanks(this._documents()!) } : {}), ...(this._catalogFallback() ? { catalog_fallback: true } : {}), }; } 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); } } function withoutBlanks(config: DocumentColumnsConfig): DocumentColumnsConfig { return Object.fromEntries( Object.entries(config).filter(([, value]) => value !== undefined && value !== null && value !== ''), ) as unknown as DocumentColumnsConfig; }