From e6abf44bef9e1cd53dd7f485b82f3fc3a040bc2f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?=
Date: Fri, 13 Nov 2026 11:52:42 -0600
Subject: [PATCH] improve ingestion system to match isssteleon setup
---
src/app/connect/api/api.types.ts | 56 ++++
src/app/connect/api/imports.api.ts | 35 ++-
.../document-review-dialog.html | 9 +
.../components/flow-editor/flow-editor.html | 9 +
.../components/flow-editor/flow-editor.ts | 9 +-
.../mapping-rules/mapping-rules.html | 238 ++++++++++++++++
.../mapping-rules/mapping-rules.scss | 113 ++++++++
.../components/mapping-rules/mapping-rules.ts | 255 ++++++++++++++++++
src/app/connect/domain/import-flow.spec.ts | 36 +++
src/app/connect/domain/import-flow.ts | 86 +++++-
src/app/reportes/reportes-page.html | 11 +
src/app/reportes/reportes.api.ts | 4 +
12 files changed, 851 insertions(+), 10 deletions(-)
create mode 100644 src/app/connect/components/mapping-rules/mapping-rules.html
create mode 100644 src/app/connect/components/mapping-rules/mapping-rules.scss
create mode 100644 src/app/connect/components/mapping-rules/mapping-rules.ts
diff --git a/src/app/connect/api/api.types.ts b/src/app/connect/api/api.types.ts
index 276340c..b729f48 100644
--- a/src/app/connect/api/api.types.ts
+++ b/src/app/connect/api/api.types.ts
@@ -85,6 +85,8 @@ export interface PreviewResponse {
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
tables?: { name: string; options: Record; kind: string }[];
source_metadata?: Record;
+ /** Columns whose sampled cells hold files (PDF, images) that can be read as documents. */
+ document_columns?: string[];
}
export interface FileOptions {
@@ -134,6 +136,56 @@ export interface ImportSourcePayload extends SourceLocator {
label?: string;
column_mapping: Record;
defaults?: Record;
+ derived?: Record;
+ documents?: DocumentColumnsConfig;
+ /** Also store, on the patient, captions the documents print that the project's catalog already knows. */
+ catalog_fallback?: boolean;
+}
+
+// Derived fields and document columns
+
+export type DerivationParamKind = 'column' | 'columns' | 'text' | 'integer' | 'mapping' | 'boolean';
+
+export interface DerivationParam {
+ name: string;
+ kind: DerivationParamKind;
+ label: string;
+ required: boolean;
+ default: unknown;
+}
+
+/** One operation a derived field may use, as `/imports/derivations` lists it. */
+export interface DerivationSpec {
+ op: string;
+ label: string;
+ description: string;
+ params: DerivationParam[];
+}
+
+export interface DerivationCatalog {
+ derivations: DerivationSpec[];
+ cases: string[];
+}
+
+/** `{op, ...params, case?}`: how one target field is computed from source columns. */
+export type DerivationRule = { op: string; case?: string } & Record;
+
+/** A grouping or naming given as a column, a list of columns or a rule. */
+export type ColumnRule = string | string[] | DerivationRule;
+
+/** Which columns of a source hold documents, and how their records are formed. */
+export interface DocumentColumnsConfig {
+ columns: string[];
+ group_by?: ColumnRule;
+ name_by?: ColumnRule;
+ file_field?: string;
+ segmentation?: string;
+ pages_per_record?: number;
+ ocr_mode?: OcrMode;
+ key_pattern?: string;
+ include_pattern?: string;
+ exclude_pattern?: string;
+ overrides?: Record>;
}
// Clinical documents
@@ -145,6 +197,10 @@ export interface DocumentSettings {
pages_per_record: number;
ocr_mode: OcrMode;
key_pattern: string;
+ /** Only documents whose text matches (regular expression, case and accents ignored). */
+ include_pattern?: string;
+ /** Documents whose text matches are left out. */
+ exclude_pattern?: string;
}
export interface ExtractedField {
diff --git a/src/app/connect/api/imports.api.ts b/src/app/connect/api/imports.api.ts
index 5afe726..14f9532 100644
--- a/src/app/connect/api/imports.api.ts
+++ b/src/app/connect/api/imports.api.ts
@@ -1,12 +1,41 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
-import { Observable } from 'rxjs';
-import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
+import { Observable, shareReplay } from 'rxjs';
+import {
+ BatchResult,
+ ConflictStrategy,
+ DerivationCatalog,
+ ImportSourcePayload,
+ PreviewResponse,
+ Row,
+ ValidationResult,
+} from './api.types';
-/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
+/**
+ * POST /imports/validate (one source, writes nothing), POST /imports/commit
+ * (a batch, one transaction), the rows a source would write
+ * (POST /imports/mapped-preview), the columns documents add to a source
+ * (POST /imports/sources/document/columns) and the operations derived
+ * fields may use (GET /imports/derivations, fetched once).
+ */
@Injectable({ providedIn: 'root' })
export class ImportsApi {
private readonly http = inject(HttpClient);
+ private catalog?: Observable;
+
+ derivations(): Observable {
+ this.catalog ??= this.http.get('/imports/derivations').pipe(shareReplay(1));
+ return this.catalog;
+ }
+
+ /** A source with document columns: its own columns plus every field and caption its documents print. */
+ documentColumns(source: ImportSourcePayload): Observable {
+ return this.http.post('/imports/sources/document/columns', { source });
+ }
+
+ mappedPreview(source: ImportSourcePayload, limit = 20): Observable<{ rows: Row[] }> {
+ return this.http.post<{ rows: Row[] }>('/imports/mapped-preview', { source, limit });
+ }
validate(source: ImportSourcePayload): Observable {
return this.http.post('/imports/validate', { source });
diff --git a/src/app/connect/components/document-review-dialog/document-review-dialog.html b/src/app/connect/components/document-review-dialog/document-review-dialog.html
index a98e60a..a9f07cf 100644
--- a/src/app/connect/components/document-review-dialog/document-review-dialog.html
+++ b/src/app/connect/components/document-review-dialog/document-review-dialog.html
@@ -33,6 +33,15 @@
/>
Expresión regular; ayuda a encontrar el expediente sin etiqueta.
+
+ Solo documentos que digan
+
+ Expresión regular; sin distinguir mayúsculas ni acentos.
+
+
+ Omitir documentos que digan
+
+
OCR
diff --git a/src/app/connect/components/flow-editor/flow-editor.html b/src/app/connect/components/flow-editor/flow-editor.html
index 4a4b976..c6472f7 100644
--- a/src/app/connect/components/flow-editor/flow-editor.html
+++ b/src/app/connect/components/flow-editor/flow-editor.html
@@ -55,6 +55,15 @@
+
+
+ functions Reglas
+ @if (f.documents() || (f.derived() | keyvalue).length) {
+ {{ (f.derived() | keyvalue).length + (f.documents() ? 1 : 0) }}
+ }
+
+
+
table_view Datos
diff --git a/src/app/connect/components/flow-editor/flow-editor.ts b/src/app/connect/components/flow-editor/flow-editor.ts
index c07fa5a..9bea92b 100644
--- a/src/app/connect/components/flow-editor/flow-editor.ts
+++ b/src/app/connect/components/flow-editor/flow-editor.ts
@@ -1,4 +1,4 @@
-import { DecimalPipe } from '@angular/common';
+import { DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, signal } from '@angular/core';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
@@ -13,12 +13,13 @@ import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
import { ColumnMapper } from '../column-mapper/column-mapper';
import { DataGrid } from '../data-grid/data-grid';
import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog';
+import { MappingRules } from '../mapping-rules/mapping-rules';
import { FlowStatusChip } from '../shared/flow-status';
import { ValidationReport } from '../validation-report/validation-report';
-const VALIDATION_TAB = 2;
+const VALIDATION_TAB = 3;
-/** Everything about the selected flow: its mapping, its data, its validation. */
+/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
@Component({
selector: 'app-flow-editor',
imports: [
@@ -26,6 +27,8 @@ const VALIDATION_TAB = 2;
DataGrid,
DecimalPipe,
FlowStatusChip,
+ KeyValuePipe,
+ MappingRules,
MatBadgeModule,
MatButtonModule,
MatIconModule,
diff --git a/src/app/connect/components/mapping-rules/mapping-rules.html b/src/app/connect/components/mapping-rules/mapping-rules.html
new file mode 100644
index 0000000..387f2ef
--- /dev/null
+++ b/src/app/connect/components/mapping-rules/mapping-rules.html
@@ -0,0 +1,238 @@
+@let f = flow();
+@let docs = documentForm();
+
+
+
+
+
+
+
+ @if (previewBusy()) {
+
+ }
+ @if (previewError(); as error) {
+ {{ error }}
+ }
+ @if (previewRows(); as rows) {
+
+
+
+
+ @for (column of previewColumns(); track column) {
+ {{ column }}
+ }
+
+
+
+ @for (row of rows; track $index) {
+
+ @for (column of previewColumns(); track column) {
+ {{ cell(row[column]) }}
+ }
+
+ } @empty {
+ La fuente no dio filas.
+ }
+
+
+
+ }
+
+
diff --git a/src/app/connect/components/mapping-rules/mapping-rules.scss b/src/app/connect/components/mapping-rules/mapping-rules.scss
new file mode 100644
index 0000000..fc1b559
--- /dev/null
+++ b/src/app/connect/components/mapping-rules/mapping-rules.scss
@@ -0,0 +1,113 @@
+:host {
+ display: block;
+}
+
+.rules {
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+ padding: 16px;
+}
+
+.rules__section {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.rules__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+
+ h3 {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0;
+ font: var(--mat-sys-title-medium);
+ }
+}
+
+.rules__badge {
+ font: var(--mat-sys-label-medium);
+ color: var(--mat-sys-primary);
+}
+
+.rules__hint {
+ margin: 0;
+ font: var(--mat-sys-body-small);
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.rules__grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+ gap: 12px 16px;
+ align-items: start;
+}
+
+.rules__wide {
+ grid-column: 1 / -1;
+}
+
+.rules__actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.rules__error {
+ margin: 0;
+ color: var(--mat-sys-error);
+ font: var(--mat-sys-body-medium);
+}
+
+.rule {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 8px;
+ border-radius: 8px;
+ background: var(--mat-sys-surface-container);
+}
+
+.rule__summary {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.rules__table-wrap {
+ overflow-x: auto;
+ max-height: 360px;
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: 8px;
+}
+
+.rules__table {
+ border-collapse: collapse;
+ font: var(--mat-sys-body-small);
+
+ th,
+ td {
+ padding: 4px 8px;
+ border-bottom: 1px solid var(--mat-sys-outline-variant);
+ text-align: left;
+ white-space: nowrap;
+ max-width: 240px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ th {
+ position: sticky;
+ top: 0;
+ background: var(--mat-sys-surface-container-high);
+ }
+}
diff --git a/src/app/connect/components/mapping-rules/mapping-rules.ts b/src/app/connect/components/mapping-rules/mapping-rules.ts
new file mode 100644
index 0000000..69def25
--- /dev/null
+++ b/src/app/connect/components/mapping-rules/mapping-rules.ts
@@ -0,0 +1,255 @@
+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 ?? '',
+ };
+ }
+}
diff --git a/src/app/connect/domain/import-flow.spec.ts b/src/app/connect/domain/import-flow.spec.ts
index da50dbd..053b40b 100644
--- a/src/app/connect/domain/import-flow.spec.ts
+++ b/src/app/connect/domain/import-flow.spec.ts
@@ -92,4 +92,40 @@ describe('ImportFlow', () => {
expect(flow.autoMap()).toBe(1);
expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
});
+
+ it('counts a derived field as covered, and mapping a column onto it drops the rule', async () => {
+ // Fails if `missingRequired` ignores `derived`, or a field could be fed by a column and a rule at once.
+ const flow = loadedFlow();
+ flow.setDerived('pac_id_hospital', { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' });
+ expect(flow.missingRequired()).toEqual([]);
+ expect((await flow.toPayload()).derived).toEqual({ pac_id_hospital: { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' } });
+
+ flow.map('Clave', 'pac_id_hospital');
+ expect(flow.derived()).toEqual({});
+ expect((await flow.toPayload()).derived).toBeUndefined();
+ });
+
+ it('sends document columns without blank settings and swaps in their columns until they are dropped', async () => {
+ // Fails if blank document settings reach the payload, or the source's own columns are lost when documents are dropped.
+ const flow = loadedFlow();
+ const own = flow.sourceColumns();
+ flow.setDocuments({ columns: ['Clave'], group_by: '', include_pattern: undefined, ocr_mode: 'auto' });
+ expect((await flow.toPayload()).documents).toEqual({ columns: ['Clave'], ocr_mode: 'auto' });
+ expect(flow.missingRequired()).toEqual([]);
+
+ flow.useDocumentPreview(preview({ columns: [...own, { name: 'Tipo de persona', inferred_type: 'string' }] }));
+ expect(flow.sourceColumns().map((c) => c.name)).toContain('Tipo de persona');
+
+ flow.setDocuments(null);
+ expect(flow.sourceColumns()).toEqual(own);
+ expect((await flow.toPayload()).documents).toBeUndefined();
+ });
+
+ it('asks for the catalog fallback only when chosen', async () => {
+ // Fails if `catalog_fallback` is sent without the user switching it on, or not sent once they do.
+ const flow = loadedFlow();
+ expect((await flow.toPayload()).catalog_fallback).toBeUndefined();
+ flow.setCatalogFallback(true);
+ expect((await flow.toPayload()).catalog_fallback).toBe(true);
+ });
});
diff --git a/src/app/connect/domain/import-flow.ts b/src/app/connect/domain/import-flow.ts
index 309e0fb..3591c84 100644
--- a/src/app/connect/domain/import-flow.ts
+++ b/src/app/connect/domain/import-flow.ts
@@ -2,6 +2,8 @@ import { Signal, computed, signal } from '@angular/core';
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
import {
CommitSourceResult,
+ DerivationRule,
+ DocumentColumnsConfig,
ImportSourcePayload,
PreviewResponse,
RowError,
@@ -47,9 +49,14 @@ export class ImportFlow {
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);
@@ -58,6 +65,12 @@ export class ImportFlow {
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();
@@ -65,18 +78,28 @@ export class ImportFlow {
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. */
+ /**
+ * 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();
- return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
+ 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 = this.mapping.bySource();
+ 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(() => {
@@ -84,7 +107,8 @@ export class ImportFlow {
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) {
+ 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();
@@ -161,6 +185,9 @@ export class ImportFlow {
map(source: string, field: string): void {
this.mapping.assign(source, field);
+ if (this._derived()[field]) {
+ this._derived.update(({ [field]: _, ...rest }) => rest);
+ }
this.touch();
}
@@ -188,9 +215,51 @@ export class ImportFlow {
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 };
@@ -215,6 +284,9 @@ export class ImportFlow {
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 } : {}),
};
}
@@ -256,3 +328,9 @@ export class ImportFlow {
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;
+}
diff --git a/src/app/reportes/reportes-page.html b/src/app/reportes/reportes-page.html
index 43f329f..7e432a8 100644
--- a/src/app/reportes/reportes-page.html
+++ b/src/app/reportes/reportes-page.html
@@ -81,6 +81,17 @@
· requeridos sin mapear: {{ source.mapeo.requeridos_sin_mapear.join(', ') }}
}
+ @if ((source.etiquetas_sin_usar | keyvalue)?.length || source.etiquetas_sin_usar_poco_frecuentes) {
+
+ Etiquetas que los documentos traen y no se usaron (puede asignarlas en la siguiente carga):
+ @for (caption of source.etiquetas_sin_usar | keyvalue; track caption.key) {
+ {{ caption.key }} ×{{ caption.value }}
+ }
+ @if (source.etiquetas_sin_usar_poco_frecuentes) {
+ otras {{ source.etiquetas_sin_usar_poco_frecuentes }} poco frecuentes
+ }
+
+ }
}
diff --git a/src/app/reportes/reportes.api.ts b/src/app/reportes/reportes.api.ts
index c9ccaf7..5e84995 100644
--- a/src/app/reportes/reportes.api.ts
+++ b/src/app/reportes/reportes.api.ts
@@ -20,6 +20,10 @@ export interface SourceReport {
mapeo: { requeridos_sin_mapear: string[]; campos_sin_mapear: string[]; columnas_origen: string[] };
filas: Record;
campos: Record;
+ /** Captions the source's documents print that the import didn't use, with how many records print each. */
+ etiquetas_sin_usar?: Record;
+ /** How many more such captions too few records print to be listed. */
+ etiquetas_sin_usar_poco_frecuentes?: number;
}
/** One line of the aggregate import log. */