import { Component, computed, effect, inject, input, signal } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCheckboxModule } from '@angular/material/checkbox'; 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 { MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; import { firstValueFrom } from 'rxjs'; import { DerivationParam, DerivationRule, DerivationSpec, DocumentColumnsConfig, OcrMode, Row, apiErrorMessage, } from '../../api/api.types'; import { ImportsApi } from '../../api/imports.api'; import { ImportFlow } from '../../domain/import-flow'; interface DocumentForm { columns: string[]; group_by: string; file_field: string; ocr_mode: OcrMode; include_pattern: string; exclude_pattern: string; } /** * What a plain column-to-field mapping can't express, for any kind of * source: columns whose cells hold documents (read for every field and * caption they print, which then become columns of their own), target * fields computed from several columns, and a look at the rows as they * would be written. * * The operations and their parameters come from the server * (`/imports/derivations`), so a new operation needs no change here. */ @Component({ selector: 'app-mapping-rules', imports: [ FormsModule, MatButtonModule, MatCheckboxModule, MatFormFieldModule, MatIconModule, MatInputModule, MatProgressBarModule, MatSelectModule, MatTooltipModule, ], templateUrl: './mapping-rules.html', styleUrl: './mapping-rules.scss', }) export class MappingRules { readonly flow = input.required(); private readonly api = inject(ImportsApi); readonly catalog = toSignal(this.api.derivations()); readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name)); readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob'))); readonly documentForm = signal(this.emptyDocumentForm()); readonly documentsBusy = signal(false); readonly documentsError = signal(null); readonly ruleField = signal(''); readonly ruleOp = signal(''); readonly ruleParams = signal>({}); readonly ruleCase = signal(''); readonly ruleError = signal(null); readonly previewRows = signal(null); readonly previewBusy = signal(false); readonly previewError = signal(null); readonly selectedSpec = computed(() => this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()), ); readonly rules = computed(() => Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })), ); readonly previewColumns = computed(() => { const rows = this.previewRows() ?? []; return [...new Set(rows.flatMap((row) => Object.keys(row)))]; }); constructor() { // The form follows the flow: what it has configured, or the columns the server flagged. effect(() => { const flow = this.flow(); const current = flow.documents(); this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() }); }); } // -- documents ----------------------------------------------------------- patchDocuments(patch: Partial): void { this.documentForm.update((form) => ({ ...form, ...patch })); } async applyDocuments(): Promise { const form = this.documentForm(); const flow = this.flow(); if (!form.columns.length) { this.clearDocuments(); return; } flow.setDocuments({ columns: form.columns, group_by: form.group_by || undefined, file_field: form.file_field || undefined, ocr_mode: form.ocr_mode, include_pattern: form.include_pattern.trim() || undefined, exclude_pattern: form.exclude_pattern.trim() || undefined, }); this.documentsBusy.set(true); this.documentsError.set(null); try { flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload()))); } catch (error) { this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.')); } finally { this.documentsBusy.set(false); } } clearDocuments(): void { this.flow().setDocuments(null); this.documentsError.set(null); } // -- derived fields ------------------------------------------------------ chooseOp(op: string): void { this.ruleOp.set(op); const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op); this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)]))); this.ruleError.set(null); } setParam(name: string, value: unknown): void { this.ruleParams.update((params) => ({ ...params, [name]: value })); } /** `clave = valor` lines, the text form of a `mapping` parameter. */ mappingText(name: string): string { const value = this.ruleParams()[name]; return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : ''; } setMappingText(name: string, text: string): void { const entries = text .split('\n') .map((line) => line.split('=')) .filter((parts) => parts.length >= 2 && parts[0].trim()) .map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]); this.setParam(name, Object.fromEntries(entries)); } addRule(): void { const spec = this.selectedSpec(); const field = this.ruleField(); if (!spec || !field) return; const params = this.ruleParams(); const missing = spec.params.filter((param) => param.required && this.blank(params[param.name])); if (missing.length) { this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`); return; } const rule: DerivationRule = { op: spec.op }; for (const param of spec.params) { const value = params[param.name]; if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value; } if (this.ruleCase()) rule.case = this.ruleCase(); this.flow().setDerived(field, rule); this.ruleField.set(''); this.ruleOp.set(''); this.ruleParams.set({}); this.ruleCase.set(''); this.ruleError.set(null); } removeRule(field: string): void { this.flow().setDerived(field, null); } // -- preview --------------------------------------------------------------- async preview(): Promise { this.previewBusy.set(true); this.previewError.set(null); try { const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10)); this.previewRows.set(rows); } catch (error) { this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.')); } finally { this.previewBusy.set(false); } } cell(value: unknown): string { if (value === null || value === undefined) return ''; return typeof value === 'object' ? JSON.stringify(value) : String(value); } private describe(rule: DerivationRule): string { const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op); const parts = (spec?.params ?? []) .filter((param) => !this.blank(rule[param.name])) .map((param) => `${param.label}: ${this.cell(rule[param.name])}`); return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' ยท '); } private initial(param: DerivationParam): unknown { if (param.kind === 'columns') return []; if (param.kind === 'mapping') return {}; return param.default ?? (param.kind === 'boolean' ? false : ''); } private blank(value: unknown): boolean { return ( value === null || value === undefined || (typeof value === 'string' && !value.trim()) || (Array.isArray(value) && !value.length) || (typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length) ); } private emptyDocumentForm(): DocumentForm { return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' }; } private formFrom(config: DocumentColumnsConfig): DocumentForm { return { columns: config.columns, group_by: typeof config.group_by === 'string' ? config.group_by : '', file_field: config.file_field ?? '', ocr_mode: config.ocr_mode ?? 'auto', include_pattern: config.include_pattern ?? '', exclude_pattern: config.exclude_pattern ?? '', }; } }