integration layer; merge work on indicators from forks with existing ingestion pipeline

This commit is contained in:
Roberto Treviño Cervantes
2026-10-23 00:00:14 -06:00
parent b0608fdc70
commit d9245fe9b7
194 changed files with 21773 additions and 848 deletions
@@ -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);
});
});
@@ -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<SourceType, ConnectionFactory>([
['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<SourceType, File[]>();
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 };
}
@@ -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');
});
});
@@ -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 };
}
+121
View File
@@ -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<SourceTable[]>([]);
private readonly _state = signal<ConnectionState>('loading');
private readonly _error = signal<string | null>(null);
readonly tables: Signal<SourceTable[]> = this._tables.asReadonly();
readonly state: Signal<ConnectionState> = this._state.asReadonly();
readonly error: Signal<string | null> = 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<void> {
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<SourceTable[]>;
}
/**
* 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<PreviewResponse>;
/** `target`: the entity the rows go to, for sources whose reading depends on it. */
abstract locator(target?: string): Promise<SourceLocator>;
}
/** Lazily computed base64 of a file, shared by every table of a connection. */
export class EncodedFile {
private encoded: Promise<string> | null = null;
constructor(
readonly file: File,
private readonly encode: (file: File) => Promise<string>,
) {}
base64(): Promise<string> {
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() })));
}
@@ -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']);
});
});
+110
View File
@@ -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<string, Record<string, unknown>>;
/**
* 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<SourceTable[]> {
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<DocumentSettings>(DEFAULT_DOCUMENT_SETTINGS);
private readonly _overrides = signal<Record<string, FieldOverrides>>({});
private readonly _extractions = signal<Record<string, DocumentExtraction>>({});
readonly settings: Signal<DocumentSettings> = 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<string, FieldOverrides>): 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<PreviewResponse> {
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<SourceLocator> {
return { source_type: 'document', payload: await this.payload(target) };
}
private async payload(target?: string): Promise<Record<string, unknown>> {
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 } : {}),
};
}
}
+52
View File
@@ -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<Record<string, unknown>> {
return { files: await encodeFiles(this.encoded) };
}
protected discover(gateway: SourceGateway): Observable<SourceTable[]> {
// 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<PreviewResponse> {
return from(this.connection.payload()).pipe(switchMap((payload) => gateway.file.previewPayload('edf', payload, target)));
}
async locator(): Promise<SourceLocator> {
return { source_type: 'edf', payload: await this.connection.payload() };
}
}
@@ -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([]);
});
});
+69
View File
@@ -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<FileKind, { icon: string; typeLabel: string }> = {
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<SourceTable[]> {
// 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<PreviewResponse> {
return gateway.file.preview(this.connection.file, this.connection.fileKind, target, this.options);
}
async locator(): Promise<SourceLocator> {
return {
source_type: this.connection.fileKind,
payload: { file_base64: await this.connection.encoded.base64(), options: this.options },
};
}
}
@@ -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' });
});
});
+264
View File
@@ -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<ValidationResult>;
}
let sequence = 0;
/**
* One source table flowing into one destination entity: the unit the user
* composes the database from. A workspace can feed several tables into one
* entity or one file into several entities.
*
* Owns its mapping (`MappingSet`), per-field default values, the latest
* preview and validation, and derives its own status. Any change to what
* would be sent clears the previous validation, so a stale result is not
* shown.
*/
export class ImportFlow {
readonly id = `flow-${++sequence}`;
readonly mapping = new MappingSet();
private readonly _preview = signal<PreviewResponse | null>(null);
private readonly _loading = signal(false);
private readonly _error = signal<string | null>(null);
private readonly _defaults = signal<Record<string, string>>({});
private readonly _validation = signal<ValidationResult | null>(null);
private readonly _validating = signal(false);
private readonly _result = signal<CommitSourceResult | null>(null);
readonly preview: Signal<PreviewResponse | null> = this._preview.asReadonly();
readonly loading: Signal<boolean> = this._loading.asReadonly();
readonly error: Signal<string | null> = this._error.asReadonly();
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
readonly validating: Signal<boolean> = this._validating.asReadonly();
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
readonly sourceColumns = computed<SourceColumn[]>(() => this._preview()?.columns ?? []);
readonly totalRows = computed(() => this._preview()?.total_rows ?? null);
/** A field is covered when a column feeds it or it has a default value. */
readonly missingRequired = computed<TargetField[]>(() => {
const mapped = this.mapping.byField();
const defaults = this._defaults();
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
});
readonly unmappedColumns = computed(() => {
const used = this.mapping.bySource();
return this.sourceColumns().filter((column) => !used.has(column.name));
});
readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length);
readonly status = computed<FlowStatus>(() => {
if (this._loading()) return 'loading';
if (this._error() || !this._preview()) return 'error';
if (this._result()) return 'loaded';
if (this._validating()) return 'validating';
if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) {
return 'incomplete';
}
const validation = this._validation();
if (!validation) return 'ready';
return validation.error_count > 0 ? 'invalid' : 'valid';
});
/** Row errors indexed by `"<row>:<field>"` for the data grid's cell highlighting. */
readonly errorsByCell = computed(() => {
const index = new Map<string, RowError[]>();
for (const error of this._validation()?.errors ?? []) {
const key = `${error.row_index}:${error.field}`;
index.set(key, [...(index.get(key) ?? []), error]);
}
return index;
});
/** Per destination field: how many rows failed on it (Power Query-style column quality). */
readonly quality = computed(() => {
const validation = this._validation();
const qualities = new Map<string, FieldQuality>();
if (!validation) return qualities;
const failingRows = new Map<string, Set<number>>();
for (const error of validation.errors) {
if (!failingRows.has(error.field)) failingRows.set(error.field, new Set());
failingRows.get(error.field)!.add(error.row_index);
}
for (const field of this.target.fields) {
const errors = failingRows.get(field.name)?.size ?? 0;
const total = validation.total_rows;
qualities.set(field.name, { field: field.name, total, errors, errorRate: total ? errors / total : 0 });
}
return qualities;
});
constructor(
readonly table: SourceTable,
readonly target: TargetMeta,
) {}
get label(): string {
return this.table.label;
}
/** Complete enough to validate. */
get canSubmit(): boolean {
return !['loading', 'error', 'incomplete'].includes(this.status());
}
/**
* Belongs in the next load: complete and not already written. A loaded
* flow stays out of later batches (re-sending it would duplicate rows in
* tables without a natural key) until it's edited, since any edit clears
* its result.
*/
get pendingLoad(): boolean {
return this.canSubmit && this.status() !== 'loaded';
}
/** Fetches the preview against this flow's target and seeds the mapping from the server's suggestions. */
load(gateway: SourceGateway): Observable<void> {
this._loading.set(true);
this._error.set(null);
return this.table.preview(gateway, this.target.key).pipe(
tap((preview) => {
this._preview.set(preview);
this.mapping.seed(preview.suggested_mapping);
}),
map(() => undefined),
catchError((error) => {
this._error.set(apiErrorMessage(error, 'No se pudo leer la fuente.'));
return of(undefined);
}),
finalize(() => this._loading.set(false)),
);
}
// -- mapping edits (every one invalidates the last validation) -----------
map(source: string, field: string): void {
this.mapping.assign(source, field);
this.touch();
}
unmapField(field: string): void {
this.mapping.releaseField(field);
this.touch();
}
unmapSource(source: string): void {
this.mapping.releaseSource(source);
this.touch();
}
confirmSuggestion(field: string): void {
this.mapping.confirm(field);
}
/** Re-applies the server's suggestions to whatever is still unmapped. Returns how many were added. */
autoMap(): number {
const added = this.mapping.fillFrom(this._preview()?.suggested_mapping ?? []);
if (added) this.touch();
return added;
}
clearMapping(): void {
this.mapping.clear();
this._defaults.set({});
this.touch();
}
setDefault(field: string, value: string | null): void {
this._defaults.update((defaults) => {
const next = { ...defaults };
if (value === null || value === '') delete next[field];
else next[field] = value;
return next;
});
this.touch();
}
activeDefaults(): Record<string, string> {
return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== ''));
}
// -- backend round trips ---------------------------------------------------
async toPayload(): Promise<ImportSourcePayload> {
const locator = await this.table.locator(this.target.key);
const defaults = this.activeDefaults();
return {
...locator,
target: this.target.key,
label: this.label,
column_mapping: this.mapping.toRecord(),
...(Object.keys(defaults).length ? { defaults } : {}),
};
}
validate(validator: Validator): Promise<void> {
this._validating.set(true);
return this.toPayload()
.then(
(payload) =>
new Promise<void>((resolve) => {
validator.validate(payload).subscribe({
next: (result) => {
this._validation.set(result);
this._error.set(null);
resolve();
},
error: (error) => {
this._error.set(apiErrorMessage(error, 'No se pudo validar la fuente.'));
resolve();
},
});
}),
)
.finally(() => this._validating.set(false));
}
recordResult(result: CommitSourceResult): void {
this._result.set(result);
// The commit re-validated every row server-side; its errors are the freshest view.
this._validation.set({
total_rows: result.total,
valid_count: result.created + result.updated,
error_count: result.rejected,
errors: result.errors,
});
}
private touch(): void {
this._validation.set(null);
this._result.set(null);
}
}
@@ -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);
});
});
+79
View File
@@ -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<ColumnMapping[]>([]);
readonly items: Signal<ColumnMapping[]> = 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<string, string> {
return Object.fromEntries(this._items().map((m) => [m.source, m.field]));
}
}
+117
View File
@@ -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<PdfDetectResponse | null>(null);
readonly detection: Signal<PdfDetectResponse | null> = 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<SourceTable[]> {
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<PreviewResponse> {
return gateway.pdf.tablePreview(this.connection.file, this.candidate.page_number, this.candidate.bbox, target);
}
async locator(): Promise<SourceLocator> {
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<PreviewResponse> {
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<SourceLocator> {
return {
source_type: 'pdf',
payload: { file_base64: await this.connection.encoded.base64(), mode: 'regions', regions: this.regions },
};
}
}
+16
View File
@@ -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' },
});
});
});
+109
View File
@@ -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<string | null>(null);
readonly dialect: Signal<string | null> = 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<SourceTable[]> {
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<string, string> = {
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<PreviewResponse> {
return gateway.sql.preview(this.connection.ref, { table: this.name, schema: this.connection.schema }, target);
}
async locator(): Promise<SourceLocator> {
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<PreviewResponse> {
return gateway.sql.preview(this.connection.ref, { query: this.query }, target);
}
async locator(): Promise<SourceLocator> {
return { source_type: 'sql', payload: { ...this.connection.ref, query: this.query } };
}
}
+12
View File
@@ -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');
});
});
+24
View File
@@ -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';
}
@@ -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();
});
});
@@ -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;
}