diff --git a/Dockerfile b/Dockerfile
index aebd4d1..f0d4b22 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,10 +1,15 @@
-FROM node:22-slim
-
+# Production image: build the Angular app, serve the static bundle with
+# nginx, and reverse-proxy the API paths to the `webapi` compose service —
+# the same routing `proxy.conf.json` gives `ng serve` in development, so the
+# app's relative `/imports`, `/data`, ... calls work unchanged.
+FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json* ./
-RUN npm install
-
+RUN npm ci
COPY . .
+RUN npx ng build --configuration production
-EXPOSE 4200
-CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"]
+FROM nginx:1.27-alpine
+COPY nginx.conf /etc/nginx/conf.d/default.conf
+COPY --from=build /app/dist/WebApp/browser /usr/share/nginx/html
+EXPOSE 80
diff --git a/angular.json b/angular.json
index d3f5a4a..52b923c 100644
--- a/angular.json
+++ b/angular.json
@@ -44,8 +44,8 @@
},
{
"type": "anyComponentStyle",
- "maximumWarning": "4kB",
- "maximumError": "8kB"
+ "maximumWarning": "6kB",
+ "maximumError": "10kB"
}
],
"outputHashing": "all"
@@ -60,6 +60,9 @@
},
"serve": {
"builder": "@angular/build:dev-server",
+ "options": {
+ "proxyConfig": "proxy.conf.json"
+ },
"configurations": {
"production": {
"buildTarget": "WebApp:build:production"
diff --git a/nginx.conf b/nginx.conf
new file mode 100644
index 0000000..7f5d0fc
--- /dev/null
+++ b/nginx.conf
@@ -0,0 +1,23 @@
+server {
+ listen 80;
+ server_name _;
+ root /usr/share/nginx/html;
+
+ # Files travel inside the import requests (multipart or base64 JSON):
+ # keep this above WebApi's WEBAPI_MAX_UPLOAD_MB (200 MB default) plus
+ # the ~33% base64 overhead.
+ client_max_body_size 270m;
+
+ location ~ ^/(api|imports|data|cacu|cama|tea|governance|health)(/|$) {
+ proxy_pass http://webapi:5000;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ # OCR over a stack of scanned pages takes a while.
+ proxy_read_timeout 600s;
+ }
+
+ location / {
+ try_files $uri $uri/ /index.html;
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index 0f2ebd5..a70b188 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,6 +16,7 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
+ "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
@@ -6481,6 +6482,12 @@
"node": ">=16.20.0"
}
},
+ "node_modules/plotly.js-cartesian-dist-min": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz",
+ "integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
+ "license": "MIT"
+ },
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
diff --git a/package.json b/package.json
index f86bd9c..62be094 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
+ "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
diff --git a/proxy.conf.json b/proxy.conf.json
new file mode 100644
index 0000000..acc8f30
--- /dev/null
+++ b/proxy.conf.json
@@ -0,0 +1,10 @@
+{
+ "/api": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/imports": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/data": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/health": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/cacu": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/cama": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/tea": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
+ "/governance": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }
+}
diff --git a/src/_theme-colors.scss b/src/_theme-colors.scss
new file mode 100644
index 0000000..36ac7b0
--- /dev/null
+++ b/src/_theme-colors.scss
@@ -0,0 +1,137 @@
+// This file was generated by running 'ng generate @angular/material:theme-color'.
+// Proceed with caution if making changes to this file.
+
+@use 'sass:map';
+@use '@angular/material' as mat;
+
+// Note: Color palettes are generated from primary: #a8c243, tertiary: #5f9ea0, neutral: #5c5f66
+$_palettes: (
+ primary: (
+ 0: #000000,
+ 10: #171e00,
+ 20: #2a3400,
+ 25: #344000,
+ 30: #3e4c00,
+ 35: #495900,
+ 40: #546500,
+ 50: #6a8000,
+ 60: #829a1c,
+ 70: #9cb638,
+ 80: #b7d251,
+ 90: #d3ef6a,
+ 95: #e1fd77,
+ 98: #f5ffc6,
+ 99: #faffe3,
+ 100: #ffffff,
+ ),
+ secondary: (
+ 0: #000000,
+ 10: #171e00,
+ 20: #2b3407,
+ 25: #363f12,
+ 30: #414b1c,
+ 35: #4d5727,
+ 40: #596332,
+ 50: #717c48,
+ 60: #8b965f,
+ 70: #a5b177,
+ 80: #c1cc90,
+ 90: #dde9aa,
+ 95: #ebf7b7,
+ 98: #f5ffc6,
+ 99: #faffe3,
+ 100: #ffffff,
+ ),
+ tertiary: (
+ 0: #000000,
+ 10: #002021,
+ 20: #003738,
+ 25: #004345,
+ 30: #004f51,
+ 35: #145b5e,
+ 40: #25686a,
+ 50: #418183,
+ 60: #5c9b9d,
+ 70: #77b6b8,
+ 80: #92d2d3,
+ 90: #aeeef0,
+ 95: #bcfcfe,
+ 98: #e3ffff,
+ 99: #f1ffff,
+ 100: #ffffff,
+ ),
+ neutral: (
+ 0: #000000,
+ 10: #181c22,
+ 20: #2d3037,
+ 25: #383b42,
+ 30: #44474d,
+ 35: #4f5259,
+ 40: #5b5e65,
+ 50: #74777e,
+ 60: #8e9198,
+ 70: #a9abb3,
+ 80: #c4c6ce,
+ 90: #e0e2ea,
+ 95: #eff0f9,
+ 98: #f9f9ff,
+ 99: #fdfcff,
+ 100: #ffffff,
+ 4: #0b0e14,
+ 6: #101419,
+ 12: #1c2026,
+ 17: #272a30,
+ 22: #32353b,
+ 24: #363940,
+ 87: #d8dae2,
+ 92: #e6e8f0,
+ 94: #ecedf6,
+ 96: #f1f3fc,
+ ),
+ neutral-variant: (
+ 0: #000000,
+ 10: #1a1d0f,
+ 20: #2f3222,
+ 25: #3a3d2d,
+ 30: #454837,
+ 35: #515442,
+ 40: #5d604e,
+ 50: #767965,
+ 60: #90927e,
+ 70: #aaad98,
+ 80: #c6c8b2,
+ 90: #e2e4cd,
+ 95: #f1f3db,
+ 98: #f9fbe3,
+ 99: #fcfdf1,
+ 100: #ffffff,
+ ),
+ error: (
+ 0: #000000,
+ 10: #410002,
+ 20: #690005,
+ 25: #7e0007,
+ 30: #93000a,
+ 35: #a80710,
+ 40: #ba1a1a,
+ 50: #de3730,
+ 60: #ff5449,
+ 70: #ff897d,
+ 80: #ffb4ab,
+ 90: #ffdad6,
+ 95: #ffedea,
+ 98: #fff8f7,
+ 99: #fffbff,
+ 100: #ffffff,
+ ),
+);
+
+$_rest: (
+ secondary: map.get($_palettes, secondary),
+ neutral: map.get($_palettes, neutral),
+ neutral-variant: map.get($_palettes, neutral-variant),
+ error: map.get($_palettes, error),
+);
+
+$primary-palette: map.merge(map.get($_palettes, primary), $_rest);
+$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);
diff --git a/src/app/app.config.ts b/src/app/app.config.ts
index e60fc79..d9c42bd 100644
--- a/src/app/app.config.ts
+++ b/src/app/app.config.ts
@@ -1,10 +1,12 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
+import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
- provideRouter(routes)
+ provideRouter(routes),
+ provideHttpClient(),
]
};
diff --git a/src/app/app.html b/src/app/app.html
index d52a576..b41af08 100644
--- a/src/app/app.html
+++ b/src/app/app.html
@@ -1,10 +1,15 @@
-
+
@@ -12,9 +17,11 @@
-
+ @if (!workspace()) {
+
+ }
diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts
index 9742bb2..943d41c 100644
--- a/src/app/app.routes.ts
+++ b/src/app/app.routes.ts
@@ -1,4 +1,31 @@
import { Routes } from '@angular/router';
import { Home } from './home';
+import { DOMINIOS } from './features/indicadores/indicadores.models';
-export const routes: Routes = [{ path: '', component: Home }];
+const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
+
+export const routes: Routes = [
+ { path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
+ {
+ path: 'conectar',
+ title: 'Conectar datos | ISSSTELEON',
+ // Lazy: the workspace (and the ~15 Material modules it uses) only
+ // downloads when someone actually opens it.
+ loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
+ data: { workspace: true, breadcrumb: 'Conectar datos' },
+ },
+ {
+ path: 'gobernanza',
+ title: 'Gobernanza de modelos | ISSSTELEON',
+ loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
+ data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
+ },
+ { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
+ ...DOMINIOS.map(dominio => ({
+ path: `indicadores/${dominio}`,
+ title: 'Indicadores | ISSSTELEON',
+ data: { workspace: true, breadcrumb: 'Indicadores', dominio },
+ loadComponent: loadIndicadores,
+ })),
+ { path: '**', redirectTo: '' },
+];
diff --git a/src/app/app.scss b/src/app/app.scss
index 4462be8..234d0f1 100644
--- a/src/app/app.scss
+++ b/src/app/app.scss
@@ -14,7 +14,7 @@
align-items: center;
display: flex;
justify-content: space-between;
- min-height: 88px;
+ min-height: var(--site-header-height);
padding: 0 clamp(32px, 3.2vw, 48px);
}
@@ -29,7 +29,20 @@
width: clamp(180px, 16vw, 200px);
}
+.site-header__nav {
+ align-items: center;
+ display: flex;
+ gap: 6px;
+}
+
+.site-header__crumb {
+ color: var(--color-primary);
+ font-size: 15px;
+ font-weight: 600;
+}
+
.site-header__section {
+ text-decoration: none;
color: var(--color-text);
font-size: 15px;
font-weight: 500;
@@ -39,6 +52,12 @@
.app-main {
display: flex;
flex: 1;
+ min-height: 0;
+}
+
+.app-shell--workspace {
+ height: 100dvh;
+ overflow: hidden;
}
.site-footer {
@@ -62,7 +81,7 @@
@media (max-width: 600px) {
.site-header__content {
- min-height: 70px;
+ min-height: var(--site-header-height);
padding: 0 20px;
}
diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts
index 6c32756..f849d1f 100644
--- a/src/app/app.spec.ts
+++ b/src/app/app.spec.ts
@@ -1,6 +1,7 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
-import { MatDialog } from '@angular/material/dialog';
+import { provideHttpClient } from '@angular/common/http';
+import { provideHttpClientTesting } from '@angular/common/http/testing';
import { App } from './app';
import { routes } from './app.routes';
@@ -8,175 +9,38 @@ describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
- providers: [provideRouter(routes)],
+ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
}).compileComponents();
});
- it('should create the app', () => {
+ async function render(url: string) {
const fixture = TestBed.createComponent(App);
- const app = fixture.componentInstance;
- expect(app).toBeTruthy();
+ fixture.detectChanges();
+ await TestBed.inject(Router).navigateByUrl(url);
+ await fixture.whenStable();
+ fixture.detectChanges();
+ return fixture.nativeElement as HTMLElement;
+ }
+
+ it('renders the ISSSTELEON shell and home page with its footer', async () => {
+ const page = await render('/');
+ expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
+ expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
+ expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
+ expect(page.querySelector('.site-footer')).not.toBeNull();
});
- it('should render the ISSSTELEON header and home page', async () => {
- const fixture = TestBed.createComponent(App);
- fixture.detectChanges();
- await TestBed.inject(Router).navigateByUrl('/');
- await fixture.whenStable();
- fixture.detectChanges();
- const compiled = fixture.nativeElement as HTMLElement;
- expect(compiled.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
- expect(compiled.querySelector('.site-header__section')?.textContent).toContain(
- 'Análisis de información',
- );
- expect(compiled.querySelector('h1')?.textContent).toContain('Analiza tu información');
+ it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
+ const page = await render('/conectar');
+ expect(page.querySelector('app-connect-page')).not.toBeNull();
+ expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
+ expect(page.querySelector('.site-footer')).toBeNull();
});
- it('opens one dialog and keeps it open on backdrop and Escape', async () => {
- const fixture = TestBed.createComponent(App);
- fixture.detectChanges();
- await TestBed.inject(Router).navigateByUrl('/');
- await fixture.whenStable();
- fixture.detectChanges();
-
- fixture.nativeElement.querySelector('.home__action').click();
- fixture.detectChanges();
- await fixture.whenStable();
-
- const dialog = TestBed.inject(MatDialog);
- expect(dialog.openDialogs).toHaveLength(1);
- const overlay = document.querySelector('.cdk-overlay-container')!;
- expect(overlay.querySelector('#upload-title')?.textContent).toContain('Cargar información');
- overlay.querySelector
('.cdk-overlay-backdrop')?.click();
- document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
- expect(dialog.openDialogs).toHaveLength(1);
- expect(overlay.querySelector('.upload-dialog__continue')?.hasAttribute('disabled')).toBe(true);
- });
-
- it('selects either source, continues, returns with selection, and closes explicitly', async () => {
- const fixture = TestBed.createComponent(App);
- fixture.detectChanges();
- await TestBed.inject(Router).navigateByUrl('/');
- await fixture.whenStable();
- fixture.detectChanges();
-
- fixture.nativeElement.querySelector('.home__action').click();
- fixture.detectChanges();
- await fixture.whenStable();
-
- const overlay = document.querySelector('.cdk-overlay-container')!;
- const cards = () => overlay.querySelectorAll('.source-card');
- const continueButton = overlay.querySelector('.upload-dialog__continue')!;
- const detectDialogChanges = () => TestBed.inject(MatDialog).openDialogs[0].componentRef?.changeDetectorRef.detectChanges();
- expect(continueButton.disabled).toBe(true);
- overlay.querySelector('.source-card')!.click();
- detectDialogChanges();
- expect(continueButton.disabled).toBe(false);
- continueButton.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
- 'Selecciona los archivos que deseas procesar.',
- );
- expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain(
- 'Configuración',
- );
- expect(continueButton.disabled).toBe(true);
- const fileInput = overlay.querySelector('input[type="file"]')!;
- const validFile = new File(['contenido'], 'pacientes.XLSX', {
- type: 'application/octet-stream',
- });
- const csvFile = new File(['a,b'], 'consultas.csv', { type: 'text/csv' });
- const invalidFile = new File(['x'], 'documento.docx');
- const emptyFile = new File([], 'vacio.csv');
- const selectFiles = (...files: File[]) => {
- Object.defineProperty(fileInput, 'files', { configurable: true, value: files });
- fileInput.dispatchEvent(new Event('change', { bubbles: true }));
- detectDialogChanges();
- fixture.detectChanges();
- };
- selectFiles(validFile, csvFile, invalidFile, emptyFile);
- expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
- expect(overlay.querySelector('.file-messages')?.textContent).toContain(
- 'documento.docx no fue agregado. Formato no compatible.',
- );
- expect(overlay.querySelector('.file-messages')?.textContent).toContain(
- 'vacio.csv no fue agregado. El archivo está vacío.',
- );
- expect(continueButton.disabled).toBe(false);
- selectFiles(validFile);
- expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
- expect(overlay.querySelector('.file-messages')?.textContent).toContain(
- 'pacientes.XLSX ya se encuentra seleccionado.',
- );
- const jsonFile = new File(['{}'], 'nuevo.json', { type: 'application/json' });
- const dialogComponent = TestBed.inject(MatDialog).openDialogs[0].componentRef!
- .instance as import('./information-upload-dialog').InformationUploadDialog;
- dialogComponent.onDrop({
- preventDefault: () => undefined,
- dataTransfer: { files: [jsonFile] },
- } as unknown as DragEvent);
- detectDialogChanges();
- fixture.detectChanges();
- expect(overlay.querySelectorAll('.file-row')).toHaveLength(3);
- overlay.querySelector('.file-row__remove')!.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
- continueButton.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(overlay.querySelector('h3')?.textContent).toContain('Confirmación');
- expect(overlay.querySelector('.configuration-placeholder p')?.textContent).toContain(
- 'La confirmación de los archivos se implementará en la siguiente fase.',
- );
- overlay.querySelector('.upload-dialog__back')!.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
- while (overlay.querySelector('.file-row__remove')) {
- overlay.querySelector('.file-row__remove')!.click();
- detectDialogChanges();
- fixture.detectChanges();
- }
- expect(overlay.querySelectorAll('.file-row')).toHaveLength(0);
- expect(overlay.querySelector('.upload-dialog__continue')?.disabled).toBe(true);
- overlay.querySelector('.upload-dialog__back')!.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(cards()[0].getAttribute('aria-pressed')).toBe('true');
- overlay.querySelectorAll('.source-card')[1].click();
- detectDialogChanges();
- const sqlContinueButton = overlay.querySelector('.upload-dialog__continue')!;
- expect(sqlContinueButton.disabled).toBe(false);
- sqlContinueButton.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(overlay.querySelector('h3')?.textContent).toContain('Conexión SQL');
- expect(overlay.querySelector('.upload-dialog__continue')?.disabled).toBe(true);
- overlay.querySelector('.upload-dialog__back')!.click();
- detectDialogChanges();
- fixture.detectChanges();
- expect(cards()[1].getAttribute('aria-pressed')).toBe('true');
- overlay.querySelector('.upload-dialog__close')!.click();
- fixture.detectChanges();
- await new Promise((resolve) => setTimeout(resolve, 200));
- expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
-
- fixture.nativeElement.querySelector('.home__action').click();
- fixture.detectChanges();
- await fixture.whenStable();
- const reopenedOverlay = document.querySelector('.cdk-overlay-container')!;
- reopenedOverlay.querySelector('.source-card')!.click();
- const reopenedDialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
- reopenedDialog.changeDetectorRef.detectChanges();
- reopenedOverlay.querySelector('.upload-dialog__continue')!.click();
- reopenedDialog.changeDetectorRef.detectChanges();
- expect(reopenedOverlay.querySelector('.selected-files')).toBeNull();
- expect(reopenedOverlay.querySelector('.upload-dialog__continue')?.disabled).toBe(true);
- reopenedOverlay.querySelector('.upload-dialog__cancel')!.click();
- fixture.detectChanges();
- await new Promise((resolve) => setTimeout(resolve, 200));
- expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
+ it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
+ const page = await render('/gobernanza');
+ expect(page.querySelector('app-governance-page')).not.toBeNull();
+ expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
+ expect(page.querySelector('.site-footer')).toBeNull();
});
});
diff --git a/src/app/app.ts b/src/app/app.ts
index 3e7d97c..b18cd4e 100644
--- a/src/app/app.ts
+++ b/src/app/app.ts
@@ -1,10 +1,31 @@
-import { Component } from '@angular/core';
-import { RouterOutlet } from '@angular/router';
+import { Component, computed, inject } from '@angular/core';
+import { toSignal } from '@angular/core/rxjs-interop';
+import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
+import { filter, map } from 'rxjs';
@Component({
- imports: [RouterOutlet],
+ imports: [RouterLink, RouterOutlet],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
})
-export class App {}
+export class App {
+ private readonly router = inject(Router);
+ private readonly route = inject(ActivatedRoute);
+
+ private readonly leafRouteData = toSignal(
+ this.router.events.pipe(
+ filter((event) => event instanceof NavigationEnd),
+ map(() => {
+ let route = this.route;
+ while (route.firstChild) route = route.firstChild;
+ return route.snapshot.data;
+ }),
+ ),
+ { initialValue: {} as Record },
+ );
+
+ /** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
+ readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
+ readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
+}
diff --git a/src/app/connect/api/api.types.ts b/src/app/connect/api/api.types.ts
new file mode 100644
index 0000000..30e9cf9
--- /dev/null
+++ b/src/app/connect/api/api.types.ts
@@ -0,0 +1,247 @@
+/** Shapes of the WebApi JSON contract for `/imports/*` and `/data/*`. */
+
+export type Domain = 'cacu' | 'cama' | 'tea';
+
+export type InferredType = 'string' | 'integer' | 'float' | 'boolean' | 'date' | 'datetime' | 'binary' | 'unknown';
+
+export type MatchReason = 'exact' | 'normalized' | 'synonym' | 'unprefixed' | 'fuzzy' | 'none';
+
+export type ConflictStrategy = 'reject' | 'upsert';
+
+export type ErrorCategory = 'missing' | 'out_of_catalog' | 'type_invalid' | 'conflict' | 'merge_conflict' | 'unknown';
+
+export type FileKind = 'csv' | 'excel' | 'json';
+
+export type SourceType = FileKind | 'sql' | 'pdf' | 'edf' | 'document';
+
+/** Backend connector categories (`GET /imports/connectors`). */
+export type ConnectorCategory = 'file' | 'database' | 'document' | 'signal';
+
+export interface SqlEngineInfo {
+ id: string;
+ label: string;
+ description: string;
+ default_port: number;
+ default_schema: string | null;
+ /** Whether the server has the driver installed. */
+ available: boolean;
+}
+
+export interface SegmentationInfo {
+ id: string;
+ label: string;
+}
+
+export interface ConnectorInfo {
+ kind: SourceType;
+ label: string;
+ description: string;
+ category: ConnectorCategory;
+ icon: string;
+ extensions: string[];
+ engines?: SqlEngineInfo[];
+ segmentations?: SegmentationInfo[];
+}
+
+/** How a database is reached: form fields, or a raw SQLAlchemy URL. */
+export type SqlConnectionRef =
+ | { server: { engine: string; host: string; port: number | null; database: string; user: string; password: string } }
+ | { connection_string: string };
+
+export interface TargetField {
+ name: string;
+ required: boolean;
+ /** JSON-schema type or format: string, integer, number, boolean, date, date-time, binary... */
+ type: string;
+}
+
+export interface TargetMeta {
+ key: string;
+ domain: Domain;
+ table: string;
+ conflict_fields: string[] | null;
+ fields: TargetField[];
+}
+
+export interface SourceColumn {
+ name: string;
+ inferred_type: InferredType;
+}
+
+export interface SuggestedMapping {
+ source_column: string;
+ target_field: string | null;
+ confidence: number;
+ reason: MatchReason;
+}
+
+export type Row = Record;
+
+export interface PreviewResponse {
+ columns: SourceColumn[];
+ sample_rows: Row[];
+ total_rows: number | null;
+ suggested_mapping: SuggestedMapping[];
+ /** Sub-tables the source offers (Excel sheets...), with the options to read each. */
+ tables?: { name: string; options: Record; kind: string }[];
+ source_metadata?: Record;
+}
+
+export interface FileOptions {
+ sheet_name?: string;
+ delimiter?: string;
+ encoding?: string;
+ record_path?: string;
+}
+
+export interface TableCandidate {
+ page_number: number;
+ bbox: [number, number, number, number]; // PDF points
+ column_count: number;
+ row_count: number;
+ preview_grid: (string | null)[][];
+}
+
+export interface PdfDetectResponse {
+ page_count: number;
+ has_text_layer: boolean;
+ table_candidates: TableCandidate[];
+}
+
+export interface RegionSpec {
+ /** The name this region's text becomes as a source column. */
+ target_field: string;
+ page_numbers: number[];
+ bbox: [number, number, number, number]; // normalized 0..1
+}
+
+export interface RegionExtractResponse {
+ columns: SourceColumn[];
+ rows: Row[];
+ warnings: { page_number: number; message: string }[];
+ suggested_mapping: SuggestedMapping[];
+}
+
+/** The `{source_type, payload}` part of a source, as built by its SourceTable. */
+export interface SourceLocator {
+ source_type: SourceType;
+ payload: Record;
+}
+
+/** One entry of `/imports/validate`'s `source` / `/imports/commit`'s `sources`. */
+export interface ImportSourcePayload extends SourceLocator {
+ target: string;
+ label?: string;
+ column_mapping: Record;
+ defaults?: Record;
+}
+
+// -- documents -----------------------------------------------------------------
+
+export type OcrMode = 'auto' | 'always' | 'never';
+
+export interface DocumentSettings {
+ segmentation: string;
+ pages_per_record: number;
+ ocr_mode: OcrMode;
+ key_pattern: string;
+}
+
+export interface ExtractedField {
+ value: unknown;
+ confidence: number;
+ /** etiqueta | patron | texto_libre | manual */
+ method: string;
+ raw?: string;
+ document?: string;
+ page_number?: number;
+ line?: string;
+ bbox?: [number, number, number, number] | null;
+}
+
+export interface DocumentImage {
+ document: string;
+ page_number: number;
+ bbox: [number, number, number, number];
+ kind: 'scan' | 'figure';
+}
+
+export interface ExtractedRecord {
+ index: number;
+ key: string | null;
+ confidence: number;
+ fields: Record;
+ missing: string[];
+ conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
+ sources: { document: string; page_numbers: number[] }[];
+ images: DocumentImage[];
+}
+
+export interface DocumentFieldSpec {
+ name: string;
+ kind: 'text' | 'identifier' | 'integer' | 'decimal' | 'date' | 'choice';
+ required: boolean;
+ labels: string[];
+}
+
+export interface DocumentExtraction extends PreviewResponse {
+ key_field: string | null;
+ fields: DocumentFieldSpec[];
+ records: ExtractedRecord[];
+}
+
+export interface RowError {
+ row_index: number;
+ field: string;
+ category: ErrorCategory;
+ message: string;
+ raw_value?: unknown;
+}
+
+export interface ValidationResult {
+ total_rows: number;
+ valid_count: number;
+ error_count: number;
+ errors: RowError[];
+}
+
+export interface CommitSourceResult {
+ target: string;
+ label: string | null;
+ total: number;
+ created: number;
+ updated: number;
+ rejected: number;
+ errors: RowError[];
+ /** Foreign keys filled from natural keys, e.g. `{pac_id: 12}`. */
+ linked?: Record;
+ /** Rows combined into a row of another source (`merge_duplicates`). */
+ merged?: number;
+ warnings?: RowError[];
+}
+
+export interface BatchResult {
+ ok: boolean;
+ results: CommitSourceResult[];
+}
+
+export interface DataPage {
+ target: string;
+ total: number;
+ limit: number;
+ offset: number;
+ /** Column names in table order. */
+ columns: string[];
+ rows: Row[];
+}
+
+export interface ApiError {
+ error: string;
+}
+
+/** Pulls the backend's `{error}` message out of an HttpErrorResponse-like value. */
+export function apiErrorMessage(error: unknown, fallback: string): string {
+ const body = (error as { error?: unknown })?.error;
+ if (body && typeof body === 'object' && typeof (body as ApiError).error === 'string') return (body as ApiError).error;
+ return fallback;
+}
diff --git a/src/app/connect/api/connectors.api.ts b/src/app/connect/api/connectors.api.ts
new file mode 100644
index 0000000..f6a2225
--- /dev/null
+++ b/src/app/connect/api/connectors.api.ts
@@ -0,0 +1,18 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable, map, shareReplay } from 'rxjs';
+import { ConnectorInfo } from './api.types';
+
+/** GET /imports/connectors: what the server can read. Fetched once per app. */
+@Injectable({ providedIn: 'root' })
+export class ConnectorsApi {
+ private readonly http = inject(HttpClient);
+ private readonly connectors$ = this.http.get<{ connectors: ConnectorInfo[] }>('/imports/connectors').pipe(
+ map((response) => response.connectors),
+ shareReplay({ bufferSize: 1, refCount: false }),
+ );
+
+ list(): Observable {
+ return this.connectors$;
+ }
+}
diff --git a/src/app/connect/api/data.api.ts b/src/app/connect/api/data.api.ts
new file mode 100644
index 0000000..e84a43b
--- /dev/null
+++ b/src/app/connect/api/data.api.ts
@@ -0,0 +1,15 @@
+import { HttpClient, HttpParams } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable } from 'rxjs';
+import { DataPage } from './api.types';
+
+/** GET /data/: rows actually stored in the destination database. */
+@Injectable({ providedIn: 'root' })
+export class DataApi {
+ private readonly http = inject(HttpClient);
+
+ page(target: string, limit: number, offset: number): Observable {
+ const params = new HttpParams().set('limit', limit).set('offset', offset);
+ return this.http.get(`/data/${encodeURIComponent(target)}`, { params });
+ }
+}
diff --git a/src/app/connect/api/document-source.api.ts b/src/app/connect/api/document-source.api.ts
new file mode 100644
index 0000000..798797a
--- /dev/null
+++ b/src/app/connect/api/document-source.api.ts
@@ -0,0 +1,25 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable } from 'rxjs';
+import { DocumentExtraction } from './api.types';
+
+/** Clinical documents: field extraction and page/image rendering. */
+@Injectable({ providedIn: 'root' })
+export class DocumentSourceApi {
+ private readonly http = inject(HttpClient);
+
+ /** `payload` is the document source payload (files, segmentation, overrides...). */
+ extract(payload: Record, target: string): Observable {
+ return this.http.post('/imports/sources/document/extract', { ...payload, target });
+ }
+
+ /** PNG of a page, or of a normalized region of it (an embedded image). */
+ pageImage(file: File, pageNumber: number, bbox?: [number, number, number, number], dpi = 110): Observable {
+ const form = new FormData();
+ form.append('file', file);
+ form.append('page_number', String(pageNumber));
+ form.append('dpi', String(dpi));
+ if (bbox) form.append('bbox', JSON.stringify(bbox));
+ return this.http.post('/imports/sources/document/page-image', form, { responseType: 'blob' });
+ }
+}
diff --git a/src/app/connect/api/file-encoding.ts b/src/app/connect/api/file-encoding.ts
new file mode 100644
index 0000000..617aaf3
--- /dev/null
+++ b/src/app/connect/api/file-encoding.ts
@@ -0,0 +1,10 @@
+/** Base64 of a File's bytes, for JSON endpoints that carry a file. */
+export async function fileToBase64(file: Blob): Promise {
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ const chunk = 0x8000;
+ let binary = '';
+ for (let i = 0; i < bytes.length; i += chunk) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
+ }
+ return btoa(binary);
+}
diff --git a/src/app/connect/api/file-source.api.ts b/src/app/connect/api/file-source.api.ts
new file mode 100644
index 0000000..c4c6e35
--- /dev/null
+++ b/src/app/connect/api/file-source.api.ts
@@ -0,0 +1,24 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable } from 'rxjs';
+import { FileOptions, PreviewResponse, SourceType } from './api.types';
+
+/** Previews of uploaded files: multipart for one file, JSON payload for any source. */
+@Injectable({ providedIn: 'root' })
+export class FileSourceApi {
+ private readonly http = inject(HttpClient);
+
+ preview(file: File, kind: SourceType, target: string | null, options: FileOptions = {}): Observable {
+ const form = new FormData();
+ form.append('file', file);
+ form.append('source_kind', kind);
+ if (target) form.append('target', target);
+ if (Object.keys(options).length > 0) form.append('options', JSON.stringify(options));
+ return this.http.post('/imports/sources/file/preview', form);
+ }
+
+ /** Same payload an import source carries, e.g. several EDF files at once. */
+ previewPayload(kind: SourceType, payload: Record, target: string | null): Observable {
+ return this.http.post(`/imports/sources/${kind}/preview`, { payload, ...(target ? { target } : {}) });
+ }
+}
diff --git a/src/app/connect/api/imports.api.ts b/src/app/connect/api/imports.api.ts
new file mode 100644
index 0000000..5afe726
--- /dev/null
+++ b/src/app/connect/api/imports.api.ts
@@ -0,0 +1,19 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable } from 'rxjs';
+import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
+
+/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
+@Injectable({ providedIn: 'root' })
+export class ImportsApi {
+ private readonly http = inject(HttpClient);
+
+ validate(source: ImportSourcePayload): Observable {
+ return this.http.post('/imports/validate', { source });
+ }
+
+ /** `mergeDuplicates`: rows of different sources with the same natural key become one record. */
+ commit(sources: ImportSourcePayload[], onConflict: ConflictStrategy, mergeDuplicates = false): Observable {
+ return this.http.post('/imports/commit', { sources, on_conflict: onConflict, merge_duplicates: mergeDuplicates });
+ }
+}
diff --git a/src/app/connect/api/pdf-source.api.ts b/src/app/connect/api/pdf-source.api.ts
new file mode 100644
index 0000000..4cd089d
--- /dev/null
+++ b/src/app/connect/api/pdf-source.api.ts
@@ -0,0 +1,48 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable, from, switchMap } from 'rxjs';
+import { PdfDetectResponse, PreviewResponse, RegionExtractResponse, RegionSpec } from './api.types';
+import { fileToBase64 } from './file-encoding';
+
+/** POST /imports/sources/pdf/... endpoints. Every call resends the file bytes. */
+@Injectable({ providedIn: 'root' })
+export class PdfSourceApi {
+ private readonly http = inject(HttpClient);
+
+ detect(file: File): Observable {
+ const form = new FormData();
+ form.append('file', file);
+ return this.http.post('/imports/sources/pdf/detect', form);
+ }
+
+ /** Raw PNG bytes; the caller turns them into an object URL. */
+ pageImage(file: File, pageNumber: number, dpi?: number): Observable {
+ const form = new FormData();
+ form.append('file', file);
+ form.append('page_number', String(pageNumber));
+ if (dpi) form.append('dpi', String(dpi));
+ return this.http.post('/imports/sources/pdf/page-image', form, { responseType: 'blob' });
+ }
+
+ tablePreview(file: File, pageNumber: number, bbox: [number, number, number, number], target: string | null): Observable {
+ const form = new FormData();
+ form.append('file', file);
+ form.append('page_number', String(pageNumber));
+ form.append('bbox', JSON.stringify(bbox));
+ if (target) form.append('target', target);
+ return this.http.post('/imports/sources/pdf/table/preview', form);
+ }
+
+ extractRegions(file: File, regions: RegionSpec[], target: string | null, dpi = 150): Observable {
+ return from(fileToBase64(file)).pipe(
+ switchMap((file_base64) =>
+ this.http.post('/imports/sources/pdf/regions/extract', {
+ file_base64,
+ regions,
+ dpi,
+ ...(target ? { target } : {}),
+ }),
+ ),
+ );
+ }
+}
diff --git a/src/app/connect/api/source-gateway.ts b/src/app/connect/api/source-gateway.ts
new file mode 100644
index 0000000..5cb8045
--- /dev/null
+++ b/src/app/connect/api/source-gateway.ts
@@ -0,0 +1,18 @@
+import { Injectable, inject } from '@angular/core';
+import { DocumentSourceApi } from './document-source.api';
+import { FileSourceApi } from './file-source.api';
+import { PdfSourceApi } from './pdf-source.api';
+import { SqlSourceApi } from './sql-source.api';
+
+/**
+ * The source endpoints, handed to domain objects (`DataConnection.load`,
+ * `SourceTable.preview`) so each subclass calls the one it needs and the
+ * domain layer stays free of Angular DI.
+ */
+@Injectable({ providedIn: 'root' })
+export class SourceGateway {
+ readonly file = inject(FileSourceApi);
+ readonly sql = inject(SqlSourceApi);
+ readonly pdf = inject(PdfSourceApi);
+ readonly document = inject(DocumentSourceApi);
+}
diff --git a/src/app/connect/api/sql-source.api.ts b/src/app/connect/api/sql-source.api.ts
new file mode 100644
index 0000000..7822d9c
--- /dev/null
+++ b/src/app/connect/api/sql-source.api.ts
@@ -0,0 +1,42 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable, map } from 'rxjs';
+import { PreviewResponse, SourceColumn, SqlConnectionRef } from './api.types';
+
+/** POST /imports/sources/sql/*. Stateless: every call carries the connection. */
+@Injectable({ providedIn: 'root' })
+export class SqlSourceApi {
+ private readonly http = inject(HttpClient);
+
+ testConnection(connection: SqlConnectionRef): Observable<{ ok: true; dialect: string }> {
+ return this.http.post<{ ok: true; dialect: string }>('/imports/sources/sql/test-connection', connection);
+ }
+
+ schemas(connection: SqlConnectionRef): Observable {
+ return this.http.post<{ schemas: string[] }>('/imports/sources/sql/schemas', connection).pipe(map((response) => response.schemas));
+ }
+
+ tables(connection: SqlConnectionRef, schema?: string): Observable {
+ return this.http
+ .post<{ tables: string[] }>('/imports/sources/sql/tables', { ...connection, ...(schema ? { schema } : {}) })
+ .pipe(map((response) => response.tables));
+ }
+
+ columns(connection: SqlConnectionRef, table: string, schema?: string): Observable {
+ return this.http
+ .post<{ columns: SourceColumn[] }>('/imports/sources/sql/columns', { ...connection, table, ...(schema ? { schema } : {}) })
+ .pipe(map((response) => response.columns));
+ }
+
+ preview(
+ connection: SqlConnectionRef,
+ source: { table?: string; schema?: string; query?: string },
+ target: string | null,
+ ): Observable {
+ return this.http.post('/imports/sources/sql/preview', {
+ ...connection,
+ ...(source.query ? { query: source.query } : { table: source.table, ...(source.schema ? { schema: source.schema } : {}) }),
+ ...(target ? { target } : {}),
+ });
+ }
+}
diff --git a/src/app/connect/api/targets.api.ts b/src/app/connect/api/targets.api.ts
new file mode 100644
index 0000000..a4706fd
--- /dev/null
+++ b/src/app/connect/api/targets.api.ts
@@ -0,0 +1,20 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable, inject } from '@angular/core';
+import { Observable, map, shareReplay } from 'rxjs';
+import { TargetMeta } from './api.types';
+
+/** GET /imports/targets, fetched once per app and shared. */
+@Injectable({ providedIn: 'root' })
+export class TargetsApi {
+ private readonly http = inject(HttpClient);
+ private readonly targets$ = this.http
+ .get<{ targets: TargetMeta[] }>('/imports/targets')
+ .pipe(
+ map((response) => response.targets),
+ shareReplay({ bufferSize: 1, refCount: false }),
+ );
+
+ list(): Observable {
+ return this.targets$;
+ }
+}
diff --git a/src/app/connect/components/column-mapper/column-mapper.html b/src/app/connect/components/column-mapper/column-mapper.html
new file mode 100644
index 0000000..cc168ed
--- /dev/null
+++ b/src/app/connect/components/column-mapper/column-mapper.html
@@ -0,0 +1,191 @@
+@let f = flow();
+@let s = summary();
+
+
+
+
+
+ @for (column of columns(); track column.name) {
+
+
{{
+ column.inferred_type | typeIcon
+ }}
+
+ {{ column.name }}
+ {{ samples().get(column.name) || '(vacío)' }}
+
+ @if (mappedTo(column.name); as field) {
+
→ {{ field }}
+ }
+
drag_indicator
+
+ {{ column.inferred_type | typeIcon }} {{ column.name }}
+
+
+ } @empty {
+
{{ onlyUnusedColumns() ? 'Todas las columnas están asignadas.' : 'La fuente no tiene columnas.' }}
+ }
+
+
+
+
+
+
+
+
+ search
+ Buscar campo
+
+
+
+ Todos
+ Obligatorios
+ Sin asignar
+
+
+ @if (s.suggestions > 0) {
+
+ done_all Confirmar {{ s.suggestions }}
+
+ }
+
+ auto_fix_high Auto-mapear
+
+
+ layers_clear Limpiar
+
+
+ @if (lastAutoMap() !== null) {
+
+ {{ lastAutoMap() === 0 ? 'No se encontraron más coincidencias por nombre.' : 'Se asignaron ' + lastAutoMap() + ' campo(s).' }}
+
+ }
+
+
+ @for (field of fields(); track field.name) {
+ @let mapping = f.mapping.byField().get(field.name);
+ @let defaultValue = f.defaults()[field.name];
+
+
+ {{ field.type | typeIcon }}
+ {{ field.name }}
+ @if (field.required) {
+ *
+ }
+ @if (errorsFor(field.name); as errors) {
+
+ report {{ errors }}
+
+ }
+
+
+
+ @if (mapping) {
+
+
drag_indicator
+
{{ mapping.source }}
+ @if (mapping.confidence !== undefined) {
+
{{
+ confidenceLabel(mapping.confidence)
+ }}
+
+ check
+
+ }
+
+ close
+
+
view_column {{ mapping.source }}
+
+ } @else {
+
+
+ @for (column of f.sourceColumns(); track column.name) {
+
+ {{ column.name }}
+ @if (mappedTo(column.name); as other) {
+ (ahora en {{ other }})
+ }
+
+ }
+
+
+ }
+
+
+
+ @if (editingDefault() === field.name) {
+
+ Valor por defecto
+
+
+ } @else if (defaultValue) {
+
+
+ = {{ defaultValue }}
+ cancel
+
+
+ } @else {
+
+ edit_note
+
+ }
+
+
+ } @empty {
+
Ningún campo coincide con el filtro.
+ }
+
+
+
diff --git a/src/app/connect/components/column-mapper/column-mapper.scss b/src/app/connect/components/column-mapper/column-mapper.scss
new file mode 100644
index 0000000..d629de8
--- /dev/null
+++ b/src/app/connect/components/column-mapper/column-mapper.scss
@@ -0,0 +1,340 @@
+:host {
+ display: block;
+}
+
+.mapper {
+ align-items: start;
+ display: grid;
+ gap: var(--space-4);
+ grid-template-columns: minmax(260px, 340px) 1fr;
+}
+
+.mapper__header {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ justify-content: space-between;
+ margin-bottom: var(--space-2);
+
+ h3 {
+ font: var(--mat-sys-title-small);
+ margin: 0;
+ }
+}
+
+.mapper__summary {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.mapper__missing {
+ color: var(--mat-sys-error);
+ font-weight: 500;
+}
+
+.mapper__columns {
+ position: sticky;
+ top: 0;
+}
+
+.tray {
+ background: var(--mat-sys-surface-container-low);
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ max-height: 60vh;
+ min-height: 96px;
+ overflow: auto;
+ padding: var(--space-2);
+}
+
+.tray.cdk-drop-list-dragging {
+ outline: 2px dashed var(--mat-sys-outline);
+}
+
+.tray__empty,
+.fields__empty {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ margin: var(--space-2);
+}
+
+.column-chip {
+ align-items: center;
+ background: var(--mat-sys-surface);
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-small);
+ cursor: grab;
+ display: flex;
+ gap: var(--space-2);
+ padding: 6px var(--space-2);
+
+ &:hover {
+ border-color: var(--mat-sys-primary);
+ }
+}
+
+.column-chip--used {
+ opacity: 0.62;
+}
+
+.column-chip__type {
+ color: var(--mat-sys-primary);
+ flex: none;
+ font-size: 18px;
+ height: 18px;
+ width: 18px;
+}
+
+.column-chip__text {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ line-height: 1.25;
+ min-width: 0;
+}
+
+.column-chip__name {
+ font: var(--mat-sys-label-large);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.column-chip__sample {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.column-chip__target {
+ color: var(--mat-sys-primary);
+ flex: none;
+ font: var(--mat-sys-label-small);
+ max-width: 45%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.column-chip__grip {
+ color: var(--mat-sys-outline);
+ flex: none;
+ font-size: 18px;
+ height: 18px;
+ width: 18px;
+}
+
+.mapper__toolbar {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin-bottom: var(--space-2);
+}
+
+.mapper__search {
+ width: 220px;
+}
+
+.mapper__spacer {
+ flex: 1;
+}
+
+.mapper__note {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ margin: 0 0 var(--space-2);
+}
+
+.fields {
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ overflow: hidden;
+}
+
+.field {
+ align-items: center;
+ border-bottom: 1px solid var(--mat-sys-outline-variant);
+ display: grid;
+ gap: var(--space-3);
+ grid-template-columns: minmax(180px, 1fr) minmax(220px, 1.2fr) minmax(48px, 0.7fr);
+ min-height: 56px;
+ padding: var(--space-1) var(--space-3);
+
+ &:last-child {
+ border-bottom: 0;
+ }
+}
+
+.field--missing {
+ background: color-mix(in srgb, var(--mat-sys-error-container) 35%, transparent);
+}
+
+.field__meta {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+ min-width: 0;
+}
+
+.field__type {
+ color: var(--mat-sys-on-surface-variant);
+ flex: none;
+ font-size: 18px;
+ height: 18px;
+ width: 18px;
+}
+
+.field__name {
+ font: var(--mat-sys-body-medium);
+ font-family: 'Roboto Mono', ui-monospace, monospace;
+ font-size: 13px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.field__required {
+ color: var(--mat-sys-error);
+ font-weight: 700;
+}
+
+.field__errors {
+ align-items: center;
+ background: #fff1d6;
+ border-radius: 999px;
+ color: #7a4b00;
+ display: inline-flex;
+ font: var(--mat-sys-label-small);
+ gap: 2px;
+ padding: 1px 6px 1px 3px;
+
+ mat-icon {
+ font-size: 14px;
+ height: 14px;
+ width: 14px;
+ }
+}
+
+.slot {
+ border: 1.5px dashed transparent;
+ border-radius: var(--mat-sys-corner-small);
+ min-height: 44px;
+ padding: 2px;
+ transition: border-color 0.12s ease, background-color 0.12s ease;
+}
+
+.slot.cdk-drop-list-receiving {
+ border-color: var(--mat-sys-outline);
+}
+
+.slot.cdk-drop-list-dragging {
+ background: var(--mat-sys-primary-container);
+ border-color: var(--mat-sys-primary);
+}
+
+.slot ::ng-deep .cdk-drag-placeholder {
+ display: none;
+}
+
+.slot__select {
+ width: 100%;
+ --mat-form-field-container-height: 40px;
+ --mat-form-field-container-vertical-padding: 8px;
+}
+
+.slot__option-note {
+ color: var(--mat-sys-on-surface-variant);
+ font-size: 12px;
+ margin-left: 4px;
+}
+
+.slot__chip {
+ align-items: center;
+ background: var(--mat-sys-secondary-container);
+ border-radius: var(--mat-sys-corner-small);
+ color: var(--mat-sys-on-secondary-container);
+ cursor: grab;
+ display: flex;
+ gap: var(--space-1);
+ min-height: 40px;
+ padding: 0 var(--space-1) 0 var(--space-2);
+
+ > mat-icon {
+ font-size: 18px;
+ height: 18px;
+ opacity: 0.6;
+ width: 18px;
+ }
+}
+
+.slot__chip--suggested {
+ background: var(--mat-sys-surface-container-high);
+ border: 1px dashed var(--mat-sys-primary);
+ color: var(--mat-sys-on-surface);
+}
+
+.slot__source {
+ flex: 1;
+ font: var(--mat-sys-label-large);
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.slot__confidence {
+ background: var(--mat-sys-primary);
+ border-radius: 999px;
+ color: var(--mat-sys-on-primary);
+ font: var(--mat-sys-label-small);
+ padding: 1px 6px;
+}
+
+.slot__button {
+ --mat-icon-button-state-layer-size: 28px;
+ height: 28px;
+ padding: 2px;
+ width: 28px;
+
+ mat-icon {
+ font-size: 18px;
+ height: 18px;
+ width: 18px;
+ }
+}
+
+.field__default {
+ display: flex;
+ justify-content: flex-end;
+ min-width: 0;
+}
+
+.field__default-input {
+ width: 100%;
+}
+
+.field__default-button {
+ opacity: 0.5;
+}
+
+.field:hover .field__default-button {
+ opacity: 1;
+}
+
+@media (max-width: 1100px) {
+ .mapper {
+ grid-template-columns: 1fr;
+ }
+ .mapper__columns {
+ position: static;
+ }
+ .tray {
+ max-height: 260px;
+ }
+}
diff --git a/src/app/connect/components/column-mapper/column-mapper.spec.ts b/src/app/connect/components/column-mapper/column-mapper.spec.ts
new file mode 100644
index 0000000..3094cb3
--- /dev/null
+++ b/src/app/connect/components/column-mapper/column-mapper.spec.ts
@@ -0,0 +1,54 @@
+import { TestBed } from '@angular/core/testing';
+import { CdkDragDrop } from '@angular/cdk/drag-drop';
+import { ImportFlow } from '../../domain/import-flow';
+import { FakeConnection, FakeTable, NO_GATEWAY, PACIENTE } from '../../testing/fakes';
+import { ColumnMapper } from './column-mapper';
+
+describe('ColumnMapper', () => {
+ function setup() {
+ const flow = new ImportFlow(new FakeTable(new FakeConnection()), PACIENTE);
+ flow.load(NO_GATEWAY).subscribe();
+ const fixture = TestBed.createComponent(ColumnMapper);
+ fixture.componentRef.setInput('flow', flow);
+ fixture.detectChanges();
+ return { flow, fixture, mapper: fixture.componentInstance };
+ }
+
+ const drop = (column: string, target: string) =>
+ ({ item: { data: column }, container: { data: target }, previousContainer: { data: 'tray' } }) as unknown as CdkDragDrop;
+
+ it('renders a slot per destination field, required first, with the missing one flagged', () => {
+ const { fixture } = setup();
+ const rows = Array.from(fixture.nativeElement.querySelectorAll('.field')) as HTMLElement[];
+ expect(rows.map((row) => row.querySelector('.field__name')?.textContent?.trim())).toEqual(['pac_id_hospital', 'pac_sexo', 'pac_parentesco']);
+ expect(rows[0].classList).toContain('field--missing');
+ });
+
+ it('dropping a column on a field maps it; dropping it back on the tray unmaps it', () => {
+ const { flow, mapper } = setup();
+ mapper.onDropOnField(drop('Clave', 'pac_id_hospital'));
+ expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
+ expect(flow.status()).toBe('ready');
+
+ mapper.onDropOnTray({ item: { data: 'Clave' }, container: {}, previousContainer: { other: true } } as unknown as CdkDragDrop);
+ expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo' });
+ });
+
+ it('the select is an alternative to dragging, and a default value covers a required field', () => {
+ const { flow, mapper } = setup();
+ mapper.pick('pac_sexo', null);
+ expect(flow.mapping.size()).toBe(0);
+ mapper.saveDefault('pac_id_hospital', ' H-DEFAULT ');
+ expect(flow.defaults()).toEqual({ pac_id_hospital: 'H-DEFAULT' });
+ expect(flow.missingRequired()).toEqual([]);
+ });
+
+ it('filters fields and columns', () => {
+ const { mapper } = setup();
+ mapper.fieldFilter.set('unassigned');
+ expect(mapper.fields().map((f) => f.name)).toEqual(['pac_id_hospital', 'pac_parentesco']);
+ mapper.onlyUnusedColumns.set(true);
+ expect(mapper.columns().map((c) => c.name)).toEqual(['Clave']);
+ expect(mapper.samples().get('Sexo')).toBe('F · X');
+ });
+});
diff --git a/src/app/connect/components/column-mapper/column-mapper.ts b/src/app/connect/components/column-mapper/column-mapper.ts
new file mode 100644
index 0000000..ba20f98
--- /dev/null
+++ b/src/app/connect/components/column-mapper/column-mapper.ts
@@ -0,0 +1,152 @@
+import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop';
+import { Component, computed, input, signal } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MatButtonToggleModule } from '@angular/material/button-toggle';
+import { MatChipsModule } from '@angular/material/chips';
+import { MatFormFieldModule } from '@angular/material/form-field';
+import { MatIconModule } from '@angular/material/icon';
+import { MatInputModule } from '@angular/material/input';
+import { MatSelectModule } from '@angular/material/select';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { SourceColumn, TargetField } from '../../api/api.types';
+import { ImportFlow } from '../../domain/import-flow';
+import { AutofocusDirective } from '../shared/autofocus.directive';
+import { TypeIconPipe, TypeLabelPipe } from '../shared/type-icon.pipe';
+
+type FieldFilter = 'all' | 'required' | 'unassigned';
+
+/**
+ * Drag-and-drop column mapping for one flow: source columns on the left,
+ * destination fields (drop slots) on the right. Every slot also takes a
+ * pick from a select (keyboard/accessibility path) and an optional default
+ * value, so a field the source lacks can still be filled.
+ *
+ * Presentation only: every edit goes through `ImportFlow`, which owns the
+ * mapping state.
+ */
+@Component({
+ selector: 'app-column-mapper',
+ imports: [
+ AutofocusDirective,
+ DragDropModule,
+ MatButtonModule,
+ MatButtonToggleModule,
+ MatChipsModule,
+ MatFormFieldModule,
+ MatIconModule,
+ MatInputModule,
+ MatSelectModule,
+ MatTooltipModule,
+ TypeIconPipe,
+ TypeLabelPipe,
+ ],
+ templateUrl: './column-mapper.html',
+ styleUrl: './column-mapper.scss',
+})
+export class ColumnMapper {
+ readonly flow = input.required();
+
+ readonly fieldFilter = signal('all');
+ readonly fieldSearch = signal('');
+ readonly onlyUnusedColumns = signal(false);
+ readonly editingDefault = signal(null);
+ readonly lastAutoMap = signal(null);
+
+ readonly acceptsColumns = (drag: CdkDrag) => typeof drag.data === 'string';
+
+ readonly fields = computed(() => {
+ const flow = this.flow();
+ const mapped = flow.mapping.byField();
+ const defaults = flow.defaults();
+ const term = this.fieldSearch().trim().toLowerCase();
+ return flow.target.fields
+ .filter((field) => !term || field.name.toLowerCase().includes(term))
+ .filter((field) => {
+ switch (this.fieldFilter()) {
+ case 'required':
+ return field.required;
+ case 'unassigned':
+ return !mapped.has(field.name) && !defaults[field.name];
+ default:
+ return true;
+ }
+ })
+ .sort((a, b) => Number(b.required) - Number(a.required));
+ });
+
+ readonly columns = computed(() => {
+ const flow = this.flow();
+ return this.onlyUnusedColumns() ? flow.unmappedColumns() : flow.sourceColumns();
+ });
+
+ /** Up to three distinct non-empty sample values per source column, for the tray. */
+ readonly samples = computed(() => {
+ const rows = this.flow().preview()?.sample_rows ?? [];
+ const samples = new Map();
+ for (const column of this.flow().sourceColumns()) {
+ const values = new Set();
+ for (const row of rows) {
+ const value = row[column.name];
+ if (value !== null && value !== undefined && String(value).trim() !== '') values.add(String(value));
+ if (values.size === 3) break;
+ }
+ samples.set(column.name, [...values].join(' · '));
+ }
+ return samples;
+ });
+
+ readonly summary = computed(() => {
+ const flow = this.flow();
+ const covered = flow.target.fields.filter((f) => flow.mapping.byField().has(f.name) || flow.defaults()[f.name]).length;
+ return {
+ covered,
+ total: flow.target.fields.length,
+ missing: flow.missingRequired().length,
+ suggestions: flow.pendingSuggestions(),
+ unused: flow.unmappedColumns().length,
+ };
+ });
+
+ onSearch(event: Event): void {
+ this.fieldSearch.set((event.target as HTMLInputElement).value);
+ }
+
+ onDropOnField(event: CdkDragDrop): void {
+ this.flow().map(event.item.data as string, event.container.data);
+ }
+
+ onDropOnTray(event: CdkDragDrop): void {
+ if (event.previousContainer !== event.container) this.flow().unmapSource(event.item.data as string);
+ }
+
+ pick(field: string, source: string | null): void {
+ if (source) this.flow().map(source, field);
+ else this.flow().unmapField(field);
+ }
+
+ autoMap(): void {
+ this.lastAutoMap.set(this.flow().autoMap());
+ }
+
+ confirmAll(): void {
+ const flow = this.flow();
+ flow.mapping.items().forEach((m) => m.confidence !== undefined && flow.confirmSuggestion(m.field));
+ }
+
+ saveDefault(field: string, value: string): void {
+ this.flow().setDefault(field, value.trim() || null);
+ this.editingDefault.set(null);
+ }
+
+ errorsFor(field: string): number {
+ return this.flow().quality().get(field)?.errors ?? 0;
+ }
+
+ mappedTo(column: string): string | undefined {
+ return this.flow().mapping.bySource().get(column)?.field;
+ }
+
+ confidenceLabel(confidence: number): string {
+ return `${Math.round(confidence * 100)}%`;
+ }
+}
diff --git a/src/app/connect/components/connect-page/connect-page.html b/src/app/connect/components/connect-page/connect-page.html
new file mode 100644
index 0000000..1060c17
--- /dev/null
+++ b/src/app/connect/components/connect-page/connect-page.html
@@ -0,0 +1,87 @@
+
+
+
+ {{ paneOpen() ? 'menu_open' : 'menu' }}
+
+
+ Análisis de información
+
Conectar datos
+
+
+
+ @for (domain of domains; track domain.id) {
+ {{ domain.label }}
+ }
+
+
+
+
+
+ add Obtener datos
+
+
+ travel_explore Explorar la base
+
+
+ fact_check Validar todo
+
+
+ cloud_upload Cargar a la base
+
+
+
+ @if (store.catalogError(); as error) {
+
error {{ error }}
+ }
+
+
+
+
+
+
+
+
+
+ @if (store.selectedFlow(); as flow) {
+
+ }
+
+
+
+
+ @let s = store.summary();
+ cable {{ s.connections }} conexión(es)
+ account_tree {{ s.flows }} flujo(s) · {{ s.ready }} listo(s)
+ @if (s.incomplete) {
+ rule {{ s.incomplete }} sin mapear
+ }
+ table_rows {{ s.rows | number }} filas de origen
+ @if (s.errors) {
+ report {{ s.errors | number }} con errores
+ }
+
+ Destino: {{ store.domain().toUpperCase() }}
+
+
diff --git a/src/app/connect/components/connect-page/connect-page.scss b/src/app/connect/components/connect-page/connect-page.scss
new file mode 100644
index 0000000..f92a749
--- /dev/null
+++ b/src/app/connect/components/connect-page/connect-page.scss
@@ -0,0 +1,115 @@
+:host {
+ display: flex;
+ flex: 1;
+ min-width: 0;
+}
+
+.workspace {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ height: calc(100dvh - var(--site-header-height));
+ min-width: 0;
+}
+
+.workspace__toolbar {
+ --mat-toolbar-container-background-color: var(--mat-sys-surface);
+ --mat-toolbar-standard-height: 68px;
+ border-bottom: 1px solid var(--mat-sys-outline-variant);
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ height: auto;
+ min-height: 68px;
+ padding: var(--space-2) var(--space-4);
+}
+
+.workspace__title {
+ display: flex;
+ flex-direction: column;
+ line-height: 1.1;
+ margin-right: var(--space-4);
+
+ h1 {
+ color: var(--color-primary);
+ font-family: var(--font-heading);
+ font-size: 26px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: 0;
+ }
+}
+
+.workspace__eyebrow {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-small);
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+}
+
+.workspace__spacer {
+ flex: 1;
+}
+
+.workspace__alert {
+ align-items: center;
+ background: var(--mat-sys-error-container);
+ color: var(--mat-sys-on-error-container);
+ display: flex;
+ gap: var(--space-2);
+ margin: 0;
+ padding: var(--space-2) var(--space-4);
+}
+
+.workspace__body {
+ background: var(--color-background);
+ flex: 1;
+ min-height: 0;
+}
+
+.workspace__pane {
+ --mat-sidenav-container-shape: 0;
+ background: var(--mat-sys-surface-container-lowest, #fff);
+ border-right: 1px solid var(--mat-sys-outline-variant);
+ width: 320px;
+}
+
+.workspace__main {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-4) var(--space-6);
+}
+
+.workspace__status {
+ align-items: center;
+ background: var(--color-text);
+ color: #dfe5ee;
+ display: flex;
+ flex-wrap: wrap;
+ font: var(--mat-sys-body-small);
+ gap: var(--space-1) var(--space-5);
+ min-height: 32px;
+ padding: 0 var(--space-4);
+
+ span {
+ align-items: center;
+ display: inline-flex;
+ gap: 6px;
+ }
+
+ mat-icon {
+ font-size: 16px;
+ height: 16px;
+ width: 16px;
+ }
+}
+
+.workspace__status-warn {
+ color: #ffd27a;
+}
+
+@media (max-width: 900px) {
+ .workspace__pane {
+ width: 280px;
+ }
+}
diff --git a/src/app/connect/components/connect-page/connect-page.ts b/src/app/connect/components/connect-page/connect-page.ts
new file mode 100644
index 0000000..9a7c768
--- /dev/null
+++ b/src/app/connect/components/connect-page/connect-page.ts
@@ -0,0 +1,157 @@
+import { DragDropModule } from '@angular/cdk/drag-drop';
+import { DecimalPipe } from '@angular/common';
+import { Component, Injector, inject, signal } from '@angular/core';
+import { MatBadgeModule } from '@angular/material/badge';
+import { MatButtonModule } from '@angular/material/button';
+import { MatButtonToggleModule } from '@angular/material/button-toggle';
+import { MatDialog } from '@angular/material/dialog';
+import { MatPaginatorIntl } from '@angular/material/paginator';
+import { MatIconModule } from '@angular/material/icon';
+import { MatSidenavModule } from '@angular/material/sidenav';
+import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
+import { MatToolbarModule } from '@angular/material/toolbar';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { Domain, TargetMeta } from '../../api/api.types';
+import { DataConnection, SourceTable } from '../../domain/data-source';
+import { PdfConnection } from '../../domain/pdf-source';
+import { SqlConnection } from '../../domain/sql-source';
+import { ConnectWorkspaceStore, DOMAINS } from '../../state/connect-workspace.store';
+import { ConnectionsPanel, TableUse } from '../connections-panel/connections-panel';
+import { ConnectorGalleryDialog } from '../connector-gallery-dialog/connector-gallery-dialog';
+import { DatabaseExplorerData, DatabaseExplorerDialog } from '../database-explorer-dialog/database-explorer-dialog';
+import { FlowCanvas } from '../flow-canvas/flow-canvas';
+import { FlowEditor } from '../flow-editor/flow-editor';
+import { LoadDialog, LoadDialogResult } from '../load-dialog/load-dialog';
+import { NewFlowDialog, NewFlowDialogData } from '../new-flow-dialog/new-flow-dialog';
+import { PdfRegionsDialog, PdfRegionsDialogData, PdfRegionsResult } from '../pdf-regions-dialog/pdf-regions-dialog';
+import { SpanishPaginatorIntl } from '../shared/spanish-paginator-intl';
+import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-dialog';
+
+/**
+ * The "Conectar datos" workspace (route `/conectar`): connections pane on
+ * the left, composition canvas + selected flow's editor in the middle, a
+ * toolbar for the batch-level actions, a status bar. Owns the workspace
+ * store (one per visit) and the dialogs; everything else is delegated to
+ * the child components and the store.
+ */
+@Component({
+ selector: 'app-connect-page',
+ imports: [
+ ConnectionsPanel,
+ DecimalPipe,
+ DragDropModule,
+ FlowCanvas,
+ FlowEditor,
+ MatBadgeModule,
+ MatButtonModule,
+ MatButtonToggleModule,
+ MatIconModule,
+ MatSidenavModule,
+ MatSnackBarModule,
+ MatToolbarModule,
+ MatTooltipModule,
+ ],
+ // Workspace-scoped (the lazy chunk), including for dialogs opened with
+ // this page's injector.
+ providers: [ConnectWorkspaceStore, { provide: MatPaginatorIntl, useClass: SpanishPaginatorIntl }],
+ templateUrl: './connect-page.html',
+ styleUrl: './connect-page.scss',
+})
+export class ConnectPage {
+ readonly store = inject(ConnectWorkspaceStore);
+ private readonly dialog = inject(MatDialog);
+ private readonly snackBar = inject(MatSnackBar);
+ private readonly injector = inject(Injector);
+
+ readonly domains = DOMAINS;
+ readonly paneOpen = signal(true);
+ readonly validatingAll = signal(false);
+
+ setDomain(domain: Domain): void {
+ this.store.setDomain(domain);
+ }
+
+ openGallery(): void {
+ this.dialog
+ .open(ConnectorGalleryDialog, { width: '960px', maxWidth: '96vw', autoFocus: false })
+ .afterClosed()
+ .subscribe((connections) => connections?.forEach((connection) => this.store.addConnection(connection)));
+ }
+
+ useTable({ table, target }: TableUse): void {
+ if (target) {
+ this.store.createFlow(table, target);
+ return;
+ }
+ this.dialog
+ .open(NewFlowDialog, {
+ width: '560px',
+ maxWidth: '96vw',
+ data: { table, targets: this.store.targets(), existingTargets: this.store.flowsByTarget() },
+ })
+ .afterClosed()
+ .subscribe((chosen) => chosen && this.store.createFlow(table, chosen));
+ }
+
+ onTableDropped(table: SourceTable): void {
+ this.useTable({ table });
+ }
+
+ addQuery(connection: SqlConnection): void {
+ this.dialog
+ .open(SqlQueryDialog, { data: connection, maxWidth: '96vw' })
+ .afterClosed()
+ .subscribe((result) => {
+ if (!result) return;
+ const table = connection.addQuery(result.name, result.query);
+ this.useTable({ table });
+ });
+ }
+
+ drawRegions(connection: PdfConnection): void {
+ const fieldNames = [...new Set(this.store.targets().flatMap((target) => target.fields.map((field) => field.name)))].sort();
+ this.dialog
+ .open(PdfRegionsDialog, {
+ data: { connection, fieldNames },
+ width: '1280px',
+ maxWidth: '98vw',
+ autoFocus: false,
+ // Drawn regions are real work: Escape (which also dismisses the
+ // name autocomplete) must not discard them; only "Cancelar" does.
+ disableClose: true,
+ })
+ .afterClosed()
+ .subscribe((result) => {
+ if (!result) return;
+ const table = connection.addRegions(result.name, result.regions);
+ this.useTable({ table });
+ });
+ }
+
+ async validateAll(): Promise {
+ this.validatingAll.set(true);
+ await this.store.validateAll();
+ this.validatingAll.set(false);
+ const { errors } = this.store.summary();
+ this.snackBar.open(errors ? `Validación terminada: ${errors} fila(s) con errores.` : 'Validación terminada: sin errores.', 'OK', {
+ duration: 4000,
+ });
+ }
+
+ openLoad(): void {
+ this.dialog
+ .open(LoadDialog, { width: '920px', maxWidth: '96vw', injector: this.injector, autoFocus: false })
+ .afterClosed()
+ .subscribe((result) => result === 'explore' && this.openExplorer());
+ }
+
+ openExplorer(initial?: string): void {
+ const flow = this.store.selectedFlow();
+ this.dialog.open(DatabaseExplorerDialog, {
+ injector: this.injector,
+ width: '1280px',
+ maxWidth: '98vw',
+ data: { targets: this.store.targets(), initial: initial ?? flow?.target.key },
+ });
+ }
+}
diff --git a/src/app/connect/components/connections-panel/connections-panel.html b/src/app/connect/components/connections-panel/connections-panel.html
new file mode 100644
index 0000000..ad44d52
--- /dev/null
+++ b/src/app/connect/components/connections-panel/connections-panel.html
@@ -0,0 +1,154 @@
+
+
+
+ @if (store.connections().length === 0) {
+
+
+
+ storage Conectar una base de datos
+
+
+ } @else {
+
+ @for (connection of store.connections(); track connection.id) {
+
+
+
+ @if (connection.error(); as error) {
+ {{ error }}
+ }
+
+
+ @for (table of connection.tables(); track table.id) {
+
+
{{ table.icon }}
+
+ {{ table.name }}
+ {{ table.kindLabel }}
+
+ @if (flowCount(table); as count) {
+
{{ count }}
+ }
+
+ arrow_forward
+
+ @if (table.removable) {
+
+ close
+
+ }
+
+ {{ table.icon }} {{ table.label }}
+
+
+
+ } @empty {
+ @if (connection.state() === 'ready') {
+
+ Sin tablas.
+
+ }
+ }
+
+
+ }
+
+ }
+
+
+
+
+ Arrastra una tabla de origen sobre una entidad para mapearla directamente.
+
+ @for (target of store.targets(); track target.key) {
+
+ table_chart
+
+ {{ target.table }}
+ @if (store.flowsByTarget().get(target.key); as count) {
+ {{ count }}
+ }
+
+
+ {{ target.fields.length }} campos@if (target.conflict_fields) { · clave {{ target.conflict_fields.join(', ') }} }
+
+
+ }
+
+
diff --git a/src/app/connect/components/connections-panel/connections-panel.scss b/src/app/connect/components/connections-panel/connections-panel.scss
new file mode 100644
index 0000000..2b41982
--- /dev/null
+++ b/src/app/connect/components/connections-panel/connections-panel.scss
@@ -0,0 +1,217 @@
+:host {
+ display: block;
+}
+
+.pane__header {
+ align-items: center;
+ display: flex;
+ justify-content: space-between;
+ padding: var(--space-3) var(--space-3) var(--space-1) var(--space-4);
+
+ h2 {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-large);
+ letter-spacing: 0.08em;
+ margin: 0;
+ text-transform: uppercase;
+ }
+}
+
+.pane__caption,
+.pane__hint {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.pane__hint {
+ margin: 0 var(--space-4) var(--space-2);
+}
+
+.pane__empty {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ padding: var(--space-2) var(--space-4) var(--space-4);
+}
+
+.pane__db-button {
+ align-self: stretch;
+}
+
+.connections {
+ display: block;
+ padding: 0 var(--space-2) var(--space-3);
+}
+
+.connection {
+ --mat-expansion-container-background-color: transparent;
+ --mat-expansion-header-collapsed-state-height: 56px;
+ --mat-expansion-header-expanded-state-height: 56px;
+ box-shadow: none !important;
+}
+
+.connection__header {
+ padding: 0 var(--space-2) 0 var(--space-3);
+}
+
+.connection__header ::ng-deep .mat-content {
+ align-items: center;
+ gap: var(--space-2);
+ overflow: hidden;
+}
+
+.connection__icon {
+ color: var(--mat-sys-primary);
+ flex: none;
+}
+
+.connection__text {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.connection__label {
+ font: var(--mat-sys-title-small);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.connection__type {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.connection__error-icon,
+.connection__error {
+ color: var(--mat-sys-error);
+}
+
+.connection__error {
+ font: var(--mat-sys-body-small);
+ margin: 0 0 var(--space-2);
+}
+
+.connection ::ng-deep .mat-expansion-panel-body {
+ padding: 0 0 var(--space-2) var(--space-6);
+}
+
+.tables__empty {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ margin: 0;
+ padding: var(--space-1) var(--space-2);
+}
+
+.table-item {
+ align-items: center;
+ border-radius: var(--mat-sys-corner-small);
+ cursor: grab;
+ display: flex;
+ gap: var(--space-2);
+ min-height: 40px;
+ padding: 0 0 0 var(--space-2);
+
+ &:hover {
+ background: var(--mat-sys-surface-container-high);
+ }
+
+ &:active {
+ cursor: grabbing;
+ }
+}
+
+.table-item--placeholder {
+ background: var(--mat-sys-surface-container-highest);
+ opacity: 0.6;
+}
+
+.table-item__icon {
+ color: var(--mat-sys-on-surface-variant);
+ flex: none;
+ font-size: 20px;
+ height: 20px;
+ width: 20px;
+}
+
+.table-item__text {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ line-height: 1.2;
+ min-width: 0;
+}
+
+.table-item__name {
+ font: var(--mat-sys-body-medium);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.table-item__kind {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.target-item__title {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+}
+
+.table-item__flows,
+.target-item__flows {
+ background: var(--mat-sys-primary);
+ border-radius: 999px;
+ color: var(--mat-sys-on-primary);
+ font: var(--mat-sys-label-small);
+ min-width: 20px;
+ padding: 2px 6px;
+ text-align: center;
+}
+
+.table-item__action {
+ --mat-icon-button-state-layer-size: 32px;
+ flex: none;
+ height: 32px;
+ opacity: 0.55;
+ padding: 4px;
+ width: 32px;
+
+ mat-icon {
+ font-size: 18px;
+ height: 18px;
+ width: 18px;
+ }
+}
+
+.table-item:hover .table-item__action {
+ opacity: 1;
+}
+
+.targets {
+ padding-top: 0;
+}
+
+.target-item {
+ border-radius: var(--mat-sys-corner-small);
+ margin: 0 var(--space-2);
+ transition: background-color 0.12s ease, outline-color 0.12s ease;
+ width: auto !important;
+}
+
+.target-item.cdk-drop-list-receiving {
+ outline: 1px dashed var(--mat-sys-primary);
+}
+
+.target-item.cdk-drop-list-dragging {
+ background: var(--mat-sys-primary-container);
+ outline: 2px solid var(--mat-sys-primary);
+}
+
+.target-item ::ng-deep .cdk-drag-placeholder {
+ display: none;
+}
diff --git a/src/app/connect/components/connections-panel/connections-panel.ts b/src/app/connect/components/connections-panel/connections-panel.ts
new file mode 100644
index 0000000..177f858
--- /dev/null
+++ b/src/app/connect/components/connections-panel/connections-panel.ts
@@ -0,0 +1,86 @@
+import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop';
+import { Component, inject, output } from '@angular/core';
+import { MatSnackBar } from '@angular/material/snack-bar';
+import { MatBadgeModule } from '@angular/material/badge';
+import { MatButtonModule } from '@angular/material/button';
+import { MatDividerModule } from '@angular/material/divider';
+import { MatExpansionModule } from '@angular/material/expansion';
+import { MatIconModule } from '@angular/material/icon';
+import { MatListModule } from '@angular/material/list';
+import { MatMenuModule } from '@angular/material/menu';
+import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { TargetMeta } from '../../api/api.types';
+import { DataConnection, SourceTable } from '../../domain/data-source';
+import { PdfConnection } from '../../domain/pdf-source';
+import { SqlConnection } from '../../domain/sql-source';
+import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
+import { FileDropzone } from '../file-dropzone/file-dropzone';
+
+/** Payload of a "use this table" request: a table, optionally already aimed at an entity. */
+export interface TableUse {
+ table: SourceTable;
+ target?: TargetMeta;
+}
+
+/**
+ * The workspace's left pane: every
+ * connection with its tables (drag a table onto the canvas, or straight
+ * onto a destination entity below, to create a flow) and the destination
+ * schema of the current domain, with how many flows feed each entity.
+ */
+@Component({
+ selector: 'app-connections-panel',
+ imports: [
+ DragDropModule,
+ FileDropzone,
+ MatBadgeModule,
+ MatButtonModule,
+ MatDividerModule,
+ MatExpansionModule,
+ MatIconModule,
+ MatListModule,
+ MatMenuModule,
+ MatProgressSpinnerModule,
+ MatTooltipModule,
+ ],
+ templateUrl: './connections-panel.html',
+ styleUrl: './connections-panel.scss',
+})
+export class ConnectionsPanel {
+ readonly store = inject(ConnectWorkspaceStore);
+ private readonly snackBar = inject(MatSnackBar);
+
+ readonly addConnection = output();
+ readonly useTable = output();
+ readonly addQuery = output();
+ readonly drawRegions = output();
+
+ /** Table lists are drag *sources* only. */
+ readonly nothingEnters = () => false;
+ readonly onlyTables = (drag: CdkDrag) => drag.data instanceof SourceTable;
+
+ isSql(connection: DataConnection): connection is SqlConnection {
+ return connection instanceof SqlConnection;
+ }
+
+ isPdf(connection: DataConnection): connection is PdfConnection {
+ return connection instanceof PdfConnection;
+ }
+
+ flowCount(table: SourceTable): number {
+ return this.store.flowsOf(table).length;
+ }
+
+ onFilesDropped(files: File[]): void {
+ const rejected = this.store.addFiles(files);
+ if (rejected.length) {
+ this.snackBar.open(`Formato no soportado: ${rejected.map((file) => file.name).join(', ')}`, 'OK', { duration: 5000 });
+ }
+ }
+
+ onDropOnTarget(event: CdkDragDrop): void {
+ const table = event.item.data;
+ if (table instanceof SourceTable) this.useTable.emit({ table, target: event.container.data });
+ }
+}
diff --git a/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html
new file mode 100644
index 0000000..85e206d
--- /dev/null
+++ b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.html
@@ -0,0 +1,138 @@
+
+ @if (view() !== 'catalog') {
+
+ arrow_back
+
+ }
+ {{ view() === 'catalog' ? 'Obtener datos' : entry()?.name }}
+
+
+
+ @switch (view()) {
+ @case ('catalog') {
+
+
+ @for (item of visibleCategories(); track item.id) {
+
+ {{ item.icon }}
+ {{ item.label }}
+
+ }
+
+
+
+
+ search
+ Buscar conector
+
+
+
+ @if (catalogError(); as error) {
+ error {{ error }}
+ }
+
+ @for (item of visibleEntries(); track item.id) {
+
+ {{ item.icon }}
+ {{ item.name }}
+ {{ item.description }}
+
+ } @empty {
+
Ningún conector coincide con la búsqueda.
+ }
+
+
+
+ }
+
+ @case ('files') {
+
+ @switch (entry()?.connector?.kind) {
+ @case ('document') {
+ Agrega todos los documentos juntos: reportes, formatos o notas en PDF o imagen. Se separan por paciente aunque
+ uno ocupe varias páginas o varios archivos, y los campos se extraen del texto, incluido el texto libre.
+ }
+ @case ('edf') {
+ Agrega todos los registros juntos; cada archivo será una fila con los datos del estudio y el archivo original.
+ }
+ @default {
+ Puedes agregar varios archivos a la vez; cada uno se convierte en una conexión y sus tablas (las hojas de un
+ libro de Excel, las tablas de un PDF) quedan disponibles para mapear.
+ }
+ }
+
+
+ }
+
+ @case ('database') {
+
+ Solo lectura: la conexión se abre en modo de solo lectura y únicamente se permiten consultas SELECT.
+
+ @if (engine() === 'url') {
+
+ } @else {
+
+ }
+
+ @if (testing()) {
+
+ }
+ @if (testResult(); as result) {
+
+ {{ result.ok ? 'check_circle' : 'error' }} {{ result.message }}
+
+ }
+ }
+ }
+
+
+
+ Cancelar
+ @if (view() === 'files') {
+
+ Conectar {{ files().length > 1 ? files().length + ' archivos' : '' }}
+
+ }
+ @if (view() === 'database') {
+
+ network_check Probar conexión
+
+ Conectar
+ }
+
diff --git a/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss
new file mode 100644
index 0000000..463b96f
--- /dev/null
+++ b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.scss
@@ -0,0 +1,120 @@
+.gallery__title {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+}
+
+.gallery__content {
+ min-height: 420px;
+}
+
+.gallery {
+ display: grid;
+ gap: var(--space-4);
+ grid-template-columns: 200px 1fr;
+}
+
+.gallery__categories {
+ border-right: 1px solid var(--mat-sys-outline-variant);
+ padding-right: var(--space-2);
+}
+
+.gallery__search {
+ width: 100%;
+}
+
+.gallery__grid {
+ display: grid;
+ gap: var(--space-3);
+ grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
+ margin-top: var(--space-3);
+}
+
+.connector-card {
+ align-items: flex-start;
+ background: var(--mat-sys-surface);
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ color: var(--mat-sys-on-surface);
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ font: inherit;
+ gap: var(--space-1);
+ min-height: 118px;
+ padding: var(--space-4);
+ position: relative;
+ text-align: left;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+
+ &:hover,
+ &:focus-visible {
+ border-color: var(--mat-sys-primary);
+ box-shadow: var(--mat-sys-level1);
+ outline: none;
+ }
+}
+
+.connector-card__icon {
+ color: var(--mat-sys-primary);
+ margin-bottom: var(--space-1);
+}
+
+.connector-card__name {
+ font: var(--mat-sys-title-small);
+}
+
+.connector-card__description {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.gallery__hint {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-medium);
+ margin: 0 0 var(--space-4);
+ max-width: 720px;
+}
+
+.gallery__empty {
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.db-form {
+ display: grid;
+ gap: 0 var(--space-4);
+ grid-template-columns: 1fr 1fr;
+}
+
+.db-form__wide {
+ grid-column: 1 / -1;
+}
+
+.db-test {
+ align-items: center;
+ color: var(--mat-sys-primary);
+ display: flex;
+ gap: var(--space-2);
+ margin: var(--space-3) 0 0;
+
+ &.db-test--error {
+ color: var(--mat-sys-error);
+ }
+}
+
+@media (max-width: 720px) {
+ .gallery {
+ grid-template-columns: 1fr;
+ }
+ .gallery__categories {
+ border-right: 0;
+ }
+ .db-form {
+ grid-template-columns: 1fr;
+ }
+}
+
+.connector-card:disabled {
+ cursor: not-allowed;
+ opacity: 0.55;
+}
diff --git a/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts
new file mode 100644
index 0000000..3151669
--- /dev/null
+++ b/src/app/connect/components/connector-gallery-dialog/connector-gallery-dialog.ts
@@ -0,0 +1,172 @@
+import { Component, computed, inject, signal } from '@angular/core';
+import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
+import { MatButtonModule } from '@angular/material/button';
+import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
+import { MatFormFieldModule } from '@angular/material/form-field';
+import { MatIconModule } from '@angular/material/icon';
+import { MatInputModule } from '@angular/material/input';
+import { MatListModule } from '@angular/material/list';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatRippleModule } from '@angular/material/core';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { toSignal } from '@angular/core/rxjs-interop';
+import { catchError, of } from 'rxjs';
+import { ConnectorInfo, SqlConnectionRef, SqlEngineInfo, apiErrorMessage } from '../../api/api.types';
+import { ConnectorsApi } from '../../api/connectors.api';
+import { SourceGateway } from '../../api/source-gateway';
+import { connectionsFor } from '../../domain/connection-registry';
+import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
+import { DataConnection } from '../../domain/data-source';
+import { SqlConnection } from '../../domain/sql-source';
+import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
+import { FileDropzone } from '../file-dropzone/file-dropzone';
+
+type View = 'catalog' | 'files' | 'database';
+
+/**
+ * "Obtener datos": pick a connector from the gallery (as reported by the
+ * server), then drop files or fill a database connection form. Closes
+ * with the new, not yet loaded, `DataConnection`s.
+ */
+@Component({
+ selector: 'app-connector-gallery-dialog',
+ imports: [
+ FileDropzone,
+ MatButtonModule,
+ MatDialogModule,
+ MatFormFieldModule,
+ MatIconModule,
+ MatInputModule,
+ MatListModule,
+ MatProgressBarModule,
+ MatRippleModule,
+ MatTooltipModule,
+ ReactiveFormsModule,
+ ],
+ templateUrl: './connector-gallery-dialog.html',
+ styleUrl: './connector-gallery-dialog.scss',
+})
+export class ConnectorGalleryDialog {
+ private readonly dialogRef = inject>(MatDialogRef);
+ private readonly gateway = inject(SourceGateway);
+ private readonly formBuilder = inject(FormBuilder);
+
+ readonly categories = GALLERY_CATEGORIES;
+ readonly category = signal('all');
+ readonly search = signal('');
+ readonly view = signal('catalog');
+ readonly entry = signal(null);
+ readonly catalogError = signal(null);
+
+ private readonly connectors = toSignal(
+ inject(ConnectorsApi)
+ .list()
+ .pipe(
+ catchError((error) => {
+ this.catalogError.set(apiErrorMessage(error, 'No se pudo consultar los conectores del servidor.'));
+ return of([] as ConnectorInfo[]);
+ }),
+ ),
+ { initialValue: [] as ConnectorInfo[] },
+ );
+ private readonly entries = computed(() => galleryEntries(this.connectors()));
+
+ readonly visibleEntries = computed(() => {
+ const term = this.search().trim().toLowerCase();
+ return this.entries().filter(
+ (entry) =>
+ (this.category() === 'all' || entry.category === this.category()) &&
+ (!term || entry.name.toLowerCase().includes(term) || entry.description.toLowerCase().includes(term)),
+ );
+ });
+ readonly visibleCategories = computed(() =>
+ this.categories.filter((c) => c.id === 'all' || this.entries().some((entry) => entry.category === c.id)),
+ );
+
+ // -- files --
+ readonly files = signal([]);
+
+ // -- database --
+ readonly serverForm = this.formBuilder.nonNullable.group({
+ host: ['', Validators.required],
+ port: [null as number | null],
+ database: ['', Validators.required],
+ user: [''],
+ password: [''],
+ });
+ readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
+ readonly testing = signal(false);
+ readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
+
+ readonly engine = computed(() => this.entry()?.engine ?? null);
+ readonly serverEngine = computed(() => {
+ const engine = this.engine();
+ return engine && engine !== 'url' ? engine : null;
+ });
+
+ pick(entry: GalleryEntry): void {
+ if (!entry.available) return;
+ this.entry.set(entry);
+ this.testResult.set(null);
+ this.view.set(entry.engine ? 'database' : 'files');
+ }
+
+ back(): void {
+ this.view.set('catalog');
+ this.files.set([]);
+ }
+
+ onSearch(event: Event): void {
+ this.search.set((event.target as HTMLInputElement).value);
+ }
+
+ testConnection(): void {
+ const ref = this.connectionRef();
+ if (!ref) return;
+ this.testing.set(true);
+ this.testResult.set(null);
+ this.gateway.sql.testConnection(ref).subscribe({
+ next: (response) => {
+ this.testing.set(false);
+ this.testResult.set({ ok: true, message: `Conexión correcta (${response.dialect}).` });
+ },
+ error: (error) => {
+ this.testing.set(false);
+ this.testResult.set({ ok: false, message: apiErrorMessage(error, 'No se pudo conectar.') });
+ },
+ });
+ }
+
+ connectFiles(): void {
+ const entry = this.entry();
+ if (entry) this.dialogRef.close(connectionsFor(entry.connector.kind, this.files()));
+ }
+
+ connectDatabase(): void {
+ const ref = this.connectionRef();
+ if (!ref) return;
+ this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
+ }
+
+ get databaseFormInvalid(): boolean {
+ return this.engine() === 'url' ? this.urlForm.invalid : this.serverForm.invalid;
+ }
+
+ private connectionRef(): SqlConnectionRef | null {
+ const engine = this.engine();
+ if (!engine) return null;
+ if (engine === 'url') {
+ this.urlForm.markAllAsTouched();
+ return this.urlForm.valid ? { connection_string: this.urlForm.getRawValue().url.trim() } : null;
+ }
+ this.serverForm.markAllAsTouched();
+ if (this.serverForm.invalid) return null;
+ return { server: { engine: engine.id, ...this.serverForm.getRawValue() } };
+ }
+
+ private connectionLabel(): string {
+ const engine = this.engine();
+ if (engine === 'url') return describeSqlUrl(this.urlForm.getRawValue().url);
+ return describeSqlServer({ engine: engine as SqlEngineInfo, ...this.serverForm.getRawValue() });
+ }
+}
diff --git a/src/app/connect/components/data-grid/data-grid.html b/src/app/connect/components/data-grid/data-grid.html
new file mode 100644
index 0000000..ac44fd5
--- /dev/null
+++ b/src/app/connect/components/data-grid/data-grid.html
@@ -0,0 +1,82 @@
+@let f = flow();
+
+
+ table_chart Destino
+ input Origen
+
+ @if (view() === 'target') {
+
+ Solo filas con errores
+
+ }
+
+ Muestra de {{ shownOf().shown }}@if (shownOf().total !== null) { de {{ shownOf().total }} } filas
+ @if (view() === 'target' && !f.validation()) {
+ · valida el flujo para ver la calidad de cada campo
+ }
+
+
+
+@if (columns().length === 0) {
+
+ @if (view() === 'target') {
+ Aún no hay campos asignados — mapea columnas en la pestaña «Mapeo».
+ } @else {
+ La fuente no tiene columnas.
+ }
+
+} @else {
+
+}
diff --git a/src/app/connect/components/data-grid/data-grid.scss b/src/app/connect/components/data-grid/data-grid.scss
new file mode 100644
index 0000000..733a5b5
--- /dev/null
+++ b/src/app/connect/components/data-grid/data-grid.scss
@@ -0,0 +1,146 @@
+:host {
+ display: block;
+}
+
+.grid-toolbar {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+ margin-bottom: var(--space-3);
+
+ mat-button-toggle mat-icon {
+ font-size: 18px;
+ height: 18px;
+ margin-right: 4px;
+ vertical-align: middle;
+ width: 18px;
+ }
+}
+
+.grid-toolbar__caption,
+.grid-empty {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.grid-empty {
+ padding: var(--space-4);
+}
+
+.grid-scroll {
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ max-height: 62vh;
+ overflow: auto;
+}
+
+.grid {
+ --mat-table-row-item-container-height: 36px;
+ --mat-table-header-container-height: 64px;
+ min-width: 100%;
+ width: max-content;
+}
+
+.grid th,
+.grid td {
+ border-right: 1px solid var(--mat-sys-outline-variant);
+ max-width: 280px;
+ padding: 0 var(--space-3);
+}
+
+.grid__index {
+ background: var(--mat-sys-surface-container-low);
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-small);
+ text-align: right;
+ width: 48px;
+}
+
+.grid__index--error {
+ box-shadow: inset 3px 0 0 var(--mat-sys-error);
+ color: var(--mat-sys-error);
+}
+
+.grid__header {
+ background: var(--mat-sys-surface-container) !important;
+ vertical-align: top;
+ padding-top: var(--space-2) !important;
+ padding-bottom: var(--space-2) !important;
+}
+
+.grid__title {
+ align-items: center;
+ display: flex;
+ font-family: 'Roboto Mono', ui-monospace, monospace;
+ font-size: 12px;
+ font-weight: 600;
+ gap: 4px;
+ white-space: nowrap;
+
+ mat-icon {
+ color: var(--mat-sys-primary);
+ font-size: 16px;
+ height: 16px;
+ width: 16px;
+ }
+}
+
+.grid__subtitle {
+ color: var(--mat-sys-on-surface-variant);
+ display: block;
+ font: var(--mat-sys-body-small);
+ white-space: nowrap;
+}
+
+.quality {
+ border-radius: 2px;
+ display: flex;
+ height: 4px;
+ margin-top: 6px;
+ overflow: hidden;
+ width: 100%;
+}
+
+.quality__ok {
+ background: var(--mat-sys-primary);
+}
+
+.quality__bad {
+ background: var(--mat-sys-error);
+}
+
+.grid__cell {
+ align-items: center;
+ display: flex;
+ font: var(--mat-sys-body-small);
+ gap: 4px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ mat-icon {
+ flex: none;
+ font-size: 14px;
+ height: 14px;
+ width: 14px;
+ }
+}
+
+.grid__cell--error {
+ background: var(--mat-sys-error-container);
+ border-radius: 4px;
+ color: var(--mat-sys-on-error-container);
+ margin: 0 -6px;
+ padding: 2px 6px;
+}
+
+.grid__cell--default {
+ color: var(--mat-sys-primary);
+ font-style: italic;
+}
+
+.grid__cell--empty {
+ color: var(--mat-sys-outline);
+ font-style: italic;
+}
diff --git a/src/app/connect/components/data-grid/data-grid.ts b/src/app/connect/components/data-grid/data-grid.ts
new file mode 100644
index 0000000..6495000
--- /dev/null
+++ b/src/app/connect/components/data-grid/data-grid.ts
@@ -0,0 +1,118 @@
+import { Component, computed, input, signal } from '@angular/core';
+import { MatButtonToggleModule } from '@angular/material/button-toggle';
+import { MatIconModule } from '@angular/material/icon';
+import { MatSlideToggleModule } from '@angular/material/slide-toggle';
+import { MatTableModule } from '@angular/material/table';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { Row, RowError } from '../../api/api.types';
+import { ImportFlow } from '../../domain/import-flow';
+import { TypeIconPipe } from '../shared/type-icon.pipe';
+
+type GridView = 'target' | 'source';
+
+interface GridColumn {
+ id: string;
+ title: string;
+ subtitle: string | null;
+ type: string;
+ /** Destination view: source column feeding it; source view: the column itself. */
+ sourceColumn: string | null;
+ defaultValue: string | null;
+ errorRate: number | null;
+}
+
+interface GridRow {
+ index: number;
+ values: Row;
+ hasErrors: boolean;
+}
+
+/**
+ * The sample rows of one flow, Power Query-style: "Destino" shows them as
+ * they will land in the database (destination field names, defaults
+ * applied, cells that failed validation highlighted with the reason, a
+ * quality bar per field), "Origen" shows the raw source columns.
+ */
+@Component({
+ selector: 'app-data-grid',
+ imports: [MatButtonToggleModule, MatIconModule, MatSlideToggleModule, MatTableModule, MatTooltipModule, TypeIconPipe],
+ templateUrl: './data-grid.html',
+ styleUrl: './data-grid.scss',
+})
+export class DataGrid {
+ readonly flow = input.required();
+
+ readonly view = signal('target');
+ readonly onlyErrors = signal(false);
+
+ readonly columns = computed(() => {
+ const flow = this.flow();
+ if (this.view() === 'source') {
+ const bySource = flow.mapping.bySource();
+ return flow.sourceColumns().map((column) => ({
+ id: column.name,
+ title: column.name,
+ subtitle: bySource.get(column.name) ? `→ ${bySource.get(column.name)!.field}` : null,
+ type: column.inferred_type,
+ sourceColumn: column.name,
+ defaultValue: null,
+ errorRate: null,
+ }));
+ }
+ const byField = flow.mapping.byField();
+ const defaults = flow.defaults();
+ const quality = flow.quality();
+ return flow.target.fields
+ .filter((field) => byField.has(field.name) || defaults[field.name])
+ .map((field) => ({
+ id: field.name,
+ title: field.name,
+ subtitle: byField.get(field.name) ? `← ${byField.get(field.name)!.source}` : `= ${defaults[field.name]}`,
+ type: field.type,
+ sourceColumn: byField.get(field.name)?.source ?? null,
+ defaultValue: defaults[field.name] ?? null,
+ errorRate: quality.get(field.name)?.errorRate ?? null,
+ }));
+ });
+
+ readonly displayedColumns = computed(() => ['__row', ...this.columns().map((column) => column.id)]);
+
+ readonly rows = computed(() => {
+ const flow = this.flow();
+ const errors = flow.errorsByCell();
+ const erroredRows = new Set([...errors.keys()].map((key) => Number(key.split(':')[0])));
+ const rows = (flow.preview()?.sample_rows ?? []).map((values, index) => ({ index, values, hasErrors: erroredRows.has(index) }));
+ return this.onlyErrors() && this.view() === 'target' ? rows.filter((row) => row.hasErrors) : rows;
+ });
+
+ readonly shownOf = computed(() => {
+ const flow = this.flow();
+ return { shown: flow.preview()?.sample_rows.length ?? 0, total: flow.totalRows() };
+ });
+
+ cell(row: GridRow, column: GridColumn): { text: string; isDefault: boolean; isEmpty: boolean } {
+ const raw = column.sourceColumn ? row.values[column.sourceColumn] : null;
+ const blank = raw === null || raw === undefined || String(raw).trim() === '';
+ if (blank && column.defaultValue) return { text: column.defaultValue, isDefault: true, isEmpty: false };
+ return { text: blank ? 'null' : displayValue(raw), isDefault: false, isEmpty: blank };
+ }
+
+ errors(row: GridRow, column: GridColumn): RowError[] {
+ if (this.view() !== 'target') return [];
+ return this.flow().errorsByCell().get(`${row.index}:${column.id}`) ?? [];
+ }
+
+ errorText(errors: RowError[]): string {
+ return errors.map((error) => error.message).join('\n');
+ }
+
+ qualityPercent(rate: number): number {
+ return Math.round((1 - rate) * 100);
+ }
+}
+
+/** Excel/SQL dates arrive as midnight timestamps ("2024-01-10T00:00:00"); show them as plain dates. */
+function displayValue(value: unknown): string {
+ const text = String(value);
+ return /^\d{4}-\d{2}-\d{2}T00:00:00$/.test(text) ? text.slice(0, 10) : text;
+}
diff --git a/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html
new file mode 100644
index 0000000..288c88b
--- /dev/null
+++ b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.html
@@ -0,0 +1,61 @@
+
+ travel_explore Explorar la base de datos
+ refresh
+
+
+
+ @for (target of data.targets; track target.key) {
+
+ table_chart
+ {{ target.table }}
+
+ @if (totals().get(target.key); as total) {
+ {{ total | number }} filas
+ } @else if (totals().has(target.key)) {
+ {{ totals().get(target.key) === 0 ? 'vacía' : 'no disponible' }}
+ } @else {
+ …
+ }
+
+
+ }
+
+
+
+ @if (loading()) {
+
+ }
+ @if (error(); as message) {
+ {{ message }}
+ }
+ @if (page(); as p) {
+ @if (p.rows.length === 0) {
+ La tabla está vacía.
+ } @else {
+
+
+ }
+ }
+
+
+
+ Cerrar
+
diff --git a/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss
new file mode 100644
index 0000000..3c29817
--- /dev/null
+++ b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.scss
@@ -0,0 +1,76 @@
+.explorer__title {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+
+ button {
+ margin-left: auto;
+ }
+}
+
+.explorer {
+ display: grid;
+ gap: var(--space-4);
+ grid-template-columns: 240px minmax(0, 1fr);
+ height: 70vh;
+}
+
+.explorer__tables {
+ border-right: 1px solid var(--mat-sys-outline-variant);
+ overflow: auto;
+}
+
+.explorer__rows {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.explorer__scroll {
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ flex: 1;
+ overflow: auto;
+}
+
+.explorer__table {
+ --mat-table-row-item-container-height: 36px;
+ width: max-content;
+ min-width: 100%;
+
+ th,
+ td {
+ border-right: 1px solid var(--mat-sys-outline-variant);
+ font-size: 12px;
+ max-width: 260px;
+ overflow: hidden;
+ padding: 0 var(--space-3);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ th {
+ font-family: 'Roboto Mono', ui-monospace, monospace;
+ }
+}
+
+.explorer__null {
+ color: var(--mat-sys-outline);
+ font-style: italic;
+}
+
+.explorer__empty,
+.explorer__error {
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.explorer__error {
+ color: var(--mat-sys-error);
+}
+
+@media (max-width: 800px) {
+ .explorer {
+ grid-template-columns: 1fr;
+ height: auto;
+ }
+}
diff --git a/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts
new file mode 100644
index 0000000..cd1d879
--- /dev/null
+++ b/src/app/connect/components/database-explorer-dialog/database-explorer-dialog.ts
@@ -0,0 +1,96 @@
+import { DecimalPipe } from '@angular/common';
+import { Component, OnInit, computed, inject, signal } from '@angular/core';
+import { forkJoin, of } from 'rxjs';
+import { catchError, map } from 'rxjs/operators';
+import { MatButtonModule } from '@angular/material/button';
+import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
+import { MatIconModule } from '@angular/material/icon';
+import { MatListModule } from '@angular/material/list';
+import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatTableModule } from '@angular/material/table';
+import { DataPage, TargetMeta, apiErrorMessage } from '../../api/api.types';
+import { DataApi } from '../../api/data.api';
+
+export interface DatabaseExplorerData {
+ targets: TargetMeta[];
+ initial?: string;
+}
+
+/**
+ * Read-only view of what's stored in the destination database, table by
+ * table, paged server-side through the backend's Repository. The "Vista de
+ * datos" to confirm a load landed as expected.
+ */
+@Component({
+ selector: 'app-database-explorer-dialog',
+ imports: [DecimalPipe, MatButtonModule, MatDialogModule, MatIconModule, MatListModule, MatPaginatorModule, MatProgressBarModule, MatTableModule],
+ templateUrl: './database-explorer-dialog.html',
+ styleUrl: './database-explorer-dialog.scss',
+})
+export class DatabaseExplorerDialog implements OnInit {
+ readonly data = inject(MAT_DIALOG_DATA);
+ private readonly api = inject(DataApi);
+
+ readonly totals = signal>(new Map());
+ readonly selected = signal(null);
+ readonly page = signal(null);
+ readonly pageIndex = signal(0);
+ readonly pageSize = signal(25);
+ readonly loading = signal(false);
+ readonly error = signal(null);
+
+ /** Table order from the backend (keys and FKs first), not the alphabetical order JSON objects arrive in. */
+ readonly allColumns = computed(() => this.page()?.columns ?? []);
+
+ ngOnInit(): void {
+ forkJoin(
+ this.data.targets.map((target) =>
+ this.api.page(target.key, 1, 0).pipe(
+ map((page) => [target.key, page.total] as const),
+ catchError(() => of([target.key, null] as const)),
+ ),
+ ),
+ ).subscribe((entries) => this.totals.set(new Map(entries)));
+ const initial = this.data.targets.find((target) => target.key === this.data.initial) ?? this.data.targets[0];
+ if (initial) this.open(initial);
+ }
+
+ open(target: TargetMeta): void {
+ this.selected.set(target);
+ this.pageIndex.set(0);
+ this.fetch();
+ }
+
+ onPage(event: PageEvent): void {
+ this.pageIndex.set(event.pageIndex);
+ this.pageSize.set(event.pageSize);
+ this.fetch();
+ }
+
+ refresh(): void {
+ this.ngOnInit();
+ }
+
+ display(value: unknown): string {
+ if (value === null || value === undefined) return 'null';
+ return String(value);
+ }
+
+ private fetch(): void {
+ const target = this.selected();
+ if (!target) return;
+ this.loading.set(true);
+ this.error.set(null);
+ this.api.page(target.key, this.pageSize(), this.pageIndex() * this.pageSize()).subscribe({
+ next: (page) => {
+ this.loading.set(false);
+ this.page.set(page);
+ },
+ error: (error) => {
+ this.loading.set(false);
+ this.error.set(apiErrorMessage(error, 'No se pudo leer la tabla.'));
+ },
+ });
+ }
+}
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
new file mode 100644
index 0000000..a98e60a
--- /dev/null
+++ b/src/app/connect/components/document-review-dialog/document-review-dialog.html
@@ -0,0 +1,184 @@
+Revisar extracción · {{ target.domain.toUpperCase() }} {{ target.table }}
+
+
+
+
+
+ @if (extracting()) {
+
+ Leyendo documentos; las páginas escaneadas pasan por OCR y pueden tardar.
+ }
+ @if (error(); as message) {
+ error {{ message }}
+ }
+
+ @if (selected(); as record) {
+
+
+
+
+ @if (record.images.length) {
+ Imágenes en sus páginas
+
+ @for (image of record.images; track $index) {
+
+ @if (thumbnails()[thumbnailKey(image)]; as url) {
+
+ } @else {
+ image
+ }
+ {{ image.kind === 'scan' ? 'Escaneo' : 'Imagen' }} · p. {{ image.page_number }}
+
+ }
+
+ }
+
+ @if (page(); as shown) {
+ {{ shown.document }} · página {{ shown.page }}
+ @if (shown.url) {
+
+ } @else {
+
+ }
+ }
+ }
+
+
+
+
+ Cancelar
+
+ Aplicar
+
+
diff --git a/src/app/connect/components/document-review-dialog/document-review-dialog.scss b/src/app/connect/components/document-review-dialog/document-review-dialog.scss
new file mode 100644
index 0000000..8a24dc5
--- /dev/null
+++ b/src/app/connect/components/document-review-dialog/document-review-dialog.scss
@@ -0,0 +1,228 @@
+.review {
+ display: grid;
+ gap: var(--space-4);
+ grid-template-columns: minmax(240px, 300px) minmax(0, 1fr);
+ max-height: 78vh;
+}
+
+.review__side {
+ border-right: 1px solid var(--mat-sys-outline-variant);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ overflow-y: auto;
+ padding-right: var(--space-3);
+}
+
+.settings {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+}
+
+.records__header {
+ align-items: baseline;
+ display: flex;
+ font: var(--mat-sys-label-large);
+ justify-content: space-between;
+}
+
+.records__review,
+.records__warn {
+ color: var(--mat-sys-error);
+}
+
+.records__empty,
+.review__hint {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-medium);
+}
+
+.review__main {
+ min-width: 0;
+ overflow-y: auto;
+}
+
+.review__error {
+ align-items: center;
+ color: var(--mat-sys-error);
+ display: flex;
+ gap: var(--space-2);
+}
+
+.record__header {
+ align-items: baseline;
+ display: flex;
+ gap: var(--space-3);
+ justify-content: space-between;
+
+ h3 {
+ font: var(--mat-sys-title-medium);
+ margin: 0;
+ }
+}
+
+.record__confidence {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-medium);
+}
+
+.record__confidence--low {
+ color: var(--mat-sys-error);
+}
+
+.record__subtitle {
+ font: var(--mat-sys-title-small);
+ margin: var(--space-4) 0 var(--space-2);
+}
+
+.fields {
+ border-collapse: collapse;
+ margin-top: var(--space-3);
+ width: 100%;
+
+ th,
+ td {
+ border-bottom: 1px solid var(--mat-sys-outline-variant);
+ padding: var(--space-1) var(--space-2);
+ text-align: left;
+ vertical-align: middle;
+ }
+
+ thead th {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-medium);
+ }
+}
+
+.fields__name {
+ font: var(--mat-sys-body-small);
+ font-family: var(--font-mono, monospace);
+ white-space: nowrap;
+}
+
+.fields__required {
+ color: var(--mat-sys-error);
+ margin-left: 2px;
+}
+
+.fields__row--missing .fields__input {
+ border-color: var(--mat-sys-error);
+}
+
+.fields__value {
+ min-width: 180px;
+}
+
+.fields__input {
+ background: transparent;
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-extra-small);
+ color: inherit;
+ font: var(--mat-sys-body-medium);
+ padding: 4px 8px;
+ width: 100%;
+
+ &:focus {
+ border-color: var(--mat-sys-primary);
+ outline: none;
+ }
+}
+
+.fields__input--edited {
+ background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
+}
+
+.fields__conflict {
+ align-items: center;
+ color: var(--mat-sys-error);
+ display: inline-flex;
+ font: var(--mat-sys-label-small);
+ gap: 2px;
+
+ mat-icon {
+ font-size: 16px;
+ height: 16px;
+ width: 16px;
+ }
+}
+
+.fields__confidence {
+ min-width: 120px;
+
+ mat-progress-bar.low {
+ --mat-progress-bar-active-indicator-color: var(--mat-sys-error);
+ }
+}
+
+.method {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-small);
+}
+
+.method--manual {
+ color: var(--mat-sys-primary);
+}
+
+.evidence {
+ align-items: flex-start;
+ display: flex;
+ flex-direction: column;
+ height: auto;
+ max-width: 340px;
+ padding: 2px 6px;
+ text-align: left;
+}
+
+.evidence__line {
+ font: var(--mat-sys-body-small);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ width: 100%;
+}
+
+.evidence__where {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-label-small);
+}
+
+.images {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+}
+
+.image {
+ align-items: center;
+ background: var(--mat-sys-surface-container-low);
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-small);
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ font: var(--mat-sys-label-small);
+ gap: var(--space-1);
+ padding: var(--space-2);
+
+ img {
+ max-height: 120px;
+ max-width: 160px;
+ }
+}
+
+.page {
+ border: 1px solid var(--mat-sys-outline-variant);
+ max-width: 100%;
+}
+
+@media (max-width: 900px) {
+ .review {
+ grid-template-columns: 1fr;
+ }
+
+ .review__side {
+ border-right: none;
+ padding-right: 0;
+ }
+}
diff --git a/src/app/connect/components/document-review-dialog/document-review-dialog.ts b/src/app/connect/components/document-review-dialog/document-review-dialog.ts
new file mode 100644
index 0000000..52344f0
--- /dev/null
+++ b/src/app/connect/components/document-review-dialog/document-review-dialog.ts
@@ -0,0 +1,208 @@
+import { PercentPipe } from '@angular/common';
+import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
+import { FormsModule } from '@angular/forms';
+import { MatButtonModule } from '@angular/material/button';
+import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
+import { MatFormFieldModule } from '@angular/material/form-field';
+import { MatIconModule } from '@angular/material/icon';
+import { MatInputModule } from '@angular/material/input';
+import { MatListModule } from '@angular/material/list';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatSelectModule } from '@angular/material/select';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import {
+ DocumentFieldSpec,
+ DocumentImage,
+ DocumentSettings,
+ ExtractedField,
+ ExtractedRecord,
+ SegmentationInfo,
+ TargetMeta,
+ apiErrorMessage,
+} from '../../api/api.types';
+import { SourceGateway } from '../../api/source-gateway';
+import { DocumentTable, FieldOverrides } from '../../domain/document-source';
+
+export interface DocumentReviewData {
+ table: DocumentTable;
+ target: TargetMeta;
+ segmentations: SegmentationInfo[];
+}
+
+const METHOD_LABELS: Record = {
+ etiqueta: 'Etiqueta',
+ patron: 'Patrón',
+ texto_libre: 'Texto libre',
+ manual: 'Manual',
+};
+
+const REVIEW_BELOW = 0.8;
+
+/**
+ * Review of what was extracted from a set of documents for one target
+ * entity: how pages were split into patient records, every value with its
+ * confidence and the line it was read from, conflicts between documents,
+ * and the images on each record's pages. Values can be corrected; the
+ * corrections and settings are applied to the table on "Aplicar".
+ */
+@Component({
+ selector: 'app-document-review-dialog',
+ imports: [
+ FormsModule,
+ MatButtonModule,
+ MatDialogModule,
+ MatFormFieldModule,
+ MatIconModule,
+ MatInputModule,
+ MatListModule,
+ MatProgressBarModule,
+ MatSelectModule,
+ MatTooltipModule,
+ PercentPipe,
+ ],
+ templateUrl: './document-review-dialog.html',
+ styleUrl: './document-review-dialog.scss',
+})
+export class DocumentReviewDialog {
+ private readonly data = inject(MAT_DIALOG_DATA);
+ private readonly dialogRef = inject>(MatDialogRef);
+ private readonly gateway = inject(SourceGateway);
+ private readonly destroyRef = inject(DestroyRef);
+
+ readonly table = this.data.table;
+ readonly target = this.data.target;
+ readonly segmentations = this.data.segmentations;
+ readonly methodLabels = METHOD_LABELS;
+ readonly reviewBelow = REVIEW_BELOW;
+
+ readonly settings = signal({ ...this.table.settings() });
+ readonly overrides = signal(structuredClone(this.table.overrides(this.target.key)));
+ readonly extracting = signal(false);
+ readonly error = signal(null);
+ readonly selectedIndex = signal(0);
+
+ readonly extraction = computed(() => this.table.extractions()[this.target.key] ?? null);
+ readonly records = computed(() => this.extraction()?.records ?? []);
+ readonly fields = computed(() => this.extraction()?.fields ?? []);
+ readonly selected = computed(() => this.records()[this.selectedIndex()] ?? null);
+ readonly needsReview = computed(() => this.records().filter((record) => this.recordNeedsReview(record)).length);
+
+ /** Object URLs of rendered images, by `document|page|bbox`. */
+ readonly thumbnails = signal>({});
+ readonly page = signal<{ document: string; page: number; url: string | null } | null>(null);
+
+ constructor() {
+ if (this.extraction()) this.select(0);
+ else this.extract();
+ this.destroyRef.onDestroy(() => {
+ Object.values(this.thumbnails()).forEach((url) => URL.revokeObjectURL(url));
+ const page = this.page();
+ if (page?.url) URL.revokeObjectURL(page.url);
+ });
+ }
+
+ // -- settings ------------------------------------------------------------
+
+ updateSettings(patch: Partial): void {
+ this.settings.update((settings) => ({ ...settings, ...patch }));
+ }
+
+ get settingsChanged(): boolean {
+ return JSON.stringify(this.settings()) !== JSON.stringify(this.table.settings());
+ }
+
+ extract(): void {
+ if (this.settingsChanged) this.overrides.set({});
+ this.table.configure(this.settings());
+ this.extracting.set(true);
+ this.error.set(null);
+ this.table.preview(this.gateway, this.target.key).subscribe({
+ next: () => {
+ this.extracting.set(false);
+ this.select(0);
+ },
+ error: (error) => {
+ this.extracting.set(false);
+ this.error.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
+ },
+ });
+ }
+
+ // -- records and values ------------------------------------------------------
+
+ select(index: number): void {
+ this.selectedIndex.set(index);
+ this.page.set(null);
+ this.selected()?.images.forEach((image) => this.loadThumbnail(image));
+ }
+
+ recordNeedsReview(record: ExtractedRecord): boolean {
+ return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW;
+ }
+
+ extracted(record: ExtractedRecord, field: string): ExtractedField | null {
+ return record.fields[field] ?? null;
+ }
+
+ value(record: ExtractedRecord, field: string): string {
+ const override = this.overrides()[String(record.index)]?.[field];
+ if (override !== undefined) return String(override ?? '');
+ const value = record.fields[field]?.value;
+ return value === null || value === undefined ? '' : String(value);
+ }
+
+ isOverridden(record: ExtractedRecord, field: string): boolean {
+ return this.overrides()[String(record.index)]?.[field] !== undefined;
+ }
+
+ setValue(record: ExtractedRecord, field: string, value: string): void {
+ const key = String(record.index);
+ this.overrides.update((all) => {
+ const next = { ...all, [key]: { ...(all[key] ?? {}) } };
+ const original = record.fields[field]?.value;
+ if (value === (original === null || original === undefined ? '' : String(original))) delete next[key][field];
+ else next[key][field] = value === '' ? null : value;
+ if (!Object.keys(next[key]).length) delete next[key];
+ return next;
+ });
+ }
+
+ conflictFor(record: ExtractedRecord, field: string) {
+ return record.conflicts.find((conflict) => conflict.field === field) ?? null;
+ }
+
+ // -- pages and images ----------------------------------------------------------
+
+ thumbnailKey(image: DocumentImage): string {
+ return `${image.document}|${image.page_number}|${image.bbox.join(',')}`;
+ }
+
+ showPage(document: string | undefined, pageNumber: number | undefined): void {
+ const file = this.table.files.find((candidate) => candidate.name === document);
+ if (!file || !pageNumber) return;
+ const previous = this.page();
+ if (previous?.url) URL.revokeObjectURL(previous.url);
+ this.page.set({ document: file.name, page: pageNumber, url: null });
+ this.gateway.document.pageImage(file, pageNumber).subscribe((blob) => {
+ if (this.page()?.document === file.name && this.page()?.page === pageNumber) {
+ this.page.set({ document: file.name, page: pageNumber, url: URL.createObjectURL(blob) });
+ }
+ });
+ }
+
+ private loadThumbnail(image: DocumentImage): void {
+ const key = this.thumbnailKey(image);
+ const file = this.table.files.find((candidate) => candidate.name === image.document);
+ if (!file || this.thumbnails()[key]) return;
+ this.gateway.document.pageImage(file, image.page_number, image.kind === 'figure' ? image.bbox : undefined, 72).subscribe((blob) => {
+ this.thumbnails.update((all) => ({ ...all, [key]: URL.createObjectURL(blob) }));
+ });
+ }
+
+ // -- close -------------------------------------------------------------------------
+
+ apply(): void {
+ this.table.configure(this.settings(), { [this.target.key]: this.overrides() });
+ this.dialogRef.close(true);
+ }
+}
diff --git a/src/app/connect/components/file-dropzone/file-dropzone.html b/src/app/connect/components/file-dropzone/file-dropzone.html
new file mode 100644
index 0000000..92fdaa0
--- /dev/null
+++ b/src/app/connect/components/file-dropzone/file-dropzone.html
@@ -0,0 +1,37 @@
+
+
cloud_upload
+
Arrastra tus archivos aquí
+
{{ formatsLabel }}
+
+
+ upload_file
+ Seleccionar archivos
+
+
+
+@if (fileMessages().length > 0) {
+
+ @for (message of fileMessages(); track $index) { {{ message }} }
+
+}
+
+@if (files().length > 0) {
+
+
+
+ @for (file of files(); track file.name + ':' + file.size) {
+
+ {{ fileIcon(file) }}
+ {{ file.name }}
+ {{ formatFileSize(file.size) }}
+
+ close
+
+
+ }
+
+
+}
diff --git a/src/app/connect/components/file-dropzone/file-dropzone.scss b/src/app/connect/components/file-dropzone/file-dropzone.scss
new file mode 100644
index 0000000..092e196
--- /dev/null
+++ b/src/app/connect/components/file-dropzone/file-dropzone.scss
@@ -0,0 +1,157 @@
+:host {
+ display: block;
+}
+.dropzone {
+ align-items: center;
+ background: var(--color-surface);
+ border: 1.5px dashed #cbd2c4;
+ border-radius: 10px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ min-height: 220px;
+ padding: var(--space-6);
+ text-align: center;
+ transition:
+ background-color 0.14s ease,
+ border-color 0.14s ease;
+}
+.dropzone--active {
+ background: #f5f8e9;
+ border-color: var(--color-primary);
+ border-style: solid;
+}
+.dropzone__icon {
+ color: #71882b;
+ font-size: 40px;
+ height: 40px;
+ width: 40px;
+}
+.dropzone__title {
+ font-size: 16px;
+ font-weight: 600;
+ margin: var(--space-4) 0 var(--space-1);
+ color: var(--color-text);
+}
+.dropzone__formats {
+ color: var(--color-text-secondary);
+ font-size: 13px;
+ margin: 0 0 var(--space-4);
+}
+.select-files-button {
+ --mat-button-outlined-label-text-color: var(--color-text);
+ --mat-button-outlined-outline-color: #d7dccf;
+ --mat-button-outlined-state-layer-color: transparent;
+ --mat-button-outlined-ripple-color: transparent;
+ background: var(--color-surface);
+ border: 1px solid var(--mat-button-outlined-outline-color);
+ transition: border-color 0.18s ease;
+}
+.upload-action--outlined:hover {
+ background: #f3f6e9;
+ border-color: var(--color-primary);
+}
+.upload-action--outlined:active {
+ background: #e8eed5;
+}
+.select-files-button mat-icon {
+ color: #5f9ea0;
+ margin: 0;
+}
+.visually-hidden {
+ clip: rect(0, 0, 0, 0);
+ clip-path: inset(50%);
+ height: 1px;
+ overflow: hidden;
+ position: absolute;
+ white-space: nowrap;
+ width: 1px;
+}
+.file-messages {
+ background: #fffaf0;
+ border: 1px solid #ead8a7;
+ border-radius: 7px;
+ color: #634d13;
+ font-size: 13px;
+ line-height: 1.45;
+ list-style: none;
+ margin: var(--space-3) 0 0;
+ padding: var(--space-3) var(--space-4);
+}
+.file-messages li + li {
+ margin-top: var(--space-1);
+}
+.selected-files {
+ margin-top: var(--space-5);
+}
+.selected-files__header {
+ align-items: center;
+ display: flex;
+ gap: var(--space-3);
+ justify-content: space-between;
+ margin-bottom: var(--space-2);
+}
+.selected-files__header h3 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ color: var(--color-text);
+}
+.selected-files__count {
+ align-items: center;
+ background: var(--color-step);
+ border-radius: 20px;
+ color: #52651d;
+ display: inline-flex;
+ font-size: 12px;
+ font-weight: 600;
+ height: 25px;
+ justify-content: center;
+ min-width: 25px;
+ padding: 0 var(--space-2);
+}
+.selected-files__list {
+ border: 1px solid #e7eae3;
+ border-radius: 8px;
+ list-style: none;
+ margin: 0;
+ max-height: 220px;
+ overflow-y: auto;
+ padding: 0;
+}
+.file-row {
+ align-items: center;
+ display: grid;
+ gap: var(--space-3);
+ grid-template-columns: 22px minmax(0, 1fr) auto 40px;
+ min-height: 54px;
+ padding: var(--space-2) var(--space-2) var(--space-2) var(--space-3);
+}
+.file-row + .file-row {
+ border-top: 1px solid #eef0eb;
+}
+.file-row__icon {
+ color: #71882b;
+ font-size: 20px;
+ height: 20px;
+ width: 20px;
+}
+.file-row__name {
+ font-size: 13px;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--color-text);
+}
+.file-row__size {
+ color: #737b6b;
+ font-size: 12px;
+ white-space: nowrap;
+}
+.file-row__remove {
+ color: #596273;
+ height: 36px;
+ line-height: 36px;
+ width: 36px;
+}
diff --git a/src/app/connect/components/file-dropzone/file-dropzone.spec.ts b/src/app/connect/components/file-dropzone/file-dropzone.spec.ts
new file mode 100644
index 0000000..4be0e3f
--- /dev/null
+++ b/src/app/connect/components/file-dropzone/file-dropzone.spec.ts
@@ -0,0 +1,104 @@
+import { TestBed } from '@angular/core/testing';
+import { FileDropzone } from './file-dropzone';
+
+describe('FileDropzone', () => {
+ function createFixture() {
+ const fixture = TestBed.createComponent(FileDropzone);
+ fixture.detectChanges();
+ return fixture;
+ }
+
+ beforeEach(async () => {
+ await TestBed.configureTestingModule({ imports: [FileDropzone] }).compileComponents();
+ });
+
+ it('accepts valid files and rejects invalid extension, empty, and duplicate files', () => {
+ const fixture = createFixture();
+ const compiled = fixture.nativeElement as HTMLElement;
+ const validFile = new File(['contenido'], 'pacientes.XLSX', { type: 'application/octet-stream' });
+ const csvFile = new File(['a,b'], 'consultas.csv', { type: 'text/csv' });
+ const invalidFile = new File(['x'], 'documento.docx');
+ const emptyFile = new File([], 'vacio.csv');
+
+ const fileInput = compiled.querySelector('input[type="file"]')!;
+ Object.defineProperty(fileInput, 'files', {
+ configurable: true,
+ value: [validFile, csvFile, invalidFile, emptyFile],
+ });
+ fileInput.dispatchEvent(new Event('change', { bubbles: true }));
+ fixture.detectChanges();
+
+ expect(compiled.querySelectorAll('.file-row')).toHaveLength(2);
+ expect(compiled.querySelector('.file-messages')?.textContent).toContain(
+ 'documento.docx no fue agregado. Formato no compatible.',
+ );
+ expect(compiled.querySelector('.file-messages')?.textContent).toContain(
+ 'vacio.csv no fue agregado. El archivo está vacío.',
+ );
+ });
+
+ it('rejects a duplicate file (same name + size) already selected', () => {
+ const fixture = createFixture();
+ const compiled = fixture.nativeElement as HTMLElement;
+ const validFile = new File(['contenido'], 'pacientes.xlsx', { type: 'application/octet-stream' });
+ const fileInput = compiled.querySelector('input[type="file"]')!;
+
+ const selectFiles = (files: File[]) => {
+ Object.defineProperty(fileInput, 'files', { configurable: true, value: files });
+ fileInput.dispatchEvent(new Event('change', { bubbles: true }));
+ fixture.detectChanges();
+ };
+
+ selectFiles([validFile]);
+ expect(compiled.querySelectorAll('.file-row')).toHaveLength(1);
+ selectFiles([validFile]);
+ expect(compiled.querySelectorAll('.file-row')).toHaveLength(1);
+ expect(compiled.querySelector('.file-messages')?.textContent).toContain(
+ 'pacientes.xlsx ya se encuentra seleccionado.',
+ );
+ });
+
+ it('supports drag and drop and removing a file, and emits filesChange', () => {
+ const fixture = createFixture();
+ const compiled = fixture.nativeElement as HTMLElement;
+ const component = fixture.componentInstance;
+ const emitted: File[][] = [];
+ component.filesChange.subscribe((files) => emitted.push(files));
+
+ const jsonFile = new File(['{}'], 'nuevo.json', { type: 'application/json' });
+ component.onDrop({
+ preventDefault: () => undefined,
+ dataTransfer: { files: [jsonFile] },
+ } as unknown as DragEvent);
+ fixture.detectChanges();
+
+ expect(compiled.querySelectorAll('.file-row')).toHaveLength(1);
+ expect(emitted.at(-1)).toEqual([jsonFile]);
+
+ compiled.querySelector('.file-row__remove')!.click();
+ fixture.detectChanges();
+ expect(compiled.querySelectorAll('.file-row')).toHaveLength(0);
+ expect(emitted.at(-1)).toEqual([]);
+ });
+
+ it('honors a custom accept input, keeping pdf available by default', () => {
+ const fixture = createFixture();
+ expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(true);
+
+ fixture.componentRef.setInput('accept', ['csv']);
+ fixture.detectChanges();
+ expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(false);
+ expect(fixture.componentInstance.allowedExtensions.has('csv')).toBe(true);
+ });
+
+ it('reflects drag-over state via dragenter/dragleave', () => {
+ const fixture = createFixture();
+ const component = fixture.componentInstance;
+ const preventDefault = () => undefined;
+
+ component.onDragEnter({ preventDefault } as unknown as DragEvent);
+ expect(component.isDragOver()).toBe(true);
+ component.onDragLeave({ preventDefault } as unknown as DragEvent);
+ expect(component.isDragOver()).toBe(false);
+ });
+});
diff --git a/src/app/information-upload-dialog.ts b/src/app/connect/components/file-dropzone/file-dropzone.ts
similarity index 67%
rename from src/app/information-upload-dialog.ts
rename to src/app/connect/components/file-dropzone/file-dropzone.ts
index 2901f6b..4702123 100644
--- a/src/app/information-upload-dialog.ts
+++ b/src/app/connect/components/file-dropzone/file-dropzone.ts
@@ -1,47 +1,35 @@
-import { Component, signal } from '@angular/core';
+import { Component, EventEmitter, Input, Output, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
-import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
-type UploadSource = 'file' | 'sql';
-type UploadStep = 'source' | 'configuration' | 'confirmation';
-
+/** Drag-and-drop and file-picker area that collects a validated list of files. */
@Component({
- imports: [MatButtonModule, MatDialogModule, MatIconModule],
- selector: 'app-information-upload-dialog',
- styleUrl: './information-upload-dialog.scss',
- templateUrl: './information-upload-dialog.html',
+ imports: [MatButtonModule, MatIconModule],
+ selector: 'app-file-dropzone',
+ styleUrl: './file-dropzone.scss',
+ templateUrl: './file-dropzone.html',
})
-export class InformationUploadDialog {
- readonly step = signal('source');
- readonly source = signal(null);
+export class FileDropzone {
+ @Input() accept: string[] = ['xlsx', 'csv', 'json', 'pdf'];
+ @Input() multiple = true;
+ @Output() readonly filesChange = new EventEmitter();
+
readonly files = signal([]);
readonly fileMessages = signal([]);
readonly isDragOver = signal(false);
private dragDepth = 0;
- private readonly allowedExtensions = new Set(['xlsx', 'csv', 'json', 'pdf']);
- constructor(private readonly dialogRef: MatDialogRef) {}
-
- selectSource(source: UploadSource): void {
- this.source.set(source);
+ get allowedExtensions(): Set {
+ return new Set(this.accept.map((extension) => extension.toLowerCase()));
}
- continue(): void {
- if (this.step() === 'source' && this.source()) this.step.set('configuration');
- else if (this.step() === 'configuration' && this.source() === 'file' && this.files().length > 0) {
- this.step.set('confirmation');
- }
+ get acceptAttribute(): string {
+ return this.accept.map((extension) => `.${extension}`).join(',');
}
- back(): void {
- if (this.step() === 'confirmation') this.step.set('configuration');
- else if (this.step() === 'configuration') this.step.set('source');
- }
-
- close(): void {
- this.dialogRef.close();
+ get formatsLabel(): string {
+ return this.accept.map((extension) => extension.toUpperCase()).join(' · ');
}
onFileSelection(event: Event): void {
@@ -76,6 +64,7 @@ export class InformationUploadDialog {
removeFile(fileToRemove: File): void {
this.files.update((files) => files.filter((file) => file !== fileToRemove));
+ this.filesChange.emit(this.files());
}
formatFileSize(size: number): string {
@@ -99,7 +88,7 @@ export class InformationUploadDialog {
private addFiles(incomingFiles: File[]): void {
const messages: string[] = [];
- const accepted = [...this.files()];
+ const accepted = this.multiple ? [...this.files()] : [];
for (const file of incomingFiles) {
const extension = this.extensionOf(file.name);
@@ -115,11 +104,16 @@ export class InformationUploadDialog {
messages.push(`${file.name} ya se encuentra seleccionado.`);
continue;
}
+ if (!this.multiple) {
+ accepted.length = 0;
+ }
accepted.push(file);
+ if (!this.multiple) break;
}
- if (accepted.length !== this.files().length) this.files.set(accepted);
+ this.files.set(accepted);
this.fileMessages.set(messages);
+ this.filesChange.emit(accepted);
}
private extensionOf(fileName: string): string {
diff --git a/src/app/connect/components/flow-canvas/flow-canvas.html b/src/app/connect/components/flow-canvas/flow-canvas.html
new file mode 100644
index 0000000..11564c9
--- /dev/null
+++ b/src/app/connect/components/flow-canvas/flow-canvas.html
@@ -0,0 +1,102 @@
+
+
+
+
+ @for (flow of store.flows(); track flow.id) {
+
+
+
+ {{ flow.table.icon }}
+ {{ flow.table.name }}
+
+ arrow_right_alt
+
+ table_chart
+ {{ flow.target.table }}
+
+
+
+
+ refresh Volver a leer la fuente
+
+
+ delete Quitar flujo
+
+
+
+
+ {{ flow.table.connection.label }}
+
+
+
+
+
+
+ {{ mappedFields(flow) }}/{{ flow.target.fields.length }} campos
+
+ @if (flow.totalRows() !== null) {
+
{{ flow.totalRows() | number }} filas
+ }
+ @if (flow.validation(); as validation) {
+ @if (validation.error_count > 0) {
+
{{ validation.error_count | number }} con errores
+ }
+ }
+ @if (flow.result(); as result) {
+
+{{ result.created }} / ↻{{ result.updated }}
+ }
+
+
+ }
+
+
+
move_to_inbox
+
+ @if (store.connections().length === 0) {
+ Agrega una conexión y arrastra sus tablas aquí para componer tu carga.
+ } @else {
+ Arrastra aquí una tabla de «Conexiones» — o usa su botón arrow_forward .
+ }
+
+ @if (store.connections().length === 0) {
+
+ add Obtener datos
+
+ }
+
+
+
diff --git a/src/app/connect/components/flow-canvas/flow-canvas.scss b/src/app/connect/components/flow-canvas/flow-canvas.scss
new file mode 100644
index 0000000..7dc86a6
--- /dev/null
+++ b/src/app/connect/components/flow-canvas/flow-canvas.scss
@@ -0,0 +1,167 @@
+:host {
+ display: block;
+}
+
+.canvas {
+ border-radius: var(--mat-sys-corner-large);
+ padding: var(--space-4);
+ transition: background-color 0.15s ease, outline-color 0.15s ease;
+}
+
+.canvas.cdk-drop-list-receiving {
+ outline: 2px dashed var(--mat-sys-primary);
+ outline-offset: -2px;
+}
+
+.canvas.cdk-drop-list-dragging {
+ background: color-mix(in srgb, var(--mat-sys-primary-container) 45%, transparent);
+}
+
+.canvas ::ng-deep .cdk-drag-placeholder {
+ display: none;
+}
+
+.canvas__header {
+ align-items: baseline;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1) var(--space-3);
+ margin-bottom: var(--space-3);
+
+ h2 {
+ font: var(--mat-sys-title-medium);
+ margin: 0;
+ }
+}
+
+.canvas__caption {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.canvas__grid {
+ display: grid;
+ gap: var(--space-3);
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+}
+
+.flow-card {
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ padding: var(--space-3) var(--space-3) var(--space-3) var(--space-4);
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+
+ &:hover {
+ box-shadow: var(--mat-sys-level1);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--mat-sys-primary);
+ }
+}
+
+.flow-card--selected {
+ border-color: var(--mat-sys-primary) !important;
+ box-shadow: 0 0 0 1px var(--mat-sys-primary), var(--mat-sys-level1);
+}
+
+.flow-card__route {
+ align-items: center;
+ display: flex;
+ gap: var(--space-1);
+}
+
+.flow-card__end {
+ align-items: center;
+ display: inline-flex;
+ flex: 1 1 0;
+ gap: var(--space-1);
+ min-width: 0;
+
+ mat-icon {
+ color: var(--mat-sys-on-surface-variant);
+ flex: none;
+ font-size: 20px;
+ height: 20px;
+ width: 20px;
+ }
+}
+
+.flow-card__end--target mat-icon {
+ color: var(--mat-sys-primary);
+}
+
+.flow-card__name {
+ font: var(--mat-sys-title-small);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.flow-card__arrow {
+ color: var(--mat-sys-outline);
+ flex: none;
+}
+
+.flow-card__menu {
+ flex: none;
+ margin: -8px -4px -8px 0;
+}
+
+.flow-card__source {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ margin: -4px 0 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.flow-card__facts {
+ align-items: center;
+ color: var(--mat-sys-on-surface-variant);
+ display: flex;
+ flex-wrap: wrap;
+ font: var(--mat-sys-body-small);
+ gap: var(--space-1) var(--space-3);
+}
+
+.flow-card__errors {
+ color: #9a5b00;
+}
+
+.flow-card__loaded {
+ color: var(--mat-sys-primary);
+ font-weight: 500;
+}
+
+.canvas__drop {
+ align-items: center;
+ border: 1.5px dashed var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ color: var(--mat-sys-on-surface-variant);
+ display: flex;
+ flex-direction: column;
+ font: var(--mat-sys-body-medium);
+ gap: var(--space-2);
+ justify-content: center;
+ min-height: 132px;
+ padding: var(--space-4);
+ text-align: center;
+
+ p {
+ margin: 0;
+ max-width: 360px;
+ }
+
+ > mat-icon {
+ color: var(--mat-sys-primary);
+ }
+}
+
+.canvas__drop--alone {
+ grid-column: 1 / -1;
+ min-height: 220px;
+}
diff --git a/src/app/connect/components/flow-canvas/flow-canvas.ts b/src/app/connect/components/flow-canvas/flow-canvas.ts
new file mode 100644
index 0000000..c041352
--- /dev/null
+++ b/src/app/connect/components/flow-canvas/flow-canvas.ts
@@ -0,0 +1,56 @@
+import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop';
+import { DecimalPipe } from '@angular/common';
+import { Component, inject, output } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MatCardModule } from '@angular/material/card';
+import { MatIconModule } from '@angular/material/icon';
+import { MatMenuModule } from '@angular/material/menu';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { SourceTable } from '../../domain/data-source';
+import { ImportFlow } from '../../domain/import-flow';
+import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
+import { FlowStatusChip } from '../shared/flow-status';
+
+/**
+ * The composition canvas: one card per import flow (source table →
+ * destination entity), the whole batch visible at once. Drop a table from
+ * the connections pane anywhere on it to add a flow.
+ */
+@Component({
+ selector: 'app-flow-canvas',
+ imports: [
+ DecimalPipe,
+ DragDropModule,
+ FlowStatusChip,
+ MatButtonModule,
+ MatCardModule,
+ MatIconModule,
+ MatMenuModule,
+ MatProgressBarModule,
+ MatTooltipModule,
+ ],
+ templateUrl: './flow-canvas.html',
+ styleUrl: './flow-canvas.scss',
+})
+export class FlowCanvas {
+ readonly store = inject(ConnectWorkspaceStore);
+
+ readonly tableDropped = output();
+ readonly addConnection = output();
+
+ readonly onlyTables = (drag: CdkDrag) => drag.data instanceof SourceTable;
+
+ onDrop(event: CdkDragDrop): void {
+ if (event.item.data instanceof SourceTable) this.tableDropped.emit(event.item.data);
+ }
+
+ mappedFields(flow: ImportFlow): number {
+ return flow.mapping.size() + Object.keys(flow.activeDefaults()).length;
+ }
+
+ coverage(flow: ImportFlow): number {
+ const total = flow.target.fields.length;
+ return total ? Math.round((this.mappedFields(flow) / total) * 100) : 0;
+ }
+}
diff --git a/src/app/connect/components/flow-editor/flow-editor.html b/src/app/connect/components/flow-editor/flow-editor.html
new file mode 100644
index 0000000..4a4b976
--- /dev/null
+++ b/src/app/connect/components/flow-editor/flow-editor.html
@@ -0,0 +1,73 @@
+@let f = flow();
+
+
+
+ @if (f.loading()) {
+
+ }
+ @if (f.error(); as error) {
+
+ error {{ error }}
+ Reintentar
+
+ }
+
+ @if (f.preview()) {
+
+
+
+ account_tree Mapeo
+ @if (f.missingRequired().length) {
+ {{ f.missingRequired().length }}
+ }
+
+
+
+
+ table_view Datos
+
+
+
+
+ fact_check Validación
+ @if (f.validation(); as validation) {
+ 0">{{ validation.error_count | number }}
+ }
+
+
+
+
+ }
+
diff --git a/src/app/connect/components/flow-editor/flow-editor.scss b/src/app/connect/components/flow-editor/flow-editor.scss
new file mode 100644
index 0000000..4c28daf
--- /dev/null
+++ b/src/app/connect/components/flow-editor/flow-editor.scss
@@ -0,0 +1,101 @@
+:host {
+ display: block;
+}
+
+.editor {
+ background: var(--mat-sys-surface);
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-large);
+ overflow: hidden;
+}
+
+.editor__header {
+ align-items: center;
+ border-bottom: 1px solid var(--mat-sys-outline-variant);
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+ justify-content: space-between;
+ padding: var(--space-3) var(--space-4);
+}
+
+.editor__route {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+ min-width: 0;
+
+ > mat-icon {
+ color: var(--mat-sys-on-surface-variant);
+ flex: none;
+ }
+}
+
+.editor__source,
+.editor__target {
+ font: var(--mat-sys-title-small);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.editor__source {
+ max-width: 36ch;
+}
+
+.editor__arrow {
+ color: var(--mat-sys-outline) !important;
+}
+
+.editor__target-icon {
+ color: var(--mat-sys-primary) !important;
+}
+
+.editor__actions {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+}
+
+.editor__rows {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ margin-right: var(--space-2);
+}
+
+.editor__error {
+ align-items: center;
+ background: var(--mat-sys-error-container);
+ color: var(--mat-sys-on-error-container);
+ display: flex;
+ gap: var(--space-2);
+ margin: 0;
+ padding: var(--space-2) var(--space-4);
+}
+
+.editor__tabs ::ng-deep .mat-mdc-tab .mdc-tab__text-label {
+ gap: 6px;
+
+ mat-icon {
+ font-size: 18px;
+ height: 18px;
+ width: 18px;
+ }
+}
+
+.editor__panel {
+ padding: var(--space-4);
+}
+
+.tab-count {
+ background: var(--mat-sys-surface-container-highest);
+ border-radius: 999px;
+ font: var(--mat-sys-label-small);
+ padding: 1px 7px;
+}
+
+.tab-count--warn {
+ background: #fff1d6;
+ color: #7a4b00;
+}
diff --git a/src/app/connect/components/flow-editor/flow-editor.ts b/src/app/connect/components/flow-editor/flow-editor.ts
new file mode 100644
index 0000000..c07fa5a
--- /dev/null
+++ b/src/app/connect/components/flow-editor/flow-editor.ts
@@ -0,0 +1,72 @@
+import { DecimalPipe } from '@angular/common';
+import { Component, computed, inject, input, signal } from '@angular/core';
+import { MatBadgeModule } from '@angular/material/badge';
+import { MatButtonModule } from '@angular/material/button';
+import { MatDialog } from '@angular/material/dialog';
+import { MatIconModule } from '@angular/material/icon';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatTabsModule } from '@angular/material/tabs';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { DocumentTable } from '../../domain/document-source';
+import { ImportFlow } from '../../domain/import-flow';
+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 { FlowStatusChip } from '../shared/flow-status';
+import { ValidationReport } from '../validation-report/validation-report';
+
+const VALIDATION_TAB = 2;
+
+/** Everything about the selected flow: its mapping, its data, its validation. */
+@Component({
+ selector: 'app-flow-editor',
+ imports: [
+ ColumnMapper,
+ DataGrid,
+ DecimalPipe,
+ FlowStatusChip,
+ MatBadgeModule,
+ MatButtonModule,
+ MatIconModule,
+ MatProgressBarModule,
+ MatTabsModule,
+ MatTooltipModule,
+ ValidationReport,
+ ],
+ templateUrl: './flow-editor.html',
+ styleUrl: './flow-editor.scss',
+})
+export class FlowEditor {
+ readonly flow = input.required();
+ readonly store = inject(ConnectWorkspaceStore);
+ private readonly dialog = inject(MatDialog);
+ readonly tab = signal(0);
+
+ /** Document sources get a review of what was extracted, record by record. */
+ readonly documentTable = computed(() => {
+ const table = this.flow().table;
+ return table instanceof DocumentTable ? table : null;
+ });
+
+ reviewExtraction(): void {
+ const table = this.documentTable();
+ if (!table) return;
+ const segmentations = this.store.connectors().find((c) => c.kind === 'document')?.segmentations ?? [];
+ this.dialog
+ .open(DocumentReviewDialog, {
+ data: { table, target: this.flow().target, segmentations },
+ width: '1280px',
+ maxWidth: '98vw',
+ autoFocus: false,
+ disableClose: true,
+ })
+ .afterClosed()
+ .subscribe((applied) => applied && this.store.flowsOf(table).forEach((flow) => this.store.reloadFlow(flow)));
+ }
+
+ async validate(): Promise {
+ await this.store.validate(this.flow());
+ this.tab.set(VALIDATION_TAB);
+ }
+}
diff --git a/src/app/connect/components/load-dialog/load-dialog.html b/src/app/connect/components/load-dialog/load-dialog.html
new file mode 100644
index 0000000..e7f3302
--- /dev/null
+++ b/src/app/connect/components/load-dialog/load-dialog.html
@@ -0,0 +1,115 @@
+Cargar a la base de datos · {{ store.domain().toUpperCase() }}
+
+ @if (validating()) {
+ Validando todas las filas de {{ flows().length }} flujo(s)…
+
+ } @else {
+ @if (!batch()) {
+
+ Se escribirán {{ totals().valid | number }} filas válidas de {{ totals().rows | number }} en
+ {{ flows().length }} flujo(s), en una sola transacción: si algo falla en la base, no se escribe nada.
+ @if (totals().errors > 0) {
+ {{ totals().errors | number }} fila(s) con errores se omitirán.
+ }
+
+ } @else if (outcome(); as o) {
+
+ cloud_done
+ Carga completa: {{ o.created | number }} insertadas, {{ o.updated | number }} actualizadas, {{ o.rejected | number }} omitidas.
+ @if (o.merged) {
+ {{ o.merged | number }} combinadas con registros de otras fuentes@if (o.warnings) {, {{ o.warnings | number }} valor(es) en desacuerdo}.
+ }
+
+ }
+
+
+
+ Flujo
+
+ {{ flow.table.name }}
+ → {{ flow.target.table }}
+
+
+
+ Estado
+
+
+
+ Filas
+ {{ flow.validation()?.total_rows | number }}
+
+
+ Válidas
+ {{ flow.validation()?.valid_count | number }}
+
+
+ Con error
+ {{ flow.validation()?.error_count | number }}
+
+
+ Resultado
+
+ @if (resultOf(flow); as result) {
+ +{{ result.created }} · ↻{{ result.updated }} · ✕{{ result.rejected }}@if (result.merged) { · ⧉{{ result.merged }} }
+ } @else {
+ —
+ }
+
+
+
+
+
+
+ @if (skipped().length > 0) {
+
+ info
+ {{ skipped().length }} flujo(s) no se cargarán porque no están listos (faltan obligatorios o la fuente falló).
+
+ }
+
+ @if (!batch()) {
+
+ Si un registro ya existe en la base
+
+ Omitirlo (se reporta como conflicto)
+
+ Actualizarlo con los campos mapeados (los demás campos no se tocan)
+
+
+ @if (!store.upsertAvailable()) {
+ Actualizar solo es posible cuando todas las tablas destino tienen clave natural (p. ej. Paciente).
+ }
+
+ @if (mergeAvailable()) {
+
+ Datos de un mismo paciente en varias fuentes
+
+ Combinar las filas con la misma clave en un solo registro antes de validar
+
+
+ Cada fuente completa los campos que a las demás les faltan; si dos fuentes no coinciden en un valor se conserva
+ el del primer flujo y se reporta. La validación previa por flujo no considera esta combinación.
+
+
+ }
+ }
+
+ @if (store.committing()) {
+
+ }
+ @if (store.commitError(); as error) {
+ error {{ error }}
+ }
+ }
+
+
+ @if (batch()) {
+ Cerrar
+ travel_explore Explorar la base
+ } @else {
+ Cancelar
+
+ cloud_upload Cargar {{ totals().valid | number }} filas
+
+ }
+
diff --git a/src/app/connect/components/load-dialog/load-dialog.scss b/src/app/connect/components/load-dialog/load-dialog.scss
new file mode 100644
index 0000000..e7fa64a
--- /dev/null
+++ b/src/app/connect/components/load-dialog/load-dialog.scss
@@ -0,0 +1,60 @@
+.lead {
+ font: var(--mat-sys-body-large);
+ margin-top: 0;
+ max-width: 760px;
+}
+
+.lead--done {
+ align-items: center;
+ color: var(--mat-sys-primary);
+ display: flex;
+ gap: var(--space-2);
+}
+
+.warn {
+ color: #9a5b00;
+}
+
+.flows {
+ --mat-table-row-item-container-height: 44px;
+ margin-bottom: var(--space-3);
+ width: 100%;
+}
+
+.flows__name {
+ font: var(--mat-sys-title-small);
+}
+
+.flows__target {
+ color: var(--mat-sys-on-surface-variant);
+ margin-left: var(--space-2);
+}
+
+.note,
+.error {
+ align-items: center;
+ color: var(--mat-sys-on-surface-variant);
+ display: flex;
+ font: var(--mat-sys-body-small);
+ gap: var(--space-2);
+}
+
+.error {
+ color: var(--mat-sys-error);
+}
+
+.policy {
+ border-top: 1px solid var(--mat-sys-outline-variant);
+ margin-top: var(--space-3);
+ padding-top: var(--space-3);
+
+ h3 {
+ font: var(--mat-sys-title-small);
+ margin: 0 0 var(--space-2);
+ }
+
+ mat-radio-group {
+ display: flex;
+ flex-direction: column;
+ }
+}
diff --git a/src/app/connect/components/load-dialog/load-dialog.ts b/src/app/connect/components/load-dialog/load-dialog.ts
new file mode 100644
index 0000000..7ef5234
--- /dev/null
+++ b/src/app/connect/components/load-dialog/load-dialog.ts
@@ -0,0 +1,106 @@
+import { DecimalPipe } from '@angular/common';
+import { Component, OnInit, computed, inject, signal } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MatCheckboxModule } from '@angular/material/checkbox';
+import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
+import { MatIconModule } from '@angular/material/icon';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatRadioModule } from '@angular/material/radio';
+import { MatTableModule } from '@angular/material/table';
+import { ConflictStrategy } from '../../api/api.types';
+import { ImportFlow } from '../../domain/import-flow';
+import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
+import { FlowStatusChip } from '../shared/flow-status';
+
+export type LoadDialogResult = 'explore' | undefined;
+
+/**
+ * "Cargar a la base": validates every flow, shows what will be written,
+ * sets the batch options (conflict policy, merging a patient's data spread
+ * across sources) and loads the batch in one request and one transaction.
+ * Rows failing validation are skipped and reported, never written.
+ */
+@Component({
+ selector: 'app-load-dialog',
+ imports: [DecimalPipe, FlowStatusChip, MatButtonModule, MatCheckboxModule, MatDialogModule, MatIconModule, MatProgressBarModule, MatRadioModule, MatTableModule],
+ templateUrl: './load-dialog.html',
+ styleUrl: './load-dialog.scss',
+})
+export class LoadDialog implements OnInit {
+ readonly store = inject(ConnectWorkspaceStore);
+ private readonly dialogRef = inject>(MatDialogRef);
+
+ readonly columns = ['flow', 'status', 'rows', 'valid', 'errors', 'outcome'];
+ readonly validating = signal(true);
+ /** Whether merging is even possible here; independent of the checkbox itself. */
+ readonly mergeAvailable = this.store.mergeAvailable;
+ /** With merging, rows incomplete on their own may be completed by another source. */
+ readonly canLoad = computed(() => this.totals().valid > 0 || (this.store.mergeDuplicates() && this.totals().rows > 0));
+
+ /**
+ * The flows the next batch would write. Reactive to the merge checkbox
+ * while nothing has loaded yet, so ticking it reveals the flow it
+ * completes; frozen the moment a batch starts, so the results table
+ * keeps listing exactly what was sent.
+ */
+ private readonly _frozenFlows = signal(null);
+ readonly flows = computed(() => this._frozenFlows() ?? this.store.submittableFlows());
+ readonly skipped = computed(() => this.store.flows().filter((flow) => !this.flows().includes(flow) && !flow.canSubmit));
+
+ readonly totals = computed(() =>
+ this.flows().reduce(
+ (acc, flow) => {
+ const validation = flow.validation();
+ acc.rows += validation?.total_rows ?? 0;
+ acc.valid += validation?.valid_count ?? 0;
+ acc.errors += validation?.error_count ?? 0;
+ return acc;
+ },
+ { rows: 0, valid: 0, errors: 0 },
+ ),
+ );
+
+ readonly batch = this.store.lastBatch;
+ readonly outcome = computed(() => {
+ const batch = this.batch();
+ if (!batch) return null;
+ return batch.results.reduce(
+ (acc, result) => ({
+ created: acc.created + result.created,
+ updated: acc.updated + result.updated,
+ rejected: acc.rejected + result.rejected,
+ merged: acc.merged + (result.merged ?? 0),
+ warnings: acc.warnings + (result.warnings?.length ?? 0),
+ }),
+ { created: 0, updated: 0, rejected: 0, merged: 0, warnings: 0 },
+ );
+ });
+
+ async ngOnInit(): Promise {
+ await Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow)));
+ this.validating.set(false);
+ }
+
+ setStrategy(strategy: ConflictStrategy): void {
+ this.store.setOnConflict(strategy);
+ }
+
+ /** Toggling may bring an until-now-skipped flow into `flows()`; preview its rows too. */
+ toggleMerge(merge: boolean): void {
+ this.store.setMergeDuplicates(merge);
+ Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow)));
+ }
+
+ load(): void {
+ this._frozenFlows.set(this.store.submittableFlows());
+ this.store.commit().subscribe();
+ }
+
+ explore(): void {
+ this.dialogRef.close('explore');
+ }
+
+ resultOf(flow: ImportFlow) {
+ return flow.result();
+ }
+}
diff --git a/src/app/connect/components/new-flow-dialog/new-flow-dialog.ts b/src/app/connect/components/new-flow-dialog/new-flow-dialog.ts
new file mode 100644
index 0000000..983405a
--- /dev/null
+++ b/src/app/connect/components/new-flow-dialog/new-flow-dialog.ts
@@ -0,0 +1,74 @@
+import { Component, inject, signal } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
+import { MatIconModule } from '@angular/material/icon';
+import { MatListModule } from '@angular/material/list';
+import { TargetMeta } from '../../api/api.types';
+import { SourceTable } from '../../domain/data-source';
+import { suggestTarget } from '../../domain/target-suggester';
+
+export interface NewFlowDialogData {
+ table: SourceTable;
+ targets: TargetMeta[];
+ existingTargets: Map;
+}
+
+/** "¿A qué tabla de la base va esta fuente?" — picks the destination entity for a new flow. */
+@Component({
+ selector: 'app-new-flow-dialog',
+ imports: [MatButtonModule, MatDialogModule, MatIconModule, MatListModule],
+ template: `
+ Nueva carga desde «{{ data.table.name }}»
+
+ Elige la tabla de destino. Puedes cargar varias fuentes en la misma tabla y una misma fuente en varias tablas.
+
+ @for (target of data.targets; track target.key) {
+
+ table_chart
+
+ {{ target.table }}
+ @if (target === suggested) {
+ Sugerida
+ }
+
+
+ {{ target.fields.length }} campos · {{ requiredCount(target) }} obligatorios
+ @if (data.existingTargets.get(target.key); as count) {
+ · ya la cargan {{ count }} flujo(s)
+ }
+
+
+ }
+
+
+
+ Cancelar
+ Crear flujo
+
+ `,
+ styles: `
+ .hint { color: var(--mat-sys-on-surface-variant); margin-top: 0; }
+ .tag {
+ background: var(--mat-sys-primary-container);
+ border-radius: 999px;
+ color: var(--mat-sys-on-primary-container);
+ font: var(--mat-sys-label-small);
+ margin-left: 6px;
+ padding: 1px 8px;
+ }
+ `,
+})
+export class NewFlowDialog {
+ readonly data = inject(MAT_DIALOG_DATA);
+ readonly dialogRef = inject>(MatDialogRef);
+ readonly suggested = suggestTarget(this.data.table.name, this.data.targets, this.data.table.connection.label);
+ readonly selected = signal(this.suggested);
+
+ requiredCount(target: TargetMeta): number {
+ return target.fields.filter((field) => field.required).length;
+ }
+}
diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html
new file mode 100644
index 0000000..f9d0bea
--- /dev/null
+++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.html
@@ -0,0 +1,56 @@
+
+
+
+ chevron_left
+
+ Página {{ pageNumber() }} de {{ pageCount() }}
+ = pageCount()" (click)="next()" aria-label="Página siguiente">
+ chevron_right
+
+
+
+ @if (loading()) {
+
+ }
+ @if (error()) {
+
{{ error() }}
+ }
+
+
+ @if (imageUrl(); as url) {
+
+
+ @for (region of regionsOnCurrentPage(); track region.target_field) {
+
+
+ {{ region.target_field }}
+ ×
+
+
+ }
+
+ @if (overlay.liveBox(); as box) {
+
+ }
+
+ }
+
+
diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss
new file mode 100644
index 0000000..8772c77
--- /dev/null
+++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.scss
@@ -0,0 +1,92 @@
+:host {
+ display: block;
+}
+
+.viewer__toolbar {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+ justify-content: center;
+}
+
+.viewer__page-label {
+ color: var(--color-text);
+ font-size: 13px;
+ font-weight: 600;
+ min-width: 120px;
+ text-align: center;
+}
+
+.viewer__error {
+ background: #fdeeee;
+ border: 1px solid #e3a6a6;
+ border-radius: 7px;
+ color: #7a2222;
+ font-size: 13px;
+ margin: var(--space-2) 0 0;
+ padding: var(--space-3) var(--space-4);
+}
+
+.viewer__stage {
+ background: var(--color-step);
+ border: 1px solid var(--color-border);
+ border-radius: 8px;
+ margin-top: var(--space-3);
+ overflow: auto;
+ position: relative;
+ text-align: center;
+}
+
+.viewer__image {
+ display: block;
+ margin: 0 auto;
+ max-width: 100%;
+ user-select: none;
+}
+
+.region-overlay {
+ cursor: crosshair;
+ inset: 0;
+ position: absolute;
+ touch-action: none;
+}
+
+.region-overlay__box {
+ background: rgb(168 194 67 / 18%);
+ border: 2px solid var(--color-primary);
+ pointer-events: none;
+ position: absolute;
+}
+
+.region-overlay__live {
+ background: rgb(168 194 67 / 12%);
+ border: 2px dashed var(--color-primary);
+ pointer-events: none;
+ position: absolute;
+}
+
+.region-overlay__label {
+ align-items: center;
+ background: var(--color-primary);
+ color: var(--color-text);
+ display: inline-flex;
+ font-size: 11px;
+ font-weight: 600;
+ gap: var(--space-1);
+ left: -2px;
+ padding: 1px var(--space-1);
+ pointer-events: auto;
+ position: absolute;
+ top: -20px;
+ white-space: nowrap;
+}
+
+.region-overlay__remove {
+ background: none;
+ border: none;
+ color: var(--color-text);
+ cursor: pointer;
+ font-size: 13px;
+ line-height: 1;
+ padding: 0 0 0 var(--space-1);
+}
diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts
new file mode 100644
index 0000000..b7e330d
--- /dev/null
+++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.spec.ts
@@ -0,0 +1,116 @@
+import { TestBed } from '@angular/core/testing';
+import { Observable, of } from 'rxjs';
+import { PdfSourceApi } from '../../api/pdf-source.api';
+import { PdfPageViewer } from './pdf-page-viewer';
+
+class FakePdfSourceApi {
+ readonly calls: number[] = [];
+
+ pageImage(_file: File, pageNumber: number): Observable {
+ this.calls.push(pageNumber);
+ return of(new Blob([`page-${pageNumber}`], { type: 'image/png' }));
+ }
+}
+
+describe('PdfPageViewer', () => {
+ let fakeApi: FakePdfSourceApi;
+ let createObjectURL: ReturnType;
+ let revokeObjectURL: ReturnType;
+ let urlCounter = 0;
+
+ beforeEach(async () => {
+ fakeApi = new FakePdfSourceApi();
+ urlCounter = 0;
+ createObjectURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:mock-${++urlCounter}`);
+ revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
+
+ await TestBed.configureTestingModule({
+ imports: [PdfPageViewer],
+ providers: [{ provide: PdfSourceApi, useValue: fakeApi }],
+ }).compileComponents();
+ });
+
+ afterEach(() => {
+ createObjectURL.mockRestore();
+ revokeObjectURL.mockRestore();
+ });
+
+ function createFixture(pageNumber = 1, pageCount = 3) {
+ const fixture = TestBed.createComponent(PdfPageViewer);
+ fixture.componentRef.setInput('file', new File(['%PDF'], 'doc.pdf', { type: 'application/pdf' }));
+ fixture.componentRef.setInput('pageNumber', pageNumber);
+ fixture.componentRef.setInput('pageCount', pageCount);
+ fixture.detectChanges();
+ return fixture;
+ }
+
+ it('fetches and displays page 1 on init via an object URL', () => {
+ const fixture = createFixture(1);
+ const component = fixture.componentInstance;
+
+ expect(fakeApi.calls).toEqual([1]);
+ expect(createObjectURL).toHaveBeenCalledTimes(1);
+ expect(component.imageUrl()).toBe('blob:mock-1');
+ });
+
+ it('revokes the previous object URL and creates a new one when navigating to a new page', () => {
+ const fixture = createFixture(1);
+ fixture.componentRef.setInput('pageNumber', 2);
+ fixture.detectChanges();
+
+ expect(fakeApi.calls).toEqual([1, 2]);
+ expect(createObjectURL).toHaveBeenCalledTimes(2);
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-1');
+ expect(fixture.componentInstance.imageUrl()).toBe('blob:mock-2');
+ });
+
+ it('does not refetch an already-fetched page, but still swaps to a fresh object URL for it', () => {
+ const fixture = createFixture(1);
+ fixture.componentRef.setInput('pageNumber', 2);
+ fixture.detectChanges();
+ fixture.componentRef.setInput('pageNumber', 1);
+ fixture.detectChanges();
+
+ // Only two distinct pages were ever fetched from the API, even though
+ // page 1 was visited twice.
+ expect(fakeApi.calls).toEqual([1, 2]);
+ // But a fresh object URL is still minted from the cached Blob each time
+ // the page is (re)displayed, and the previously-shown one is revoked.
+ expect(createObjectURL).toHaveBeenCalledTimes(3);
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-2');
+ expect(fixture.componentInstance.imageUrl()).toBe('blob:mock-3');
+ });
+
+ it('revokes the current object URL on destroy', () => {
+ const fixture = createFixture(1);
+ fixture.destroy();
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-1');
+ });
+
+ it('emits pageNumberChange from the pager buttons, clamped to [1, pageCount]', () => {
+ const fixture = createFixture(2, 3);
+ const component = fixture.componentInstance;
+ const emitted: number[] = [];
+ component.pageNumberChange.subscribe((n) => emitted.push(n));
+
+ component.next();
+ component.previous();
+ fixture.componentRef.setInput('pageNumber', 1);
+ fixture.detectChanges();
+ component.previous(); // no-op, already at page 1
+
+ expect(emitted).toEqual([3, 1]);
+ });
+
+ it('filters regions to only those whose page_numbers include the current page', () => {
+ const fixture = createFixture(1);
+ fixture.componentRef.setInput('regions', [
+ { target_field: 'a', page_numbers: [1], bbox: [0, 0, 0.5, 0.5] },
+ { target_field: 'b', page_numbers: [2], bbox: [0, 0, 0.5, 0.5] },
+ { target_field: 'c', page_numbers: [1, 2], bbox: [0, 0, 0.5, 0.5] },
+ ]);
+ fixture.detectChanges();
+
+ expect(fixture.componentInstance.regionsOnCurrentPage().map((r) => r.target_field)).toEqual(['a', 'c']);
+ });
+});
diff --git a/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts
new file mode 100644
index 0000000..5064de8
--- /dev/null
+++ b/src/app/connect/components/pdf-page-viewer/pdf-page-viewer.ts
@@ -0,0 +1,105 @@
+import { Component, OnDestroy, effect, inject, input, output, signal } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MatIconModule } from '@angular/material/icon';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { RegionSpec } from '../../api/api.types';
+import { PdfSourceApi } from '../../api/pdf-source.api';
+import { DrawnRegionBox, RegionDrawOverlay } from './region-draw-overlay.directive';
+
+/**
+ * Shows one PDF page at a time as an image, with a prev/next pager and a
+ * RegionDrawOverlay on top. The parent listens to `regionDrawn` and decides
+ * what a drawn box means.
+ *
+ * Page images are cached as Blobs rather than object URLs. The displayed
+ * URL is revoked on every navigation and a fresh one is created from the
+ * cached Blob, so no URL is leaked and no page is fetched twice.
+ */
+@Component({
+ imports: [MatButtonModule, MatIconModule, MatProgressBarModule, RegionDrawOverlay],
+ selector: 'app-pdf-page-viewer',
+ styleUrl: './pdf-page-viewer.scss',
+ templateUrl: './pdf-page-viewer.html',
+})
+export class PdfPageViewer implements OnDestroy {
+ readonly file = input.required();
+ readonly pageNumber = input.required();
+ readonly pageCount = input.required();
+ /** Drawn regions on all pages; only the current page's are rendered. */
+ readonly regions = input([]);
+
+ readonly pageNumberChange = output();
+ readonly regionDrawn = output();
+ readonly regionRemove = output();
+
+ private readonly pdfApi = inject(PdfSourceApi);
+
+ readonly imageUrl = signal(null);
+ readonly loading = signal(false);
+ readonly error = signal(null);
+
+ private readonly blobCache = new Map();
+ private currentObjectUrl: string | null = null;
+ private currentFile: File | null = null;
+
+ constructor() {
+ effect(() => {
+ const file = this.file();
+ const pageNumber = this.pageNumber();
+ if (file !== this.currentFile) {
+ this.blobCache.clear();
+ this.currentFile = file;
+ }
+ this.loadPage(file, pageNumber);
+ });
+ }
+
+ ngOnDestroy(): void {
+ if (this.currentObjectUrl) URL.revokeObjectURL(this.currentObjectUrl);
+ }
+
+ previous(): void {
+ if (this.pageNumber() > 1) this.pageNumberChange.emit(this.pageNumber() - 1);
+ }
+
+ next(): void {
+ if (this.pageNumber() < this.pageCount()) this.pageNumberChange.emit(this.pageNumber() + 1);
+ }
+
+ regionsOnCurrentPage(): RegionSpec[] {
+ return this.regions().filter((region) => region.page_numbers.includes(this.pageNumber()));
+ }
+
+ onRemoveClick(event: Event, region: RegionSpec): void {
+ event.stopPropagation();
+ this.regionRemove.emit(region);
+ }
+
+ private loadPage(file: File, pageNumber: number): void {
+ const cached = this.blobCache.get(pageNumber);
+ if (cached) {
+ this.showBlob(cached);
+ return;
+ }
+ this.loading.set(true);
+ this.error.set(null);
+ this.pdfApi.pageImage(file, pageNumber).subscribe({
+ next: (blob) => {
+ this.blobCache.set(pageNumber, blob);
+ this.loading.set(false);
+ this.showBlob(blob);
+ },
+ error: () => {
+ this.loading.set(false);
+ this.error.set('No se pudo cargar la página.');
+ },
+ });
+ }
+
+ private showBlob(blob: Blob): void {
+ const url = URL.createObjectURL(blob);
+ if (this.currentObjectUrl) URL.revokeObjectURL(this.currentObjectUrl);
+ this.currentObjectUrl = url;
+ this.imageUrl.set(url);
+ }
+}
diff --git a/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts
new file mode 100644
index 0000000..f170c06
--- /dev/null
+++ b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.spec.ts
@@ -0,0 +1,136 @@
+import { Component } from '@angular/core';
+import { TestBed } from '@angular/core/testing';
+import { By } from '@angular/platform-browser';
+import { DrawnRegionBox, RegionDrawOverlay } from './region-draw-overlay.directive';
+
+@Component({
+ imports: [RegionDrawOverlay],
+ template: `
`,
+})
+class TestHostComponent {
+ readonly drawn: DrawnRegionBox[] = [];
+ onRegionDrawn(box: DrawnRegionBox): void {
+ this.drawn.push(box);
+ }
+}
+
+function pointerEvent(clientX: number, clientY: number, pointerId = 1, button = 0): PointerEvent {
+ return { clientX, clientY, pointerId, button } as unknown as PointerEvent;
+}
+
+describe('RegionDrawOverlay', () => {
+ beforeEach(async () => {
+ await TestBed.configureTestingModule({ imports: [TestHostComponent] }).compileComponents();
+ });
+
+ function createFixture(rect: { left?: number; top?: number; width: number; height: number }) {
+ const fixture = TestBed.createComponent(TestHostComponent);
+ fixture.detectChanges();
+ const overlayEl = fixture.nativeElement.querySelector('.overlay') as HTMLElement;
+ vi.spyOn(overlayEl, 'getBoundingClientRect').mockReturnValue({
+ left: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ ...rect,
+ } as DOMRect);
+ const directive = fixture.debugElement.query(By.directive(RegionDrawOverlay)).injector.get(RegionDrawOverlay);
+ return { fixture, overlayEl, directive };
+ }
+
+ it('emits a normalized bbox (relative to the overlay, not the viewport) on a drag above the minimum threshold', () => {
+ const { fixture, directive } = createFixture({ left: 100, top: 50, width: 400, height: 300 });
+ const host = fixture.componentInstance;
+
+ directive.onPointerDown(pointerEvent(140, 80)); // 40,30 relative to the overlay's origin
+ directive.onPointerMove(pointerEvent(340, 230)); // 240,180 relative
+ directive.onPointerUp(pointerEvent(340, 230));
+
+ expect(host.drawn).toHaveLength(1);
+ const box = host.drawn[0];
+ expect(box.x0).toBeCloseTo(40 / 400);
+ expect(box.y0).toBeCloseTo(30 / 300);
+ expect(box.x1).toBeCloseTo(240 / 400);
+ expect(box.y1).toBeCloseTo(180 / 300);
+ });
+
+ it('normalizes corners regardless of drag direction (bottom-right to top-left still yields x0 {
+ const { fixture, directive } = createFixture({ width: 400, height: 300 });
+ const host = fixture.componentInstance;
+
+ directive.onPointerDown(pointerEvent(240, 180));
+ directive.onPointerMove(pointerEvent(40, 30));
+ directive.onPointerUp(pointerEvent(40, 30));
+
+ expect(host.drawn).toHaveLength(1);
+ const box = host.drawn[0];
+ expect(box.x0).toBeCloseTo(40 / 400);
+ expect(box.y0).toBeCloseTo(30 / 300);
+ expect(box.x1).toBeCloseTo(240 / 400);
+ expect(box.y1).toBeCloseTo(180 / 300);
+ expect(box.x0).toBeLessThan(box.x1);
+ expect(box.y0).toBeLessThan(box.y1);
+ });
+
+ it('produces the same normalized bbox for the same relative drag, independent of the overlay rect size/position', () => {
+ const drag = (rect: { left?: number; top?: number; width: number; height: number }) => {
+ const { fixture, directive } = createFixture(rect);
+ const host = fixture.componentInstance;
+ const left = rect.left ?? 0;
+ const top = rect.top ?? 0;
+ const { width, height } = rect;
+ // Same *relative* drag in both cases: from 10%,10% to 60%,70% of the overlay.
+ directive.onPointerDown(pointerEvent(left + width * 0.1, top + height * 0.1));
+ directive.onPointerMove(pointerEvent(left + width * 0.6, top + height * 0.7));
+ directive.onPointerUp(pointerEvent(left + width * 0.6, top + height * 0.7));
+ return host.drawn[0];
+ };
+
+ const small = drag({ width: 200, height: 100 });
+ const large = drag({ left: 500, top: 300, width: 1200, height: 900 });
+
+ expect(small).toBeDefined();
+ expect(large).toBeDefined();
+ expect(small.x0).toBeCloseTo(large.x0, 6);
+ expect(small.y0).toBeCloseTo(large.y0, 6);
+ expect(small.x1).toBeCloseTo(large.x1, 6);
+ expect(small.y1).toBeCloseTo(large.y1, 6);
+ });
+
+ it('ignores drags below the minimum pixel threshold, treating them as accidental clicks', () => {
+ const { fixture, directive } = createFixture({ width: 400, height: 300 });
+ const host = fixture.componentInstance;
+
+ directive.onPointerDown(pointerEvent(10, 10));
+ directive.onPointerMove(pointerEvent(12, 11));
+ directive.onPointerUp(pointerEvent(12, 11));
+
+ expect(host.drawn).toHaveLength(0);
+ });
+
+ it('exposes the in-progress drag via the exported liveBox signal, and clears it on pointerup', () => {
+ const { directive } = createFixture({ width: 400, height: 300 });
+
+ expect(directive.liveBox()).toBeNull();
+ directive.onPointerDown(pointerEvent(10, 10));
+ directive.onPointerMove(pointerEvent(60, 90));
+ expect(directive.liveBox()).toEqual({ x: 10, y: 10, width: 50, height: 80 });
+ directive.onPointerUp(pointerEvent(60, 90));
+ expect(directive.liveBox()).toBeNull();
+ });
+
+ it('ignores non-primary pointer buttons on pointerdown', () => {
+ const { fixture, directive } = createFixture({ width: 400, height: 300 });
+ const host = fixture.componentInstance;
+
+ directive.onPointerDown(pointerEvent(10, 10, 1, 2)); // right-click
+ directive.onPointerMove(pointerEvent(200, 200));
+ directive.onPointerUp(pointerEvent(200, 200));
+
+ expect(host.drawn).toHaveLength(0);
+ expect(directive.liveBox()).toBeNull();
+ });
+});
diff --git a/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts
new file mode 100644
index 0000000..2968b5f
--- /dev/null
+++ b/src/app/connect/components/pdf-page-viewer/region-draw-overlay.directive.ts
@@ -0,0 +1,97 @@
+import { Directive, ElementRef, HostListener, inject, output, signal } from '@angular/core';
+
+/** A normalized (0..1) region box, corners already sorted so x0();
+
+ readonly liveBox = signal(null);
+
+ private readonly element = inject(ElementRef);
+ private start: { x: number; y: number } | null = null;
+
+ @HostListener('pointerdown', ['$event'])
+ onPointerDown(event: PointerEvent): void {
+ if (event.button > 0) return;
+ const rect = this.element.nativeElement.getBoundingClientRect();
+ this.start = { x: event.clientX - rect.left, y: event.clientY - rect.top };
+ this.liveBox.set({ x: this.start.x, y: this.start.y, width: 0, height: 0 });
+ try {
+ this.element.nativeElement.setPointerCapture?.(event.pointerId);
+ } catch {
+ // Pointer capture is unsupported in some test environments; drawing
+ // still works through events dispatched on the host.
+ }
+ }
+
+ @HostListener('pointermove', ['$event'])
+ onPointerMove(event: PointerEvent): void {
+ if (!this.start) return;
+ const rect = this.element.nativeElement.getBoundingClientRect();
+ this.liveBox.set(this.boxFrom(this.start, { x: event.clientX - rect.left, y: event.clientY - rect.top }));
+ }
+
+ @HostListener('pointerup', ['$event'])
+ onPointerUp(event: PointerEvent): void {
+ if (!this.start) return;
+ const rect = this.element.nativeElement.getBoundingClientRect();
+ const box = this.boxFrom(this.start, { x: event.clientX - rect.left, y: event.clientY - rect.top });
+ this.start = null;
+ this.liveBox.set(null);
+ try {
+ if (this.element.nativeElement.hasPointerCapture?.(event.pointerId)) {
+ this.element.nativeElement.releasePointerCapture(event.pointerId);
+ }
+ } catch {
+ // Capture may be unsupported here, see onPointerDown.
+ }
+
+ if (box.width < MIN_DRAG_PX || box.height < MIN_DRAG_PX) return;
+ if (rect.width <= 0 || rect.height <= 0) return;
+ this.regionDrawn.emit({
+ x0: box.x / rect.width,
+ y0: box.y / rect.height,
+ x1: (box.x + box.width) / rect.width,
+ y1: (box.y + box.height) / rect.height,
+ });
+ }
+
+ private boxFrom(start: { x: number; y: number }, current: { x: number; y: number }): LiveDrawBox {
+ const x0 = Math.min(start.x, current.x);
+ const y0 = Math.min(start.y, current.y);
+ const x1 = Math.max(start.x, current.x);
+ const y1 = Math.max(start.y, current.y);
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
+ }
+}
diff --git a/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html
new file mode 100644
index 0000000..e43122e
--- /dev/null
+++ b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.html
@@ -0,0 +1,74 @@
+Dibujar regiones · {{ connection.label }}
+
+
+
+
+
+ Nombre de la tabla
+
+
+
+
+ Arrastra sobre la página para marcar cada columna. Cada región se vuelve una columna de origen: nómbrala (se
+ sugieren los campos de la base) y luego mapéala como cualquier otra tabla.
+ @if (connection.detection()?.has_text_layer === false) {
+ Documento escaneado: el texto se leerá por OCR.
+ }
+
+
+ @for (region of regions(); track $index) {
+
+
+ Columna
+
+
+ @for (option of suggestionsFor(nameInput.value); track option) {
+ {{ option }}
+ }
+
+
+
+ 1"
+ [disabled]="pageCount === 1"
+ (change)="setAllPages(region, $event.checked)"
+ >
+ Todas las páginas
+
+ {{ pagesLabel(region) }}
+
+ delete
+
+
+
+ } @empty {
+ crop_free Aún no hay regiones.
+ }
+ @if (duplicateNames().size > 0) {
+ Cada columna necesita un nombre único.
+ }
+
+
+
+ Cancelar
+
+ Agregar tabla ({{ regions().length }} columnas)
+
+
diff --git a/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss
new file mode 100644
index 0000000..e391529
--- /dev/null
+++ b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.scss
@@ -0,0 +1,72 @@
+.regions {
+ display: grid;
+ gap: var(--space-4);
+ grid-template-columns: minmax(0, 1fr) 340px;
+ max-height: 78vh;
+}
+
+.regions__viewer {
+ min-width: 0;
+ overflow: auto;
+}
+
+.regions__side {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ overflow: auto;
+}
+
+.regions__name {
+ width: 100%;
+}
+
+.regions__hint,
+.regions__empty {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+ margin: 0 0 var(--space-2);
+}
+
+.regions__empty {
+ align-items: center;
+ display: flex;
+ gap: var(--space-2);
+}
+
+.region {
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ padding: var(--space-2) var(--space-2) 0;
+}
+
+.region--invalid {
+ border-color: var(--mat-sys-error);
+}
+
+.region__name {
+ width: 100%;
+}
+
+.region__meta {
+ align-items: center;
+ display: flex;
+ gap: var(--space-1);
+}
+
+.region__pages {
+ color: var(--mat-sys-on-surface-variant);
+ flex: 1;
+ font: var(--mat-sys-body-small);
+}
+
+.regions__error {
+ color: var(--mat-sys-error);
+ font: var(--mat-sys-body-small);
+}
+
+@media (max-width: 960px) {
+ .regions {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts
new file mode 100644
index 0000000..062e9b9
--- /dev/null
+++ b/src/app/connect/components/pdf-regions-dialog/pdf-regions-dialog.ts
@@ -0,0 +1,106 @@
+import { Component, computed, inject, signal } from '@angular/core';
+import { MatAutocompleteModule } from '@angular/material/autocomplete';
+import { MatButtonModule } from '@angular/material/button';
+import { MatCheckboxModule } from '@angular/material/checkbox';
+import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
+import { MatFormFieldModule } from '@angular/material/form-field';
+import { MatIconModule } from '@angular/material/icon';
+import { MatInputModule } from '@angular/material/input';
+import { RegionSpec } from '../../api/api.types';
+import { PdfConnection } from '../../domain/pdf-source';
+import { PdfPageViewer } from '../pdf-page-viewer/pdf-page-viewer';
+import { DrawnRegionBox } from '../pdf-page-viewer/region-draw-overlay.directive';
+
+export interface PdfRegionsDialogData {
+ connection: PdfConnection;
+ /** Destination field names in the current domain, suggested as column names. */
+ fieldNames: string[];
+}
+
+export interface PdfRegionsResult {
+ name: string;
+ regions: RegionSpec[];
+}
+
+/**
+ * Draw one box per column over the rendered page (a column of a scanned
+ * table, a form field); each box becomes a named source column, read by
+ * OCR (or from the text layer when the page has one) and aligned into rows
+ * across all boxes on the page. "Todas las páginas" repeats a box on every
+ * page, which suits multi-page reports with a fixed layout.
+ */
+@Component({
+ selector: 'app-pdf-regions-dialog',
+ imports: [
+ MatAutocompleteModule,
+ MatButtonModule,
+ MatCheckboxModule,
+ MatDialogModule,
+ MatFormFieldModule,
+ MatIconModule,
+ MatInputModule,
+ PdfPageViewer,
+ ],
+ templateUrl: './pdf-regions-dialog.html',
+ styleUrl: './pdf-regions-dialog.scss',
+})
+export class PdfRegionsDialog {
+ readonly data = inject(MAT_DIALOG_DATA);
+ private readonly dialogRef = inject>(MatDialogRef);
+
+ readonly connection = this.data.connection;
+ readonly pageCount = this.connection.detection()?.page_count ?? 1;
+ readonly page = signal(1);
+ readonly regions = signal([]);
+ readonly name = signal(`Regiones ${this.connection.tables().filter((t) => t.removable).length + 1}`);
+
+ readonly duplicateNames = computed(() => {
+ const names = this.regions().map((region) => region.target_field.trim());
+ return new Set(names.filter((name, index) => !name || names.indexOf(name) !== index));
+ });
+
+ readonly canAccept = computed(() => this.regions().length > 0 && this.duplicateNames().size === 0 && !!this.name().trim());
+
+ onRegionDrawn(box: DrawnRegionBox): void {
+ const taken = new Set(this.regions().map((region) => region.target_field));
+ let index = this.regions().length + 1;
+ while (taken.has(`columna_${index}`)) index++;
+ this.regions.update((regions) => [
+ ...regions,
+ { target_field: `columna_${index}`, page_numbers: [this.page()], bbox: [box.x0, box.y0, box.x1, box.y1] },
+ ]);
+ }
+
+ rename(region: RegionSpec, value: string): void {
+ // Committed on change/Enter, not per keystroke: replacing the region
+ // object while typing re-renders the row and drops the input's focus.
+ this.regions.update((regions) => regions.map((r) => (r === region ? { ...r, target_field: value } : r)));
+ }
+
+ setAllPages(region: RegionSpec, allPages: boolean): void {
+ const pages = allPages ? Array.from({ length: this.pageCount }, (_, i) => i + 1) : [this.page()];
+ this.regions.update((regions) => regions.map((r) => (r === region ? { ...r, page_numbers: pages } : r)));
+ }
+
+ remove(region: RegionSpec): void {
+ this.regions.update((regions) => regions.filter((r) => r !== region));
+ }
+
+ suggestionsFor(value: string): string[] {
+ const term = value.trim().toLowerCase();
+ return this.data.fieldNames.filter((name) => !term || name.toLowerCase().includes(term)).slice(0, 30);
+ }
+
+ pagesLabel(region: RegionSpec): string {
+ return region.page_numbers.length === this.pageCount && this.pageCount > 1
+ ? `${this.pageCount} págs.`
+ : `pág. ${region.page_numbers.join(', ')}`;
+ }
+
+ accept(): void {
+ this.dialogRef.close({
+ name: this.name().trim(),
+ regions: this.regions().map((region) => ({ ...region, target_field: region.target_field.trim() })),
+ });
+ }
+}
diff --git a/src/app/connect/components/shared/autofocus.directive.ts b/src/app/connect/components/shared/autofocus.directive.ts
new file mode 100644
index 0000000..55f89d1
--- /dev/null
+++ b/src/app/connect/components/shared/autofocus.directive.ts
@@ -0,0 +1,13 @@
+import { Directive, ElementRef, afterNextRender, inject } from '@angular/core';
+
+/** Focuses and selects its input when it renders, for inline editors that appear on demand. */
+@Directive({ selector: 'input[appAutofocus]' })
+export class AutofocusDirective {
+ constructor() {
+ const element = inject>(ElementRef).nativeElement;
+ afterNextRender(() => {
+ element.focus();
+ element.select();
+ });
+ }
+}
diff --git a/src/app/connect/components/shared/flow-status.ts b/src/app/connect/components/shared/flow-status.ts
new file mode 100644
index 0000000..1b40d03
--- /dev/null
+++ b/src/app/connect/components/shared/flow-status.ts
@@ -0,0 +1,47 @@
+import { Component, computed, input } from '@angular/core';
+import { MatIconModule } from '@angular/material/icon';
+import { MatTooltipModule } from '@angular/material/tooltip';
+import { FlowStatus } from '../../domain/import-flow';
+
+const PRESENTATION: Record = {
+ loading: { label: 'Leyendo', icon: 'hourglass_top', tone: 'neutral', hint: 'Leyendo la fuente…' },
+ error: { label: 'Error', icon: 'error', tone: 'error', hint: 'No se pudo leer la fuente' },
+ incomplete: { label: 'Sin mapear', icon: 'rule', tone: 'warn', hint: 'Faltan campos obligatorios por asignar' },
+ ready: { label: 'Listo', icon: 'check_circle_outline', tone: 'neutral', hint: 'Mapeo completo, sin validar' },
+ validating: { label: 'Validando', icon: 'hourglass_top', tone: 'neutral', hint: 'Validando filas…' },
+ valid: { label: 'Válido', icon: 'verified', tone: 'ok', hint: 'Todas las filas pasan la validación' },
+ invalid: { label: 'Con errores', icon: 'report', tone: 'warn', hint: 'Algunas filas no pasan la validación y se omitirán' },
+ loaded: { label: 'Cargado', icon: 'cloud_done', tone: 'ok', hint: 'Escrito en la base de datos' },
+};
+
+/** Compact status pill for a flow (canvas cards, editor header, load dialog). */
+@Component({
+ selector: 'app-flow-status',
+ imports: [MatIconModule, MatTooltipModule],
+ template: `
+
+ {{ view().icon }} {{ view().label }}
+
+ `,
+ styles: `
+ .flow-status {
+ align-items: center;
+ border-radius: 999px;
+ display: inline-flex;
+ font: var(--mat-sys-label-medium);
+ gap: 4px;
+ padding: 2px 10px 2px 6px;
+ white-space: nowrap;
+ background: var(--mat-sys-surface-container-high);
+ color: var(--mat-sys-on-surface-variant);
+ }
+ .flow-status mat-icon { font-size: 16px; height: 16px; width: 16px; }
+ .flow-status[data-tone='ok'] { background: var(--mat-sys-primary-container); color: var(--mat-sys-on-primary-container); }
+ .flow-status[data-tone='warn'] { background: #fff1d6; color: #7a4b00; }
+ .flow-status[data-tone='error'] { background: var(--mat-sys-error-container); color: var(--mat-sys-on-error-container); }
+ `,
+})
+export class FlowStatusChip {
+ readonly status = input.required();
+ readonly view = computed(() => PRESENTATION[this.status()]);
+}
diff --git a/src/app/connect/components/shared/spanish-paginator-intl.ts b/src/app/connect/components/shared/spanish-paginator-intl.ts
new file mode 100644
index 0000000..99c241a
--- /dev/null
+++ b/src/app/connect/components/shared/spanish-paginator-intl.ts
@@ -0,0 +1,18 @@
+import { Injectable } from '@angular/core';
+import { MatPaginatorIntl } from '@angular/material/paginator';
+
+/** Material's paginator speaks English by default; the whole app is in Spanish. */
+@Injectable()
+export class SpanishPaginatorIntl extends MatPaginatorIntl {
+ override itemsPerPageLabel = 'Filas por página';
+ override nextPageLabel = 'Página siguiente';
+ override previousPageLabel = 'Página anterior';
+ override firstPageLabel = 'Primera página';
+ override lastPageLabel = 'Última página';
+ override getRangeLabel = (page: number, pageSize: number, length: number): string => {
+ if (length === 0 || pageSize === 0) return `0 de ${length}`;
+ const start = page * pageSize;
+ const end = Math.min(start + pageSize, length);
+ return `${start + 1} – ${end} de ${length}`;
+ };
+}
diff --git a/src/app/connect/components/shared/type-icon.pipe.ts b/src/app/connect/components/shared/type-icon.pipe.ts
new file mode 100644
index 0000000..a56cffb
--- /dev/null
+++ b/src/app/connect/components/shared/type-icon.pipe.ts
@@ -0,0 +1,41 @@
+import { Pipe, PipeTransform } from '@angular/core';
+
+const ICONS: Record = {
+ string: 'text_fields',
+ integer: 'tag',
+ float: 'numbers',
+ number: 'numbers',
+ boolean: 'toggle_on',
+ date: 'calendar_today',
+ datetime: 'schedule',
+ 'date-time': 'schedule',
+ binary: 'attachment',
+};
+
+const LABELS: Record = {
+ string: 'Texto',
+ integer: 'Entero',
+ float: 'Decimal',
+ number: 'Decimal',
+ boolean: 'Sí/No',
+ date: 'Fecha',
+ datetime: 'Fecha y hora',
+ 'date-time': 'Fecha y hora',
+ binary: 'Binario',
+};
+
+/** A column/field type (source `inferred_type` or target JSON-schema type) as a Material icon name. */
+@Pipe({ name: 'typeIcon' })
+export class TypeIconPipe implements PipeTransform {
+ transform(type: string | null | undefined): string {
+ return ICONS[type ?? ''] ?? 'help_outline';
+ }
+}
+
+/** The same type as a human label ("Fecha", "Entero"...). */
+@Pipe({ name: 'typeLabel' })
+export class TypeLabelPipe implements PipeTransform {
+ transform(type: string | null | undefined): string {
+ return LABELS[type ?? ''] ?? (type || 'Desconocido');
+ }
+}
diff --git a/src/app/connect/components/sql-query-dialog/sql-query-dialog.ts b/src/app/connect/components/sql-query-dialog/sql-query-dialog.ts
new file mode 100644
index 0000000..bdaecfa
--- /dev/null
+++ b/src/app/connect/components/sql-query-dialog/sql-query-dialog.ts
@@ -0,0 +1,116 @@
+import { Component, inject, signal } from '@angular/core';
+import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
+import { MatButtonModule } from '@angular/material/button';
+import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
+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 { MatTableModule } from '@angular/material/table';
+import { PreviewResponse, apiErrorMessage } from '../../api/api.types';
+import { SourceGateway } from '../../api/source-gateway';
+import { SqlConnection } from '../../domain/sql-source';
+
+export interface SqlQueryResult {
+ name: string;
+ query: string;
+}
+
+/**
+ * Custom SELECT against a database connection (joins, filters, computed
+ * columns), added to the connection as one more table. "Probar" runs it
+ * (read-only, first rows only) before it's accepted.
+ */
+@Component({
+ selector: 'app-sql-query-dialog',
+ imports: [MatButtonModule, MatDialogModule, MatFormFieldModule, MatIconModule, MatInputModule, MatProgressBarModule, MatTableModule, ReactiveFormsModule],
+ template: `
+ Consulta SQL · {{ connection.label }}
+
+
+ @if (running()) {
+
+ }
+ @if (error(); as message) {
+ error {{ message }}
+ }
+ @if (preview(); as result) {
+ {{ result.total_rows }} filas · {{ result.columns.length }} columnas
+
+
+ @for (column of result.columns; track column.name) {
+
+ {{ column.name }}
+ {{ row[column.name] }}
+
+ }
+
+
+
+
+ }
+
+
+ Cancelar
+
+ play_arrow Probar
+
+ Agregar
+
+ `,
+ styles: `
+ .query-form { display: grid; gap: 0; min-width: min(640px, 80vw); }
+ .query-form__sql textarea { font-family: 'Roboto Mono', ui-monospace, monospace; font-size: 13px; }
+ .query-error { align-items: center; color: var(--mat-sys-error); display: flex; gap: 8px; }
+ .query-summary { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-small); }
+ .query-preview { border: 1px solid var(--mat-sys-outline-variant); border-radius: 8px; max-width: 80vw; overflow: auto; }
+ `,
+})
+export class SqlQueryDialog {
+ readonly connection = inject(MAT_DIALOG_DATA);
+ private readonly dialogRef = inject>(MatDialogRef);
+ private readonly gateway = inject(SourceGateway);
+
+ readonly form = inject(FormBuilder).nonNullable.group({
+ name: [`Consulta ${this.connection.tables().filter((t) => t.removable).length + 1}`, Validators.required],
+ query: ['SELECT * FROM ', Validators.required],
+ });
+ readonly running = signal(false);
+ readonly error = signal(null);
+ readonly preview = signal(null);
+ readonly columnNames = signal([]);
+
+ constructor() {
+ this.form.controls.query.valueChanges.subscribe(() => this.preview.set(null));
+ }
+
+ run(): void {
+ this.running.set(true);
+ this.error.set(null);
+ this.gateway.sql.preview(this.connection.ref, { query: this.form.getRawValue().query }, null).subscribe({
+ next: (preview) => {
+ this.running.set(false);
+ this.preview.set(preview);
+ this.columnNames.set(preview.columns.map((column) => column.name));
+ },
+ error: (error) => {
+ this.running.set(false);
+ this.error.set(apiErrorMessage(error, 'La consulta falló.'));
+ },
+ });
+ }
+
+ accept(): void {
+ this.dialogRef.close(this.form.getRawValue());
+ }
+}
diff --git a/src/app/connect/components/validation-report/validation-report.html b/src/app/connect/components/validation-report/validation-report.html
new file mode 100644
index 0000000..2e3942e
--- /dev/null
+++ b/src/app/connect/components/validation-report/validation-report.html
@@ -0,0 +1,99 @@
+@let f = flow();
+@if (f.validating()) {
+
+}
+
+@if (f.validation(); as validation) {
+
+
+ {{ validation.total_rows | number }}
+ filas leídas
+
+
+ {{ validation.valid_count | number }}
+ válidas · {{ validPercent() }}%
+
+
0">
+ {{ validation.error_count | number }}
+ con errores (se omiten)
+
+ @if (f.result(); as result) {
+
+ {{ result.created | number }} / {{ result.updated | number }}
+ insertadas / actualizadas
+
+ }
+
+
+ @if (errors().length > 0) {
+
+
+ @for (item of countsByCategory(); track item.category) {
+ {{ categoryLabels[item.category] }} · {{ item.count }}
+ }
+
+
+ Campo
+
+ Todos
+ @for (name of fieldsWithErrors(); track name) {
+ {{ name }}
+ }
+
+
+
+
+
+
+ } @else {
+ verified Todas las filas pasan la validación.
+ }
+} @else if (!f.validating()) {
+
+
fact_check
+
+ La validación revisa todas las filas de la fuente contra las reglas de la tabla destino
+ (obligatorios, catálogos, formatos) sin escribir nada en la base.
+
+
+ play_arrow Validar ahora
+
+ @if (!f.canSubmit) {
+
Completa primero los campos obligatorios en «Mapeo».
+ }
+
+}
diff --git a/src/app/connect/components/validation-report/validation-report.scss b/src/app/connect/components/validation-report/validation-report.scss
new file mode 100644
index 0000000..365c64e
--- /dev/null
+++ b/src/app/connect/components/validation-report/validation-report.scss
@@ -0,0 +1,120 @@
+:host {
+ display: block;
+}
+
+.tiles {
+ display: grid;
+ gap: var(--space-3);
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ margin-bottom: var(--space-4);
+}
+
+.tile {
+ background: var(--mat-sys-surface-container-low);
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ display: flex;
+ flex-direction: column;
+ padding: var(--space-3) var(--space-4);
+}
+
+.tile__value {
+ font: var(--mat-sys-headline-small);
+}
+
+.tile__label {
+ color: var(--mat-sys-on-surface-variant);
+ font: var(--mat-sys-body-small);
+}
+
+.tile--ok .tile__value {
+ color: var(--mat-sys-primary);
+}
+
+.tile--warn .tile__value {
+ color: #9a5b00;
+}
+
+.filters {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+ margin-bottom: var(--space-3);
+}
+
+.filters__field {
+ width: 240px;
+}
+
+.table-scroll {
+ border: 1px solid var(--mat-sys-outline-variant);
+ border-radius: var(--mat-sys-corner-medium);
+ max-height: 50vh;
+ overflow: auto;
+}
+
+.errors {
+ --mat-table-row-item-container-height: 40px;
+ width: 100%;
+}
+
+.errors__field,
+.errors__value {
+ font-family: 'Roboto Mono', ui-monospace, monospace;
+ font-size: 12px;
+}
+
+.category {
+ border-radius: 999px;
+ font: var(--mat-sys-label-small);
+ padding: 2px 8px;
+ white-space: nowrap;
+ background: var(--mat-sys-surface-container-high);
+}
+
+.category[data-category='missing'],
+.category[data-category='conflict'] {
+ background: var(--mat-sys-error-container);
+ color: var(--mat-sys-on-error-container);
+}
+
+.category[data-category='out_of_catalog'],
+.category[data-category='type_invalid'] {
+ background: #fff1d6;
+ color: #7a4b00;
+}
+
+.all-good,
+.empty {
+ align-items: center;
+ color: var(--mat-sys-on-surface-variant);
+ display: flex;
+ gap: var(--space-2);
+}
+
+.all-good mat-icon {
+ color: var(--mat-sys-primary);
+}
+
+.empty {
+ flex-direction: column;
+ padding: var(--space-6);
+ text-align: center;
+
+ > mat-icon {
+ color: var(--mat-sys-primary);
+ font-size: 36px;
+ height: 36px;
+ width: 36px;
+ }
+
+ p {
+ margin: 0;
+ max-width: 520px;
+ }
+}
+
+.empty__hint {
+ font: var(--mat-sys-body-small);
+}
diff --git a/src/app/connect/components/validation-report/validation-report.ts b/src/app/connect/components/validation-report/validation-report.ts
new file mode 100644
index 0000000..1d463eb
--- /dev/null
+++ b/src/app/connect/components/validation-report/validation-report.ts
@@ -0,0 +1,100 @@
+import { DecimalPipe } from '@angular/common';
+import { Component, computed, input, output, signal } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
+import { MatChipsModule } from '@angular/material/chips';
+import { MatFormFieldModule } from '@angular/material/form-field';
+import { MatIconModule } from '@angular/material/icon';
+import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { MatSelectModule } from '@angular/material/select';
+import { MatTableModule } from '@angular/material/table';
+import { ErrorCategory, RowError } from '../../api/api.types';
+import { ImportFlow } from '../../domain/import-flow';
+
+export const CATEGORY_LABELS: Record = {
+ missing: 'Falta dato obligatorio',
+ out_of_catalog: 'Fuera de catálogo',
+ type_invalid: 'Formato inválido',
+ conflict: 'Ya existe (clave duplicada)',
+ merge_conflict: 'Difiere de otra fuente (se conservó la primera)',
+ unknown: 'Otro',
+};
+
+/** Validation outcome of one flow: totals, then every row error, filterable by category and field. */
+@Component({
+ selector: 'app-validation-report',
+ imports: [
+ DecimalPipe,
+ MatButtonModule,
+ MatChipsModule,
+ MatFormFieldModule,
+ MatIconModule,
+ MatPaginatorModule,
+ MatProgressBarModule,
+ MatSelectModule,
+ MatTableModule,
+ ],
+ templateUrl: './validation-report.html',
+ styleUrl: './validation-report.scss',
+})
+export class ValidationReport {
+ readonly flow = input.required();
+ readonly validate = output();
+
+ readonly categoryLabels = CATEGORY_LABELS;
+ readonly columns = ['row', 'field', 'category', 'value', 'message'];
+
+ readonly categories = signal([]);
+ readonly field = signal(null);
+ readonly page = signal({ index: 0, size: 25 });
+
+ readonly errors = computed(() => this.flow().validation()?.errors ?? []);
+
+ readonly countsByCategory = computed(() => {
+ const counts = new Map();
+ for (const error of this.errors()) counts.set(error.category, (counts.get(error.category) ?? 0) + 1);
+ return [...counts.entries()].map(([category, count]) => ({ category, count }));
+ });
+
+ readonly fieldsWithErrors = computed(() => [...new Set(this.errors().map((error) => error.field))].sort());
+
+ readonly filtered = computed(() => {
+ const categories = this.categories();
+ const field = this.field();
+ return this.errors().filter(
+ (error) => (categories.length === 0 || categories.includes(error.category)) && (!field || error.field === field),
+ );
+ });
+
+ readonly pageRows = computed(() => {
+ const { index, size } = this.page();
+ return this.filtered().slice(index * size, (index + 1) * size);
+ });
+
+ readonly validPercent = computed(() => {
+ const validation = this.flow().validation();
+ return validation && validation.total_rows ? Math.round((validation.valid_count / validation.total_rows) * 100) : 0;
+ });
+
+ onCategories(value: ErrorCategory[]): void {
+ this.categories.set(value);
+ this.page.update((page) => ({ ...page, index: 0 }));
+ }
+
+ onField(value: string | null): void {
+ this.field.set(value);
+ this.page.update((page) => ({ ...page, index: 0 }));
+ }
+
+ onPage(event: PageEvent): void {
+ this.page.set({ index: event.pageIndex, size: event.pageSize });
+ }
+
+ categoryLabel(category: ErrorCategory): string {
+ return CATEGORY_LABELS[category] ?? category;
+ }
+
+ display(value: unknown): string {
+ return value === null || value === undefined || value === '' ? '(vacío)' : String(value);
+ }
+}
diff --git a/src/app/connect/domain/connection-registry.spec.ts b/src/app/connect/domain/connection-registry.spec.ts
new file mode 100644
index 0000000..f497cd3
--- /dev/null
+++ b/src/app/connect/domain/connection-registry.spec.ts
@@ -0,0 +1,52 @@
+import { ConnectorInfo } from '../api/api.types';
+import { acceptedExtensions, connectionsFor, connectionsForFiles, kindForFile } from './connection-registry';
+import { DocumentConnection } from './document-source';
+import { EegConnection } from './eeg-source';
+import { FileConnection } from './file-source';
+import { PdfConnection } from './pdf-source';
+
+const connector = (kind: ConnectorInfo['kind'], extensions: string[], category: ConnectorInfo['category'] = 'file'): ConnectorInfo => ({
+ kind,
+ label: kind,
+ description: '',
+ category,
+ icon: 'x',
+ extensions,
+});
+
+const CATALOG: ConnectorInfo[] = [
+ connector('csv', ['csv', 'txt']),
+ connector('excel', ['xlsx']),
+ connector('pdf', ['pdf'], 'document'),
+ connector('document', ['pdf', 'png', 'tif'], 'document'),
+ connector('edf', ['edf'], 'signal'),
+ connector('sql', [], 'database'),
+];
+
+describe('connection registry', () => {
+ it('picks the first connector that reads an extension, as the server does', () => {
+ expect(kindForFile('a.CSV', CATALOG)).toBe('csv');
+ expect(kindForFile('reporte.pdf', CATALOG)).toBe('pdf');
+ expect(kindForFile('escaneo.tif', CATALOG)).toBe('document');
+ expect(kindForFile('notas.docx', CATALOG)).toBeNull();
+ expect(acceptedExtensions(CATALOG)).toEqual(['csv', 'txt', 'xlsx', 'pdf', 'png', 'tif', 'edf']);
+ });
+
+ it('one connection per tabular file, one for all recordings or documents dropped together', () => {
+ const files = ['a.csv', 'b.csv', 'r1.edf', 'r2.edf', 'p.png', 'q.tif', 'x.docx', 'informe.pdf'].map((name) => new File(['x'], name));
+ const { connections, rejected } = connectionsForFiles(files, CATALOG);
+ expect(rejected.map((file) => file.name)).toEqual(['x.docx']);
+ expect(connections.filter((c) => c instanceof FileConnection)).toHaveLength(2);
+ const [eeg] = connections.filter((c) => c instanceof EegConnection) as EegConnection[];
+ expect(eeg.files).toHaveLength(2);
+ expect(eeg.label).toBe('2 registros EEG');
+ const [documents] = connections.filter((c) => c instanceof DocumentConnection) as DocumentConnection[];
+ expect(documents.files.map((f) => f.name)).toEqual(['p.png', 'q.tif']);
+ expect(connections.some((c) => c instanceof PdfConnection)).toBe(true);
+ });
+
+ it('the connector picked in the gallery decides, e.g. PDFs read as documents', () => {
+ const [connection] = connectionsFor('document', [new File(['x'], 'a.pdf'), new File(['y'], 'b.pdf')]);
+ expect(connection).toBeInstanceOf(DocumentConnection);
+ });
+});
diff --git a/src/app/connect/domain/connection-registry.ts b/src/app/connect/domain/connection-registry.ts
new file mode 100644
index 0000000..cec14a7
--- /dev/null
+++ b/src/app/connect/domain/connection-registry.ts
@@ -0,0 +1,52 @@
+import { ConnectorInfo, SourceType } from '../api/api.types';
+import { DataConnection } from './data-source';
+import { DocumentConnection } from './document-source';
+import { EegConnection } from './eeg-source';
+import { FileConnection } from './file-source';
+import { PdfConnection } from './pdf-source';
+
+/** Turns the files chosen for one source kind into workspace connections. */
+export type ConnectionFactory = (files: File[]) => DataConnection[];
+
+const FACTORIES = new Map([
+ ['csv', (files) => files.map((file) => new FileConnection(file, 'csv'))],
+ ['excel', (files) => files.map((file) => new FileConnection(file, 'excel'))],
+ ['json', (files) => files.map((file) => new FileConnection(file, 'json'))],
+ ['pdf', (files) => files.map((file) => new PdfConnection(file))],
+ // Several recordings or documents are read together: one connection, one table.
+ ['edf', (files) => [new EegConnection(files)]],
+ ['document', (files) => [new DocumentConnection(files)]],
+]);
+
+/** Adding a file source on the client is one `DataConnection` subclass and one call here. */
+export function registerConnectionFactory(kind: SourceType, factory: ConnectionFactory): void {
+ FACTORIES.set(kind, factory);
+}
+
+export function connectionsFor(kind: SourceType, files: File[]): DataConnection[] {
+ const factory = FACTORIES.get(kind);
+ return factory && files.length ? factory(files) : [];
+}
+
+/** First connector (in the server's order) that reads this extension, like the server does. */
+export function kindForFile(fileName: string, connectors: ConnectorInfo[]): SourceType | null {
+ const extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
+ return connectors.find((c) => FACTORIES.has(c.kind) && c.extensions.includes(extension))?.kind ?? null;
+}
+
+export function acceptedExtensions(connectors: ConnectorInfo[]): string[] {
+ return [...new Set(connectors.filter((c) => FACTORIES.has(c.kind)).flatMap((c) => c.extensions))];
+}
+
+/** Dropped files grouped by kind; unsupported ones come back in `rejected`. */
+export function connectionsForFiles(files: File[], connectors: ConnectorInfo[]): { connections: DataConnection[]; rejected: File[] } {
+ const byKind = new Map();
+ const rejected: File[] = [];
+ for (const file of files) {
+ const kind = kindForFile(file.name, connectors);
+ if (kind) byKind.set(kind, [...(byKind.get(kind) ?? []), file]);
+ else rejected.push(file);
+ }
+ const connections = [...byKind].flatMap(([kind, group]) => connectionsFor(kind, group));
+ return { connections, rejected };
+}
diff --git a/src/app/connect/domain/connector-catalog.spec.ts b/src/app/connect/domain/connector-catalog.spec.ts
new file mode 100644
index 0000000..9df1728
--- /dev/null
+++ b/src/app/connect/domain/connector-catalog.spec.ts
@@ -0,0 +1,24 @@
+import { galleryEntries } from './connector-catalog';
+
+describe('galleryEntries', () => {
+ it('expands SQL into one tile per engine plus a raw connection string, unavailable drivers disabled', () => {
+ const entries = galleryEntries([
+ { kind: 'csv', label: 'CSV', description: 'd', category: 'file', icon: 'table_view', extensions: ['csv'] },
+ {
+ kind: 'sql',
+ label: 'Base de datos',
+ description: '',
+ category: 'database',
+ icon: 'storage',
+ extensions: [],
+ engines: [
+ { id: 'mysql', label: 'MySQL', description: 'MySQL 8', default_port: 3306, default_schema: null, available: true },
+ { id: 'mssql', label: 'SQL Server', description: 'SQL Server', default_port: 1433, default_schema: 'dbo', available: false },
+ ],
+ },
+ ]);
+ expect(entries.map((e) => e.id)).toEqual(['csv', 'sql-mysql', 'sql-mssql', 'sql-url']);
+ expect(entries.find((e) => e.id === 'sql-mssql')?.available).toBe(false);
+ expect(entries.find((e) => e.id === 'sql-url')?.engine).toBe('url');
+ });
+});
diff --git a/src/app/connect/domain/connector-catalog.ts b/src/app/connect/domain/connector-catalog.ts
new file mode 100644
index 0000000..321ec9f
--- /dev/null
+++ b/src/app/connect/domain/connector-catalog.ts
@@ -0,0 +1,62 @@
+import { ConnectorCategory, ConnectorInfo, SqlEngineInfo } from '../api/api.types';
+
+/**
+ * The "Obtener datos" gallery, built from what the server reports it can
+ * read (`GET /imports/connectors`): one tile per connector, and one per
+ * database engine for SQL. A new connector on the server shows up here
+ * without client changes.
+ */
+export type GalleryCategory = ConnectorCategory | 'all';
+
+export interface GalleryEntry {
+ id: string;
+ name: string;
+ description: string;
+ icon: string;
+ category: ConnectorCategory;
+ connector: ConnectorInfo;
+ /** SQL tiles: the engine the connection form is for; `url` for a raw connection string. */
+ engine?: SqlEngineInfo | 'url';
+ /** False when the server lacks what this tile needs (e.g. a database driver). */
+ available: boolean;
+}
+
+export const GALLERY_CATEGORIES: { id: GalleryCategory; label: string; icon: string }[] = [
+ { id: 'all', label: 'Todos', icon: 'apps' },
+ { id: 'file', label: 'Archivo', icon: 'folder_open' },
+ { id: 'database', label: 'Base de datos', icon: 'storage' },
+ { id: 'document', label: 'Documento', icon: 'description' },
+ { id: 'signal', label: 'Señales', icon: 'monitor_heart' },
+];
+
+export function galleryEntries(connectors: ConnectorInfo[]): GalleryEntry[] {
+ return connectors.flatMap((connector): GalleryEntry[] => {
+ if (connector.kind !== 'sql') {
+ return [{ ...pick(connector), id: connector.kind, name: connector.label, connector, available: true }];
+ }
+ const engines = (connector.engines ?? []).map((engine) => ({
+ ...pick(connector),
+ id: `sql-${engine.id}`,
+ name: engine.label,
+ description: engine.available ? engine.description : `${engine.description} (driver no instalado en el servidor)`,
+ connector,
+ engine,
+ available: engine.available,
+ }));
+ const raw: GalleryEntry = {
+ ...pick(connector),
+ id: 'sql-url',
+ name: 'Otra base de datos',
+ description: 'Cadena de conexión SQLAlchemy (avanzado)',
+ icon: 'link',
+ connector,
+ engine: 'url',
+ available: true,
+ };
+ return [...engines, raw];
+ });
+}
+
+function pick(connector: ConnectorInfo) {
+ return { description: connector.description, icon: connector.icon, category: connector.category };
+}
diff --git a/src/app/connect/domain/data-source.ts b/src/app/connect/domain/data-source.ts
new file mode 100644
index 0000000..d504e0f
--- /dev/null
+++ b/src/app/connect/domain/data-source.ts
@@ -0,0 +1,121 @@
+import { Signal, signal } from '@angular/core';
+import { Observable, catchError, map, of, tap } from 'rxjs';
+import { PreviewResponse, SourceLocator, apiErrorMessage } from '../api/api.types';
+import { SourceGateway } from '../api/source-gateway';
+
+let sequence = 0;
+const nextId = (prefix: string) => `${prefix}-${++sequence}`;
+
+export type ConnectionState = 'loading' | 'ready' | 'error';
+
+/**
+ * A place data comes from (a file, a database, a set of documents): the
+ * "Conexiones" of the workspace. It exposes `SourceTable`s (Excel sheets,
+ * database tables, a PDF's tables), which are what gets mapped.
+ *
+ * Each kind is one subclass (`file-source.ts`, `sql-source.ts`,
+ * `pdf-source.ts`, `eeg-source.ts`, `document-source.ts`) that owns how its
+ * tables are discovered and previewed; nothing else switches on the kind.
+ * New kinds are wired to file extensions in `connection-registry.ts`.
+ */
+export abstract class DataConnection {
+ readonly id = nextId('conn');
+ abstract readonly icon: string;
+ abstract readonly typeLabel: string;
+
+ private readonly _tables = signal([]);
+ private readonly _state = signal('loading');
+ private readonly _error = signal(null);
+
+ readonly tables: Signal = this._tables.asReadonly();
+ readonly state: Signal = this._state.asReadonly();
+ readonly error: Signal = this._error.asReadonly();
+
+ constructor(readonly label: string) {}
+
+ /** A connection that can only ever have one table (a CSV) is shown flat, without a table level. */
+ get singleTable(): boolean {
+ return false;
+ }
+
+ /** Discovers this connection's tables. Does not throw; failures are reported in `state`/`error`. */
+ load(gateway: SourceGateway): Observable {
+ this._state.set('loading');
+ this._error.set(null);
+ return this.discover(gateway).pipe(
+ tap((tables) => {
+ this._tables.set(tables);
+ this._state.set('ready');
+ }),
+ map(() => undefined),
+ catchError((error) => {
+ this._error.set(apiErrorMessage(error, `No se pudo abrir ${this.label}.`));
+ this._state.set('error');
+ return of(undefined);
+ }),
+ );
+ }
+
+ addTable(table: SourceTable): void {
+ this._tables.update((tables) => [...tables, table]);
+ }
+
+ removeTable(table: SourceTable): void {
+ this._tables.update((tables) => tables.filter((existing) => existing !== table));
+ }
+
+ protected abstract discover(gateway: SourceGateway): Observable;
+}
+
+/**
+ * One tabular source inside a connection, the unit dragged onto the canvas
+ * to create an import flow. Previews itself against a target entity and
+ * describes itself to the backend (`SourceLocator`); knows nothing about
+ * mapping.
+ */
+export abstract class SourceTable {
+ readonly id = nextId('table');
+ abstract readonly icon: string;
+ /** What kind of table this is, for the UI: "Hoja", "Tabla", "Consulta SQL"... */
+ abstract readonly kindLabel: string;
+
+ constructor(
+ readonly connection: DataConnection,
+ readonly name: string,
+ ) {}
+
+ get label(): string {
+ return this.connection.singleTable ? this.connection.label : `${this.connection.label} › ${this.name}`;
+ }
+
+ /** Whether the user created this table (a custom query, drawn regions) and may remove it. */
+ get removable(): boolean {
+ return false;
+ }
+
+ abstract preview(gateway: SourceGateway, target: string | null): Observable;
+
+ /** `target`: the entity the rows go to, for sources whose reading depends on it. */
+ abstract locator(target?: string): Promise;
+}
+
+/** Lazily computed base64 of a file, shared by every table of a connection. */
+export class EncodedFile {
+ private encoded: Promise | null = null;
+
+ constructor(
+ readonly file: File,
+ private readonly encode: (file: File) => Promise,
+ ) {}
+
+ base64(): Promise {
+ this.encoded ??= this.encode(this.file);
+ return this.encoded;
+ }
+}
+
+
+/** Encoded `{name, file_base64}` entries, the shape multi-file payloads use. */
+export async function encodeFiles(files: EncodedFile[]): Promise<{ name: string; file_base64: string }[]> {
+ return Promise.all(files.map(async (encoded) => ({ name: encoded.file.name, file_base64: await encoded.base64() })));
+}
diff --git a/src/app/connect/domain/document-source.spec.ts b/src/app/connect/domain/document-source.spec.ts
new file mode 100644
index 0000000..b370c48
--- /dev/null
+++ b/src/app/connect/domain/document-source.spec.ts
@@ -0,0 +1,60 @@
+import { firstValueFrom, of } from 'rxjs';
+import { SourceGateway } from '../api/source-gateway';
+import { DocumentConnection, DocumentTable } from './document-source';
+import { PdfConnection } from './pdf-source';
+
+describe('DocumentTable', () => {
+ const extraction = { columns: [], sample_rows: [], total_rows: 1, suggested_mapping: [], key_field: 'pac_id_hospital', fields: [], records: [] };
+
+ function table(): DocumentTable {
+ const connection = new DocumentConnection([new File(['a'], 'a.pdf'), new File(['b'], 'b.png')]);
+ return new DocumentTable(connection, 'Registros');
+ }
+
+ it('sends every file, the settings and the corrections for the flow target only', async () => {
+ const t = table();
+ t.configure({ segmentation: 'pages', pages_per_record: 2, ocr_mode: 'always', key_pattern: ' EXP-\\d+ ' }, {
+ 'cacu.Paciente': { '0': { pac_sexo: 'F' } },
+ 'cacu.CitologiaCervical': { '1': { cit_vph_resultado: 'NEGATIVO' } },
+ });
+ const locator = await t.locator('cacu.Paciente');
+ expect(locator).toEqual({
+ source_type: 'document',
+ payload: {
+ files: [
+ { name: 'a.pdf', file_base64: btoa('a') },
+ { name: 'b.png', file_base64: btoa('b') },
+ ],
+ segmentation: 'pages',
+ pages_per_record: 2,
+ ocr_mode: 'always',
+ key_pattern: 'EXP-\\d+',
+ overrides: { '0': { pac_sexo: 'F' } },
+ },
+ });
+ });
+
+ it('changing how pages are split drops corrections, which point at record numbers', () => {
+ const t = table();
+ t.configure(t.settings(), { 'cacu.Paciente': { '0': { pac_sexo: 'F' } } });
+ t.configure({ ...t.settings(), segmentation: 'document' });
+ expect(t.overrides('cacu.Paciente')).toEqual({});
+ });
+
+ it('keeps the last extraction per target', async () => {
+ const t = table();
+ const calls: unknown[][] = [];
+ const gateway = { document: { extract: (...args: unknown[]) => (calls.push(args), of(extraction)) } } as unknown as SourceGateway;
+ await firstValueFrom(t.preview(gateway, 'cacu.Paciente'));
+ expect(t.extractions()['cacu.Paciente']).toBe(extraction);
+ expect(calls[0][1]).toBe('cacu.Paciente');
+ });
+
+ it('a PDF offers its whole text as a document table next to its detected tables', () => {
+ const gateway = { pdf: { detect: () => of({ page_count: 1, has_text_layer: false, table_candidates: [] }) } } as unknown as SourceGateway;
+ const pdf = new PdfConnection(new File(['%PDF'], 'informe.pdf'));
+ pdf.load(gateway).subscribe();
+ expect(pdf.tables()).toEqual([pdf.documentTable]);
+ expect(pdf.documentTable.files.map((f) => f.name)).toEqual(['informe.pdf']);
+ });
+});
diff --git a/src/app/connect/domain/document-source.ts b/src/app/connect/domain/document-source.ts
new file mode 100644
index 0000000..3da343c
--- /dev/null
+++ b/src/app/connect/domain/document-source.ts
@@ -0,0 +1,110 @@
+import { Signal, signal } from '@angular/core';
+import { Observable, from, of, switchMap, tap } from 'rxjs';
+import { DocumentExtraction, DocumentSettings, PreviewResponse, SourceLocator } from '../api/api.types';
+import { fileToBase64 } from '../api/file-encoding';
+import { SourceGateway } from '../api/source-gateway';
+import { DataConnection, EncodedFile, SourceTable, encodeFiles } from './data-source';
+
+/** A connection whose files can be read as clinical documents. */
+export interface DocumentFiles {
+ readonly encodedFiles: EncodedFile[];
+}
+
+export const DEFAULT_DOCUMENT_SETTINGS: DocumentSettings = {
+ segmentation: 'auto',
+ pages_per_record: 1,
+ ocr_mode: 'auto',
+ key_pattern: '',
+};
+
+export type FieldOverrides = Record>;
+
+/**
+ * Reports, forms and notes (PDF or images) that aren't tables. The server
+ * splits them into one record per patient (however many pages or files
+ * that takes) and fills the target entity's fields from labels and free
+ * text; see `DocumentTable`.
+ */
+export class DocumentConnection extends DataConnection implements DocumentFiles {
+ readonly icon = 'document_scanner';
+ readonly typeLabel = 'Documentos clínicos';
+ readonly encodedFiles: EncodedFile[];
+
+ constructor(readonly files: File[]) {
+ super(files.length === 1 ? files[0].name : `${files.length} documentos`);
+ this.encodedFiles = files.map((file) => new EncodedFile(file, fileToBase64));
+ }
+
+ override get singleTable(): boolean {
+ return true;
+ }
+
+ protected discover(): Observable {
+ return of([new DocumentTable(this, 'Registros por paciente')]);
+ }
+}
+
+/**
+ * The records extracted from a connection's documents. Extraction depends
+ * on the target entity (which fields to look for), so the last result and
+ * the user's corrections are kept per target. Settings and corrections
+ * travel in the payload; the server re-extracts on every call.
+ */
+export class DocumentTable extends SourceTable {
+ readonly icon = 'document_scanner';
+ readonly kindLabel = 'Extracción de campos';
+
+ private readonly _settings = signal(DEFAULT_DOCUMENT_SETTINGS);
+ private readonly _overrides = signal>({});
+ private readonly _extractions = signal>({});
+
+ readonly settings: Signal = this._settings.asReadonly();
+ readonly extractions = this._extractions.asReadonly();
+
+ constructor(
+ override readonly connection: DataConnection & DocumentFiles,
+ name: string,
+ ) {
+ super(connection, name);
+ }
+
+ get files(): File[] {
+ return this.connection.encodedFiles.map((encoded) => encoded.file);
+ }
+
+ overrides(target: string): FieldOverrides {
+ return this._overrides()[target] ?? {};
+ }
+
+ /** Settings apply to every target: they decide how pages become records. */
+ configure(settings: DocumentSettings, overridesByTarget?: Record): void {
+ const resegmented = JSON.stringify(settings) !== JSON.stringify(this._settings());
+ this._settings.set(settings);
+ // Record numbers change when the segmentation does; old corrections would land on the wrong patient.
+ if (resegmented) this._overrides.set({});
+ if (overridesByTarget) this._overrides.update((all) => ({ ...all, ...overridesByTarget }));
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ if (!target) return of({ columns: [], sample_rows: [], total_rows: null, suggested_mapping: [] });
+ return from(this.payload(target)).pipe(
+ switchMap((payload) => gateway.document.extract(payload, target)),
+ tap((extraction) => this._extractions.update((all) => ({ ...all, [target]: extraction }))),
+ );
+ }
+
+ async locator(target?: string): Promise {
+ return { source_type: 'document', payload: await this.payload(target) };
+ }
+
+ private async payload(target?: string): Promise> {
+ const { key_pattern, ...settings } = this._settings();
+ const overrides = target ? this.overrides(target) : {};
+ return {
+ files: await encodeFiles(this.connection.encodedFiles),
+ ...settings,
+ ...(key_pattern.trim() ? { key_pattern: key_pattern.trim() } : {}),
+ ...(Object.keys(overrides).length ? { overrides } : {}),
+ };
+ }
+}
diff --git a/src/app/connect/domain/eeg-source.ts b/src/app/connect/domain/eeg-source.ts
new file mode 100644
index 0000000..3505bb1
--- /dev/null
+++ b/src/app/connect/domain/eeg-source.ts
@@ -0,0 +1,52 @@
+import { Observable, from, map, switchMap } from 'rxjs';
+import { PreviewResponse, SourceLocator } from '../api/api.types';
+import { fileToBase64 } from '../api/file-encoding';
+import { SourceGateway } from '../api/source-gateway';
+import { DataConnection, EncodedFile, SourceTable, encodeFiles } from './data-source';
+
+/**
+ * EEG recordings (`.edf`). All files added together form one table with a
+ * row per recording: header data, an estimated background rhythm and the
+ * file itself, shaped for TEA's `EegEstudio`.
+ */
+export class EegConnection extends DataConnection {
+ readonly icon = 'monitor_heart';
+ readonly typeLabel = 'EEG (EDF)';
+ readonly encoded: EncodedFile[];
+
+ constructor(readonly files: File[]) {
+ super(files.length === 1 ? files[0].name : `${files.length} registros EEG`);
+ this.encoded = files.map((file) => new EncodedFile(file, fileToBase64));
+ }
+
+ override get singleTable(): boolean {
+ return true;
+ }
+
+ async payload(): Promise> {
+ return { files: await encodeFiles(this.encoded) };
+ }
+
+ protected discover(gateway: SourceGateway): Observable {
+ // Reading the headers up front rejects files MNE can't open.
+ const table = new EegTable(this);
+ return table.preview(gateway, null).pipe(map(() => [table]));
+ }
+}
+
+export class EegTable extends SourceTable {
+ readonly icon = 'monitor_heart';
+ readonly kindLabel = 'Registros';
+
+ constructor(override readonly connection: EegConnection) {
+ super(connection, 'Registros');
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ return from(this.connection.payload()).pipe(switchMap((payload) => gateway.file.previewPayload('edf', payload, target)));
+ }
+
+ async locator(): Promise {
+ return { source_type: 'edf', payload: await this.connection.payload() };
+ }
+}
diff --git a/src/app/connect/domain/file-source.spec.ts b/src/app/connect/domain/file-source.spec.ts
new file mode 100644
index 0000000..7de3d21
--- /dev/null
+++ b/src/app/connect/domain/file-source.spec.ts
@@ -0,0 +1,47 @@
+import { of, throwError } from 'rxjs';
+import { SourceGateway } from '../api/source-gateway';
+import { FileConnection } from './file-source';
+import { preview } from '../testing/fakes';
+
+describe('FileConnection', () => {
+ it('exposes one table per Excel sheet, each previewing and loading with its sheet_name', async () => {
+ const calls: unknown[][] = [];
+ const gateway = {
+ file: {
+ preview: (...args: unknown[]) => {
+ calls.push(args);
+ return of(preview({ tables: ['Órdenes', 'Notas'].map((name) => ({ name, options: { sheet_name: name }, kind: 'sheet' })) }));
+ },
+ },
+ } as unknown as SourceGateway;
+
+ const connection = new FileConnection(new File(['x'], 'libro.xlsx'), 'excel');
+ connection.load(gateway).subscribe();
+ expect(connection.state()).toBe('ready');
+ expect(connection.tables().map((t) => t.name)).toEqual(['Órdenes', 'Notas']);
+ expect(connection.tables()[1].label).toBe('libro.xlsx › Notas');
+
+ connection.tables()[1].preview(gateway, 'cacu.NotaMedica').subscribe();
+ expect(calls.at(-1)?.slice(1)).toEqual(['excel', 'cacu.NotaMedica', { sheet_name: 'Notas' }]);
+
+ const locator = await connection.tables()[1].locator();
+ expect(locator).toEqual({ source_type: 'excel', payload: { file_base64: btoa('x'), options: { sheet_name: 'Notas' } } });
+ });
+
+ it('a CSV is a single table labelled by the file name', () => {
+ const gateway = { file: { preview: () => of(preview()) } } as unknown as SourceGateway;
+ const connection = new FileConnection(new File(['a,b'], 'p.csv'), 'csv');
+ connection.load(gateway).subscribe();
+ expect(connection.singleTable).toBe(true);
+ expect(connection.tables().map((t) => t.label)).toEqual(['p.csv']);
+ });
+
+ it('a file that fails to parse lands in the error state with the backend message', () => {
+ const gateway = { file: { preview: () => throwError(() => ({ error: { error: 'could not parse CSV' } })) } } as unknown as SourceGateway;
+ const connection = new FileConnection(new File(['?'], 'x.csv'), 'csv');
+ connection.load(gateway).subscribe();
+ expect(connection.state()).toBe('error');
+ expect(connection.error()).toBe('could not parse CSV');
+ expect(connection.tables()).toEqual([]);
+ });
+});
diff --git a/src/app/connect/domain/file-source.ts b/src/app/connect/domain/file-source.ts
new file mode 100644
index 0000000..2c4e737
--- /dev/null
+++ b/src/app/connect/domain/file-source.ts
@@ -0,0 +1,69 @@
+import { Observable, map } from 'rxjs';
+import { FileKind, FileOptions, PreviewResponse, SourceLocator } from '../api/api.types';
+import { fileToBase64 } from '../api/file-encoding';
+import { SourceGateway } from '../api/source-gateway';
+import { DataConnection, EncodedFile, SourceTable } from './data-source';
+
+const FILE_PRESENTATION: Record = {
+ csv: { icon: 'table_view', typeLabel: 'Texto / CSV' },
+ excel: { icon: 'grid_on', typeLabel: 'Libro de Excel' },
+ json: { icon: 'data_object', typeLabel: 'JSON' },
+};
+
+/** A CSV, Excel or JSON file. Excel exposes one table per sheet; CSV/JSON exactly one. */
+export class FileConnection extends DataConnection {
+ readonly icon: string;
+ readonly typeLabel: string;
+ readonly encoded: EncodedFile;
+
+ constructor(
+ readonly file: File,
+ readonly fileKind: FileKind,
+ ) {
+ super(file.name);
+ this.icon = FILE_PRESENTATION[fileKind].icon;
+ this.typeLabel = FILE_PRESENTATION[fileKind].typeLabel;
+ this.encoded = new EncodedFile(file, fileToBase64);
+ }
+
+ override get singleTable(): boolean {
+ return this.fileKind !== 'excel';
+ }
+
+ protected discover(gateway: SourceGateway): Observable {
+ // A target-less preview proves the file parses and lists its sub-tables (Excel sheets).
+ return gateway.file.preview(this.file, this.fileKind, null).pipe(
+ map((preview) => {
+ const tables = preview.tables ?? [];
+ if (!tables.length) return [new FileTable(this, this.file.name, {})];
+ return tables.map((table) => new FileTable(this, table.name, table.options as FileOptions));
+ }),
+ );
+ }
+}
+
+export class FileTable extends SourceTable {
+ readonly icon: string;
+ readonly kindLabel: string;
+
+ constructor(
+ override readonly connection: FileConnection,
+ name: string,
+ readonly options: FileOptions,
+ ) {
+ super(connection, name);
+ this.icon = connection.fileKind === 'excel' ? 'tab' : connection.icon;
+ this.kindLabel = connection.fileKind === 'excel' ? 'Hoja' : 'Archivo';
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ return gateway.file.preview(this.connection.file, this.connection.fileKind, target, this.options);
+ }
+
+ async locator(): Promise {
+ return {
+ source_type: this.connection.fileKind,
+ payload: { file_base64: await this.connection.encoded.base64(), options: this.options },
+ };
+ }
+}
diff --git a/src/app/connect/domain/import-flow.spec.ts b/src/app/connect/domain/import-flow.spec.ts
new file mode 100644
index 0000000..da50dbd
--- /dev/null
+++ b/src/app/connect/domain/import-flow.spec.ts
@@ -0,0 +1,95 @@
+import { of, throwError } from 'rxjs';
+import { FakeConnection, FakeTable, NO_GATEWAY, PACIENTE, preview } from '../testing/fakes';
+import { ImportFlow } from './import-flow';
+
+function loadedFlow(): ImportFlow {
+ const flow = new ImportFlow(new FakeTable(new FakeConnection()), PACIENTE);
+ flow.load(NO_GATEWAY).subscribe();
+ return flow;
+}
+
+describe('ImportFlow', () => {
+ it('loads the preview and seeds the mapping from the suggestions', () => {
+ const flow = loadedFlow();
+ expect(flow.totalRows()).toBe(2);
+ expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo' });
+ expect(flow.pendingSuggestions()).toBe(1);
+ });
+
+ it('is incomplete until every required field has a column or a default', () => {
+ const flow = loadedFlow();
+ expect(flow.status()).toBe('incomplete');
+ expect(flow.missingRequired().map((f) => f.name)).toEqual(['pac_id_hospital']);
+
+ flow.setDefault('pac_id_hospital', 'H-X');
+ expect(flow.status()).toBe('ready');
+ flow.setDefault('pac_id_hospital', null);
+ flow.map('Clave', 'pac_id_hospital');
+ expect(flow.status()).toBe('ready');
+ expect(flow.canSubmit).toBe(true);
+ });
+
+ it('reports a preview failure as an error status with the backend message', () => {
+ const table = new FakeTable(new FakeConnection(), 'bad', () => throwError(() => ({ error: { error: 'could not parse CSV' } })));
+ const flow = new ImportFlow(table, PACIENTE);
+ flow.load(NO_GATEWAY).subscribe();
+ expect(flow.status()).toBe('error');
+ expect(flow.error()).toBe('could not parse CSV');
+ });
+
+ it('builds the backend payload: locator + target + mapping + only non-empty defaults', async () => {
+ const flow = loadedFlow();
+ flow.map('Clave', 'pac_id_hospital');
+ flow.setDefault('pac_parentesco', 'Afiliado');
+ flow.setDefault('pac_sexo', ' ');
+ expect(await flow.toPayload()).toEqual({
+ source_type: 'csv',
+ payload: { file_base64: 'QQ==' },
+ target: 'cacu.Paciente',
+ label: 'fake.csv',
+ column_mapping: { Sexo: 'pac_sexo', Clave: 'pac_id_hospital' },
+ defaults: { pac_parentesco: 'Afiliado' },
+ });
+ });
+
+ it('validates, indexes errors by cell and per-field quality, and any edit invalidates the result', async () => {
+ const flow = loadedFlow();
+ flow.map('Clave', 'pac_id_hospital');
+ await flow.validate({
+ validate: () =>
+ of({
+ total_rows: 2,
+ valid_count: 1,
+ error_count: 1,
+ errors: [{ row_index: 1, field: 'pac_sexo', category: 'out_of_catalog' as const, message: 'no', raw_value: 'X' }],
+ }),
+ });
+ expect(flow.status()).toBe('invalid');
+ expect(flow.errorsByCell().get('1:pac_sexo')?.[0].raw_value).toBe('X');
+ expect(flow.quality().get('pac_sexo')).toEqual({ field: 'pac_sexo', total: 2, errors: 1, errorRate: 0.5 });
+
+ flow.unmapField('pac_sexo');
+ expect(flow.validation()).toBeNull();
+ expect(flow.status()).toBe('ready');
+ });
+
+ it('records a commit result as loaded, with its errors as the freshest validation', () => {
+ const flow = loadedFlow();
+ flow.map('Clave', 'pac_id_hospital');
+ flow.recordResult({ target: 'cacu.Paciente', label: null, total: 2, created: 1, updated: 0, rejected: 1, errors: [] });
+ expect(flow.status()).toBe('loaded');
+ expect(flow.validation()?.valid_count).toBe(1);
+ });
+
+ it('autoMap only fills what is still free', () => {
+ const table = new FakeTable(new FakeConnection(), 't', () =>
+ of(preview({ suggested_mapping: [{ source_column: 'Clave', target_field: 'pac_id_hospital', confidence: 0.8, reason: 'synonym' }] })),
+ );
+ const flow = new ImportFlow(table, PACIENTE);
+ flow.load(NO_GATEWAY).subscribe();
+ flow.clearMapping();
+ flow.map('Sexo', 'pac_sexo');
+ expect(flow.autoMap()).toBe(1);
+ expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
+ });
+});
diff --git a/src/app/connect/domain/import-flow.ts b/src/app/connect/domain/import-flow.ts
new file mode 100644
index 0000000..0ad8608
--- /dev/null
+++ b/src/app/connect/domain/import-flow.ts
@@ -0,0 +1,264 @@
+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());
+ }
+
+ /**
+ * 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 {
+ 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 {
+ return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== ''));
+ }
+
+ // -- backend round trips ---------------------------------------------------
+
+ 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);
+ }
+}
diff --git a/src/app/connect/domain/mapping-set.spec.ts b/src/app/connect/domain/mapping-set.spec.ts
new file mode 100644
index 0000000..189cf09
--- /dev/null
+++ b/src/app/connect/domain/mapping-set.spec.ts
@@ -0,0 +1,44 @@
+import { MappingSet } from './mapping-set';
+
+describe('MappingSet', () => {
+ it('seeds from suggestions, skipping unmatched columns and keeping confidence', () => {
+ const set = new MappingSet();
+ set.seed([
+ { source_column: 'a', target_field: 'x', confidence: 0.8, reason: 'synonym' },
+ { source_column: 'b', target_field: null, confidence: 0, reason: 'none' },
+ ]);
+ expect(set.items()).toEqual([{ source: 'a', field: 'x', confidence: 0.8, reason: 'synonym' }]);
+ });
+
+ it('keeps the mapping 1:1 in both directions', () => {
+ const set = new MappingSet();
+ set.assign('a', 'x');
+ set.assign('b', 'x'); // field x now fed by b
+ set.assign('b', 'y'); // column b moves to y
+ expect(set.toRecord()).toEqual({ b: 'y' });
+ });
+
+ it('fillFrom never overrides a manual choice', () => {
+ const set = new MappingSet();
+ set.assign('manual', 'x');
+ const added = set.fillFrom([
+ { source_column: 'auto', target_field: 'x', confidence: 0.9, reason: 'normalized' },
+ { source_column: 'other', target_field: 'y', confidence: 0.7, reason: 'fuzzy' },
+ ]);
+ expect(added).toBe(1);
+ expect(set.toRecord()).toEqual({ manual: 'x', other: 'y' });
+ });
+
+ it('confirm drops the suggestion marker; release removes by field or by source', () => {
+ const set = new MappingSet();
+ set.seed([
+ { source_column: 'a', target_field: 'x', confidence: 0.8, reason: 'synonym' },
+ { source_column: 'b', target_field: 'y', confidence: 0.8, reason: 'synonym' },
+ ]);
+ set.confirm('x');
+ expect(set.byField().get('x')).toEqual({ source: 'a', field: 'x' });
+ set.releaseField('x');
+ set.releaseSource('b');
+ expect(set.size()).toBe(0);
+ });
+});
diff --git a/src/app/connect/domain/mapping-set.ts b/src/app/connect/domain/mapping-set.ts
new file mode 100644
index 0000000..9125755
--- /dev/null
+++ b/src/app/connect/domain/mapping-set.ts
@@ -0,0 +1,79 @@
+import { Signal, computed, signal } from '@angular/core';
+import { MatchReason, SuggestedMapping } from '../api/api.types';
+
+/** One source column feeding one destination field. */
+export interface ColumnMapping {
+ source: string;
+ field: string;
+ /** Set while the mapping is an unconfirmed auto-suggestion; cleared by any manual action. */
+ confidence?: number;
+ reason?: MatchReason;
+}
+
+/**
+ * The column mapping of one import flow, 1:1 in both directions, matching
+ * the backend's source-to-field `column_mapping` dict. Every view (field
+ * slots, the unused-columns tray, data grid headers) derives from `items`.
+ */
+export class MappingSet {
+ private readonly _items = signal([]);
+ readonly items: Signal = this._items.asReadonly();
+
+ readonly byField = computed(() => new Map(this._items().map((m) => [m.field, m])));
+ readonly bySource = computed(() => new Map(this._items().map((m) => [m.source, m])));
+ readonly size = computed(() => this._items().length);
+
+ /** Replaces everything with the server's suggestions (confidence kept, so the UI can flag them). */
+ seed(suggestions: SuggestedMapping[]): void {
+ this._items.set(
+ suggestions
+ .filter((s): s is SuggestedMapping & { target_field: string } => !!s.target_field)
+ .map((s) => ({ source: s.source_column, field: s.target_field, confidence: s.confidence, reason: s.reason })),
+ );
+ }
+
+ /** Adds suggestions only for fields and columns that are still free, keeping manual choices. */
+ fillFrom(suggestions: SuggestedMapping[]): number {
+ let added = 0;
+ this._items.update((items) => {
+ const next = [...items];
+ const usedFields = new Set(next.map((m) => m.field));
+ const usedSources = new Set(next.map((m) => m.source));
+ for (const s of suggestions) {
+ if (!s.target_field || usedFields.has(s.target_field) || usedSources.has(s.source_column)) continue;
+ next.push({ source: s.source_column, field: s.target_field, confidence: s.confidence, reason: s.reason });
+ usedFields.add(s.target_field);
+ usedSources.add(s.source_column);
+ added++;
+ }
+ return next;
+ });
+ return added;
+ }
+
+ assign(source: string, field: string): void {
+ this._items.update((items) => [...items.filter((m) => m.source !== source && m.field !== field), { source, field }]);
+ }
+
+ /** Accepts an auto-suggestion as-is (drops its confidence marker). */
+ confirm(field: string): void {
+ this._items.update((items) => items.map((m) => (m.field === field ? { source: m.source, field: m.field } : m)));
+ }
+
+ releaseField(field: string): void {
+ this._items.update((items) => items.filter((m) => m.field !== field));
+ }
+
+ releaseSource(source: string): void {
+ this._items.update((items) => items.filter((m) => m.source !== source));
+ }
+
+ clear(): void {
+ this._items.set([]);
+ }
+
+ /** The backend's `column_mapping` shape: `{source_column: target_field}`. */
+ toRecord(): Record {
+ return Object.fromEntries(this._items().map((m) => [m.source, m.field]));
+ }
+}
diff --git a/src/app/connect/domain/pdf-source.ts b/src/app/connect/domain/pdf-source.ts
new file mode 100644
index 0000000..559f75a
--- /dev/null
+++ b/src/app/connect/domain/pdf-source.ts
@@ -0,0 +1,117 @@
+import { Signal, signal } from '@angular/core';
+import { Observable, map, tap } from 'rxjs';
+import { PdfDetectResponse, PreviewResponse, RegionSpec, SourceLocator, TableCandidate } from '../api/api.types';
+import { fileToBase64 } from '../api/file-encoding';
+import { SourceGateway } from '../api/source-gateway';
+import { DataConnection, EncodedFile, SourceTable } from './data-source';
+import { DocumentFiles, DocumentTable } from './document-source';
+
+/**
+ * A PDF, readable three ways:
+ * - tables the server detects in its text layer;
+ * - columns the user draws over the pages (OCR'd when scanned);
+ * - as a clinical document: fields extracted from labels and free text,
+ * one record per patient (`DocumentTable`), for reports that aren't tables.
+ */
+export class PdfConnection extends DataConnection implements DocumentFiles {
+ readonly icon = 'picture_as_pdf';
+ readonly typeLabel = 'Documento PDF';
+ readonly encoded: EncodedFile;
+ readonly documentTable: DocumentTable;
+ private readonly _detection = signal(null);
+ readonly detection: Signal = this._detection.asReadonly();
+
+ constructor(readonly file: File) {
+ super(file.name);
+ this.encoded = new EncodedFile(file, fileToBase64);
+ this.documentTable = new DocumentTable(this, 'Campos del documento');
+ }
+
+ get encodedFiles(): EncodedFile[] {
+ return [this.encoded];
+ }
+
+ addRegions(name: string, regions: RegionSpec[]): PdfRegionTable {
+ const table = new PdfRegionTable(this, name, regions);
+ this.addTable(table);
+ return table;
+ }
+
+ protected discover(gateway: SourceGateway): Observable {
+ return gateway.pdf.detect(this.file).pipe(
+ tap((detection) => this._detection.set(detection)),
+ map((detection) => {
+ const drawn = this.tables().filter((table) => table instanceof PdfRegionTable);
+ const detected = detection.table_candidates.map(
+ (candidate, index) => new PdfDetectedTable(this, `Tabla ${index + 1} · pág. ${candidate.page_number}`, candidate),
+ );
+ return [this.documentTable, ...detected, ...drawn];
+ }),
+ );
+ }
+}
+
+export class PdfDetectedTable extends SourceTable {
+ readonly icon = 'table_chart';
+ readonly kindLabel = 'Tabla detectada';
+
+ constructor(
+ override readonly connection: PdfConnection,
+ name: string,
+ readonly candidate: TableCandidate,
+ ) {
+ super(connection, name);
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ return gateway.pdf.tablePreview(this.connection.file, this.candidate.page_number, this.candidate.bbox, target);
+ }
+
+ async locator(): Promise {
+ return {
+ source_type: 'pdf',
+ payload: {
+ file_base64: await this.connection.encoded.base64(),
+ mode: 'table',
+ page_number: this.candidate.page_number,
+ bbox: this.candidate.bbox,
+ },
+ };
+ }
+}
+
+export class PdfRegionTable extends SourceTable {
+ readonly icon = 'crop_free';
+ readonly kindLabel = 'Regiones dibujadas';
+
+ constructor(
+ override readonly connection: PdfConnection,
+ name: string,
+ readonly regions: RegionSpec[],
+ ) {
+ super(connection, name);
+ }
+
+ override get removable(): boolean {
+ return true;
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ return gateway.pdf.extractRegions(this.connection.file, this.regions, target).pipe(
+ map((extraction) => ({
+ columns: extraction.columns,
+ sample_rows: extraction.rows.slice(0, 50),
+ total_rows: extraction.rows.length,
+ suggested_mapping: extraction.suggested_mapping,
+ source_metadata: { warnings: extraction.warnings },
+ })),
+ );
+ }
+
+ async locator(): Promise {
+ return {
+ source_type: 'pdf',
+ payload: { file_base64: await this.connection.encoded.base64(), mode: 'regions', regions: this.regions },
+ };
+ }
+}
diff --git a/src/app/connect/domain/sql-source.spec.ts b/src/app/connect/domain/sql-source.spec.ts
new file mode 100644
index 0000000..d8126bb
--- /dev/null
+++ b/src/app/connect/domain/sql-source.spec.ts
@@ -0,0 +1,16 @@
+import { SqlConnection, SqlQueryTable, SqlTable } from './sql-source';
+
+describe('SqlConnection', () => {
+ it('sends the server settings, never a hand-built URL', async () => {
+ const server = { engine: 'mssql', host: 'his.local', port: null, database: 'HIS', user: 'lector', password: 'p@ss' };
+ const connection = new SqlConnection({ server }, 'HIS · lector@his.local:1433', 'dbo');
+ expect(await new SqlTable(connection, 'pacientes').locator()).toEqual({
+ source_type: 'sql',
+ payload: { server, table: 'pacientes', schema: 'dbo' },
+ });
+ expect(await new SqlQueryTable(connection, 'q', 'SELECT 1').locator()).toEqual({
+ source_type: 'sql',
+ payload: { server, query: 'SELECT 1' },
+ });
+ });
+});
diff --git a/src/app/connect/domain/sql-source.ts b/src/app/connect/domain/sql-source.ts
new file mode 100644
index 0000000..9dbd098
--- /dev/null
+++ b/src/app/connect/domain/sql-source.ts
@@ -0,0 +1,109 @@
+import { Signal, signal } from '@angular/core';
+import { Observable, map, switchMap, tap } from 'rxjs';
+import { PreviewResponse, SourceLocator, SqlConnectionRef } from '../api/api.types';
+import { SourceGateway } from '../api/source-gateway';
+import { DataConnection, SourceTable } from './data-source';
+
+/**
+ * A live database. Its tables are discovered from the server's catalog;
+ * the user can add custom SELECT queries as extra tables (a join, a
+ * filter, a computed column).
+ *
+ * The credentials travel with every request (the API is stateless) but
+ * are never shown: `label` is a credential-free display name.
+ */
+export class SqlConnection extends DataConnection {
+ readonly icon = 'storage';
+ private readonly _dialect = signal(null);
+ readonly dialect: Signal = this._dialect.asReadonly();
+
+ constructor(
+ readonly ref: SqlConnectionRef,
+ displayName: string,
+ readonly schema?: string,
+ ) {
+ super(displayName);
+ }
+
+ get typeLabel(): string {
+ return SQL_DIALECT_LABELS[this._dialect() ?? ''] ?? 'Base de datos';
+ }
+
+ addQuery(name: string, query: string): SqlQueryTable {
+ const table = new SqlQueryTable(this, name, query);
+ this.addTable(table);
+ return table;
+ }
+
+ protected discover(gateway: SourceGateway): Observable {
+ return gateway.sql.testConnection(this.ref).pipe(
+ tap((response) => this._dialect.set(response.dialect)),
+ switchMap(() => gateway.sql.tables(this.ref, this.schema)),
+ map((tables) => {
+ const queries = this.tables().filter((table) => table instanceof SqlQueryTable);
+ return [...tables.map((name) => new SqlTable(this, name)), ...queries];
+ }),
+ );
+ }
+}
+
+const SQL_DIALECT_LABELS: Record = {
+ mysql: 'MySQL',
+ mariadb: 'MariaDB',
+ postgresql: 'PostgreSQL',
+ mssql: 'SQL Server',
+ oracle: 'Oracle',
+ sqlite: 'SQLite',
+};
+
+export class SqlTable extends SourceTable {
+ readonly icon = 'table_rows';
+ readonly kindLabel = 'Tabla';
+
+ constructor(
+ override readonly connection: SqlConnection,
+ name: string,
+ ) {
+ super(connection, name);
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ return gateway.sql.preview(this.connection.ref, { table: this.name, schema: this.connection.schema }, target);
+ }
+
+ async locator(): Promise {
+ return {
+ source_type: 'sql',
+ payload: {
+ ...this.connection.ref,
+ table: this.name,
+ ...(this.connection.schema ? { schema: this.connection.schema } : {}),
+ },
+ };
+ }
+}
+
+export class SqlQueryTable extends SourceTable {
+ readonly icon = 'manage_search';
+ readonly kindLabel = 'Consulta SQL';
+
+ constructor(
+ override readonly connection: SqlConnection,
+ name: string,
+ readonly query: string,
+ ) {
+ super(connection, name);
+ }
+
+ override get removable(): boolean {
+ return true;
+ }
+
+ preview(gateway: SourceGateway, target: string | null): Observable {
+ return gateway.sql.preview(this.connection.ref, { query: this.query }, target);
+ }
+
+ async locator(): Promise {
+ return { source_type: 'sql', payload: { ...this.connection.ref, query: this.query } };
+ }
+}
diff --git a/src/app/connect/domain/sql-url.spec.ts b/src/app/connect/domain/sql-url.spec.ts
new file mode 100644
index 0000000..c796bb0
--- /dev/null
+++ b/src/app/connect/domain/sql-url.spec.ts
@@ -0,0 +1,12 @@
+import { describeSqlServer, describeSqlUrl } from './sql-url';
+
+describe('sql-url', () => {
+ const mssql = { id: 'mssql', label: 'SQL Server', description: '', default_port: 1433, default_schema: 'dbo', available: true };
+
+ it('never puts the password in what the UI shows', () => {
+ const settings = { engine: mssql, host: '10.0.10.41', port: null, database: 'his', user: 'lector', password: 'p@ss:w/rd' };
+ expect(describeSqlServer(settings)).toBe('his · lector@10.0.10.41:1433');
+ expect(describeSqlUrl('mysql+pymysql://u:secret@db.local:3307/hospital_legacy')).toBe('hospital_legacy · db.local:3307');
+ expect(describeSqlUrl('not a url')).toBe('Base de datos');
+ });
+});
diff --git a/src/app/connect/domain/sql-url.ts b/src/app/connect/domain/sql-url.ts
new file mode 100644
index 0000000..059e198
--- /dev/null
+++ b/src/app/connect/domain/sql-url.ts
@@ -0,0 +1,24 @@
+import { SqlEngineInfo } from '../api/api.types';
+
+export interface SqlServerSettings {
+ engine: SqlEngineInfo;
+ host: string;
+ port: number | null;
+ database: string;
+ user: string;
+ password: string;
+}
+
+/** What the UI shows for a connection; never the password. */
+export function describeSqlServer(settings: SqlServerSettings): string {
+ const port = settings.port ?? settings.engine.default_port;
+ return `${settings.database} · ${settings.user ? `${settings.user}@` : ''}${settings.host}:${port}`;
+}
+
+/** Credential-free label for a raw connection string (`scheme://user:pass@host/db` -> `db · host`). */
+export function describeSqlUrl(url: string): string {
+ const match = /^([^:]+):\/\/(?:[^@/]*@)?([^/?#]*)\/?([^?#]*)/.exec(url.trim());
+ if (!match) return 'Base de datos';
+ const [, , host, database] = match;
+ return database ? `${decodeURIComponent(database)} · ${host}` : host || 'Base de datos';
+}
diff --git a/src/app/connect/domain/target-suggester.spec.ts b/src/app/connect/domain/target-suggester.spec.ts
new file mode 100644
index 0000000..5b9523b
--- /dev/null
+++ b/src/app/connect/domain/target-suggester.spec.ts
@@ -0,0 +1,29 @@
+import { TargetMeta } from '../api/api.types';
+import { suggestTarget, words } from './target-suggester';
+
+const targets = ['Paciente', 'OrdenesEstudio', 'NotaMedica', 'BiopsiaCervical', 'BiometriaHematica'].map(
+ (table) => ({ key: `cacu.${table}`, domain: 'cacu', table, conflict_fields: null, fields: [] }) as TargetMeta,
+);
+
+describe('suggestTarget', () => {
+ it('splits camelCase, strips accents and extensions', () => {
+ expect(words('OrdenesEstudio')).toEqual(['ordenes', 'estudio']);
+ expect(words('Notas médicas.xlsx')).toEqual(['notas', 'medicas']);
+ });
+
+ it.each([
+ ['pacientes.csv', '', 'Paciente'],
+ ['Órdenes', 'libro.xlsx', 'OrdenesEstudio'],
+ ['Notas médicas', 'libro.xlsx', 'NotaMedica'],
+ ['cacu_biometrias.json', '', 'BiometriaHematica'],
+ // Nothing in the table's own name — fall back to the connection's.
+ ['Tabla 1 · pág. 1', 'cacu_biopsias_reporte.pdf', 'BiopsiaCervical'],
+ ['Regiones 1', 'pacientes_escaneados.pdf', 'Paciente'],
+ ])('%s (%s) → %s', (table, connection, expected) => {
+ expect(suggestTarget(table, targets, connection)?.table).toBe(expected);
+ });
+
+ it('suggests nothing rather than guessing', () => {
+ expect(suggestTarget('datos', targets, 'export.csv')).toBeNull();
+ });
+});
diff --git a/src/app/connect/domain/target-suggester.ts b/src/app/connect/domain/target-suggester.ts
new file mode 100644
index 0000000..c9ca4b7
--- /dev/null
+++ b/src/app/connect/domain/target-suggester.ts
@@ -0,0 +1,49 @@
+import { TargetMeta } from '../api/api.types';
+
+/** Lower-case, accent-free words: "Notas médicas" -> ["notas", "medicas"], "OrdenesEstudio" -> ["ordenes", "estudio"]. */
+export function words(text: string): string[] {
+ return text
+ .replace(/\.[a-z0-9]{2,4}$/i, '') // file extension
+ .replace(/([a-z])([A-Z])/g, '$1 $2') // camelCase
+ .normalize('NFKD')
+ .replace(/[̀-ͯ]/g, '')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter((word) => word.length > 2);
+}
+
+/**
+ * Singular/plural-insensitive forms of a word. Spanish plurals add "-s"
+ * after a vowel (paciente → pacientes, nota → notas) and "-es" after a
+ * consonant (orden → órdenes), so both sides are compared as-is, minus "s"
+ * and minus "es" instead of guessing one singular form.
+ */
+function forms(word: string): string[] {
+ const result = [word];
+ if (word.length > 4 && word.endsWith('s')) result.push(word.slice(0, -1));
+ if (word.length > 5 && word.endsWith('es')) result.push(word.slice(0, -2));
+ return result;
+}
+
+function overlap(sourceText: string, targetText: string): number {
+ const source = new Set(words(sourceText).flatMap(forms));
+ return words(targetText).filter((word) => forms(word).some((form) => source.has(form))).length;
+}
+
+/**
+ * Best-guess destination entity for a source table from its words ("Órdenes"
+ * → OrdenesEstudio, "pacientes.csv" → Paciente), falling back to the
+ * connection's name when the table's own name says nothing ("Regiones 1"
+ * inside "pacientes_escaneados.pdf"). Only a default; the user confirms it.
+ */
+export function suggestTarget(tableName: string, targets: TargetMeta[], connectionName = ''): TargetMeta | null {
+ for (const name of [tableName, connectionName]) {
+ let best: { target: TargetMeta; score: number } | null = null;
+ for (const target of targets) {
+ const score = overlap(name, target.table);
+ if (score > (best?.score ?? 0)) best = { target, score };
+ }
+ if (best) return best.target;
+ }
+ return null;
+}
diff --git a/src/app/connect/state/connect-workspace.store.spec.ts b/src/app/connect/state/connect-workspace.store.spec.ts
new file mode 100644
index 0000000..ad8d21b
--- /dev/null
+++ b/src/app/connect/state/connect-workspace.store.spec.ts
@@ -0,0 +1,122 @@
+import { TestBed } from '@angular/core/testing';
+import { Observable, firstValueFrom, of } from 'rxjs';
+import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
+import { ImportsApi } from '../api/imports.api';
+import { SourceGateway } from '../api/source-gateway';
+import { TargetsApi } from '../api/targets.api';
+import { FakeConnection, FakeTable, NOTA, PACIENTE } from '../testing/fakes';
+import { ConnectWorkspaceStore } from './connect-workspace.store';
+
+class FakeImportsApi {
+ committed: { sources: ImportSourcePayload[]; onConflict: ConflictStrategy } | null = null;
+ validate = () => of({ total_rows: 2, valid_count: 2, error_count: 0, errors: [] });
+ commit(sources: ImportSourcePayload[], onConflict: ConflictStrategy): Observable {
+ this.committed = { sources, onConflict };
+ return of({
+ ok: true,
+ results: sources.map((s) => ({ target: s.target, label: s.label ?? null, total: 2, created: 2, updated: 0, rejected: 0, errors: [] })),
+ });
+ }
+}
+
+describe('ConnectWorkspaceStore', () => {
+ let store: ConnectWorkspaceStore;
+ let imports: FakeImportsApi;
+ const tama: TargetMeta = { ...PACIENTE, key: 'tea.Pacientes', domain: 'tea', table: 'Pacientes', conflict_fields: null };
+
+ beforeEach(() => {
+ imports = new FakeImportsApi();
+ TestBed.configureTestingModule({
+ providers: [
+ ConnectWorkspaceStore,
+ { provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
+ { provide: ImportsApi, useValue: imports },
+ { provide: SourceGateway, useValue: {} },
+ ],
+ });
+ store = TestBed.inject(ConnectWorkspaceStore);
+ });
+
+ function flowFrom(label: string, target: TargetMeta) {
+ const connection = new FakeConnection(label);
+ store.addConnection(connection);
+ const flow = store.createFlow(new FakeTable(connection), target);
+ flow.map('Clave', 'pac_id_hospital');
+ return { connection, flow };
+ }
+
+ it('filters targets by the domain, and locks the domain once a flow exists', () => {
+ expect(store.targets().map((t) => t.key)).toEqual(['cacu.Paciente', 'cacu.NotaMedica']);
+ flowFrom('a.csv', PACIENTE);
+ store.setDomain('tea');
+ expect(store.domain()).toBe('cacu');
+ });
+
+ it('removing a connection removes the flows built on its tables', () => {
+ const { connection } = flowFrom('a.csv', PACIENTE);
+ flowFrom('b.csv', PACIENTE);
+ store.removeConnection(connection);
+ expect(store.flows().map((f) => f.label)).toEqual(['b.csv']);
+ expect(store.selectedFlow()?.label).toBe('b.csv');
+ });
+
+ it('counts how many flows feed each destination table', () => {
+ flowFrom('a.csv', PACIENTE);
+ flowFrom('b.csv', PACIENTE);
+ expect(store.flowsByTarget().get('cacu.Paciente')).toBe(2);
+ });
+
+ it('commits every submittable flow in ONE request and hands each flow its result', async () => {
+ const { flow: first } = flowFrom('a.csv', PACIENTE);
+ const { flow: second } = flowFrom('b.csv', PACIENTE);
+ const incomplete = store.createFlow(new FakeTable(new FakeConnection('c.csv')), PACIENTE);
+
+ await firstValueFrom(store.commit());
+
+ expect(imports.committed?.sources.map((s) => s.label)).toEqual(['a.csv', 'b.csv']);
+ expect(incomplete.status()).toBe('incomplete');
+ expect(first.status()).toBe('loaded');
+ expect(second.result()?.created).toBe(2);
+
+ // Loaded flows are not re-sent (keyless tables would get duplicates)…
+ expect(store.submittableFlows()).toEqual([]);
+ // …until they're edited.
+ first.setDefault('pac_parentesco', 'Afiliado');
+ expect(store.submittableFlows()).toEqual([first]);
+ });
+
+ it('only sends upsert when every target has a natural key', async () => {
+ flowFrom('a.csv', PACIENTE);
+ store.setOnConflict('upsert');
+ await firstValueFrom(store.commit());
+ expect(imports.committed?.onConflict).toBe('upsert');
+
+ const { flow: again } = flowFrom('a2.csv', PACIENTE);
+ expect(store.submittableFlows()).toEqual([again]);
+ const nota = store.createFlow(new FakeTable(new FakeConnection('n.csv')), NOTA);
+ nota.map('Clave', 'pac_id_hospital');
+ nota.map('Sexo', 'nm_id_hospital');
+ expect(store.upsertAvailable()).toBe(false);
+ await firstValueFrom(store.commit());
+ expect(imports.committed?.onConflict).toBe('reject');
+ });
+
+ it('with mergeDuplicates on, a flow missing a required field joins the batch when a sibling shares its key', async () => {
+ const { flow: complete } = flowFrom('padron.csv', PACIENTE);
+ const incomplete = store.createFlow(new FakeTable(new FakeConnection('ficha.pdf')), PACIENTE);
+
+ // Off by default: the incomplete one stays out, same as before this feature.
+ expect(store.submittableFlows()).toEqual([complete]);
+
+ store.setMergeDuplicates(true);
+ expect(store.submittableFlows()).toEqual([complete, incomplete]);
+
+ await firstValueFrom(store.commit());
+ expect(imports.committed?.sources.map((s) => s.label)).toEqual(['padron.csv', 'ficha.pdf']);
+
+ // Both flows are now 'loaded'; a fresh incomplete flow with no live sibling on
+ // the same keyed target still never submits, even with merging on.
+ store.createFlow(new FakeTable(new FakeConnection('solo.pdf')), PACIENTE);
+ expect(store.submittableFlows()).toEqual([]);
+ });
+});
diff --git a/src/app/connect/state/connect-workspace.store.ts b/src/app/connect/state/connect-workspace.store.ts
new file mode 100644
index 0000000..f683deb
--- /dev/null
+++ b/src/app/connect/state/connect-workspace.store.ts
@@ -0,0 +1,235 @@
+import { Injectable, computed, inject, signal } from '@angular/core';
+import { toSignal } from '@angular/core/rxjs-interop';
+import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
+import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
+import { ConnectorsApi } from '../api/connectors.api';
+import { ImportsApi } from '../api/imports.api';
+import { SourceGateway } from '../api/source-gateway';
+import { TargetsApi } from '../api/targets.api';
+import { acceptedExtensions, connectionsForFiles } from '../domain/connection-registry';
+import { DataConnection, SourceTable } from '../domain/data-source';
+import { ImportFlow } from '../domain/import-flow';
+
+export const DOMAINS: { id: Domain; label: string; description: string }[] = [
+ { id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
+ { id: 'cama', label: 'CaMa', description: 'Cáncer de mama' },
+ { id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
+];
+
+/**
+ * State of one "Conectar datos" workspace: connections, the import flows
+ * composed from their tables, the selected flow, the destination domain
+ * and the batch options.
+ *
+ * Network work is delegated to the domain objects (`connection.load`,
+ * `flow.load`, `flow.validate`) and, for the batch, to `ImportsApi.commit`.
+ * Provided per page, so leaving it discards the session.
+ */
+@Injectable()
+export class ConnectWorkspaceStore {
+ private readonly gateway = inject(SourceGateway);
+ private readonly importsApi = inject(ImportsApi);
+
+ private readonly targetsError = signal(null);
+ readonly allTargets = toSignal(
+ inject(TargetsApi)
+ .list()
+ .pipe(
+ catchError((error) => {
+ this.targetsError.set(apiErrorMessage(error, 'No se pudo cargar el esquema de la base de datos.'));
+ return of([] as TargetMeta[]);
+ }),
+ ),
+ { initialValue: [] as TargetMeta[] },
+ );
+ readonly catalogError = this.targetsError.asReadonly();
+
+ /** What the server can read; drives the gallery and which dropped files are accepted. */
+ readonly connectors = toSignal(inject(ConnectorsApi).list().pipe(catchError(() => of([] as ConnectorInfo[]))), {
+ initialValue: [] as ConnectorInfo[],
+ });
+ readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
+
+ private readonly _domain = signal('cacu');
+ private readonly _connections = signal([]);
+ private readonly _flows = signal([]);
+ private readonly _selectedFlowId = signal(null);
+ private readonly _onConflict = signal('reject');
+ private readonly _mergeDuplicates = signal(false);
+ private readonly _committing = signal(false);
+ private readonly _lastBatch = signal