Files
WebApp/src/app/connect/domain/import-flow.ts
T

265 lines
8.9 KiB
TypeScript

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<ValidationResult>;
}
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<PreviewResponse | null>(null);
private readonly _loading = signal(false);
private readonly _error = signal<string | null>(null);
private readonly _defaults = signal<Record<string, string>>({});
private readonly _validation = signal<ValidationResult | null>(null);
private readonly _validating = signal(false);
private readonly _result = signal<CommitSourceResult | null>(null);
readonly preview: Signal<PreviewResponse | null> = this._preview.asReadonly();
readonly loading: Signal<boolean> = this._loading.asReadonly();
readonly error: Signal<string | null> = this._error.asReadonly();
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
readonly validating: Signal<boolean> = this._validating.asReadonly();
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
readonly sourceColumns = computed<SourceColumn[]>(() => 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<TargetField[]>(() => {
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<FlowStatus>(() => {
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 `"<row>:<field>"` for the data grid's cell highlighting. */
readonly errorsByCell = computed(() => {
const index = new Map<string, RowError[]>();
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<string, FieldQuality>();
if (!validation) return qualities;
const failingRows = new Map<string, Set<number>>();
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());
}
/**
* Belongs in the next load: complete and not already written. A loaded
* flow stays out of later batches (re-sending it would duplicate rows in
* tables without a natural key) until it's edited, since any edit clears
* its result.
*/
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<void> {
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)),
);
}
// -- mapping edits (every one 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<string, string> {
return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== ''));
}
// -- backend round trips ---------------------------------------------------
async toPayload(): Promise<ImportSourcePayload> {
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<void> {
this._validating.set(true);
return this.toPayload()
.then(
(payload) =>
new Promise<void>((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);
}
}