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' }); }); it('counts a derived field as covered, and mapping a column onto it drops the rule', async () => { // Fails if `missingRequired` ignores `derived`, or a field could be fed by a column and a rule at once. const flow = loadedFlow(); flow.setDerived('pac_id_hospital', { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' }); expect(flow.missingRequired()).toEqual([]); expect((await flow.toPayload()).derived).toEqual({ pac_id_hospital: { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' } }); flow.map('Clave', 'pac_id_hospital'); expect(flow.derived()).toEqual({}); expect((await flow.toPayload()).derived).toBeUndefined(); }); it('sends document columns without blank settings and swaps in their columns until they are dropped', async () => { // Fails if blank document settings reach the payload, or the source's own columns are lost when documents are dropped. const flow = loadedFlow(); const own = flow.sourceColumns(); flow.setDocuments({ columns: ['Clave'], group_by: '', include_pattern: undefined, ocr_mode: 'auto' }); expect((await flow.toPayload()).documents).toEqual({ columns: ['Clave'], ocr_mode: 'auto' }); expect(flow.missingRequired()).toEqual([]); flow.useDocumentPreview(preview({ columns: [...own, { name: 'Tipo de persona', inferred_type: 'string' }] })); expect(flow.sourceColumns().map((c) => c.name)).toContain('Tipo de persona'); flow.setDocuments(null); expect(flow.sourceColumns()).toEqual(own); expect((await flow.toPayload()).documents).toBeUndefined(); }); it('asks for the catalog fallback only when chosen', async () => { // Fails if `catalog_fallback` is sent without the user switching it on, or not sent once they do. const flow = loadedFlow(); expect((await flow.toPayload()).catalog_fallback).toBeUndefined(); flow.setCatalogFallback(true); expect((await flow.toPayload()).catalog_fallback).toBe(true); }); });