integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -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<BatchResult> {
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@@ -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<string | null>(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<Domain>('cacu');
|
||||
private readonly _connections = signal<DataConnection[]>([]);
|
||||
private readonly _flows = signal<ImportFlow[]>([]);
|
||||
private readonly _selectedFlowId = signal<string | null>(null);
|
||||
private readonly _onConflict = signal<ConflictStrategy>('reject');
|
||||
private readonly _mergeDuplicates = signal(false);
|
||||
private readonly _committing = signal(false);
|
||||
private readonly _lastBatch = signal<BatchResult | null>(null);
|
||||
private readonly _commitError = signal<string | null>(null);
|
||||
|
||||
readonly domain = this._domain.asReadonly();
|
||||
readonly connections = this._connections.asReadonly();
|
||||
readonly flows = this._flows.asReadonly();
|
||||
readonly onConflict = this._onConflict.asReadonly();
|
||||
readonly mergeDuplicates = this._mergeDuplicates.asReadonly();
|
||||
readonly committing = this._committing.asReadonly();
|
||||
readonly lastBatch = this._lastBatch.asReadonly();
|
||||
readonly commitError = this._commitError.asReadonly();
|
||||
|
||||
readonly targets = computed(() => this.allTargets().filter((target) => target.domain === this._domain()));
|
||||
readonly selectedFlow = computed(() => this._flows().find((flow) => flow.id === this._selectedFlowId()) ?? null);
|
||||
|
||||
/** A batch writes to one domain's database, so the domain can only change while there are no flows. */
|
||||
readonly domainLocked = computed(() => this._flows().length > 0);
|
||||
|
||||
/**
|
||||
* Flows with a known target and a natural key, not still loading/erroring
|
||||
* and not already written — candidates to combine by `mergeDuplicates`,
|
||||
* complete or not (a source missing a required field may still supply
|
||||
* others a sibling source lacks).
|
||||
*/
|
||||
private readonly mergeCandidateFlows = computed(() =>
|
||||
this._flows().filter((flow) => !!flow.target.conflict_fields && !['loading', 'error', 'loaded'].includes(flow.status())),
|
||||
);
|
||||
|
||||
/** Merging only makes sense when several flows feed the same keyed entity. */
|
||||
readonly mergeAvailable = computed(() => {
|
||||
const keyed = this.mergeCandidateFlows();
|
||||
return new Set(keyed.map((flow) => flow.target.key)).size < keyed.length;
|
||||
});
|
||||
|
||||
private readonly mergeableTargetKeys = computed(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const flow of this.mergeCandidateFlows()) counts.set(flow.target.key, (counts.get(flow.target.key) ?? 0) + 1);
|
||||
return new Set([...counts].filter(([, count]) => count > 1).map(([key]) => key));
|
||||
});
|
||||
|
||||
/**
|
||||
* Flows the next batch will write. Normally just the complete ones; with
|
||||
* `mergeDuplicates` on, a flow missing a required field joins them too
|
||||
* when another flow targets the same keyed entity — the gap may be
|
||||
* exactly what that other source supplies, so the batch combines them
|
||||
* before validating instead of dropping the incomplete one silently.
|
||||
*/
|
||||
readonly submittableFlows = computed(() => {
|
||||
const complete = this._flows().filter((flow) => flow.pendingLoad);
|
||||
if (!this._mergeDuplicates()) return complete;
|
||||
const mergeableKeys = this.mergeableTargetKeys();
|
||||
const extra = this.mergeCandidateFlows().filter((flow) => !complete.includes(flow) && mergeableKeys.has(flow.target.key));
|
||||
return [...complete, ...extra];
|
||||
});
|
||||
|
||||
readonly upsertAvailable = computed(() => {
|
||||
const flows = this.submittableFlows();
|
||||
return flows.length > 0 && flows.every((flow) => !!flow.target.conflict_fields);
|
||||
});
|
||||
|
||||
readonly summary = computed(() => {
|
||||
const flows = this._flows();
|
||||
const rows = flows.reduce((total, flow) => total + (flow.totalRows() ?? 0), 0);
|
||||
const errors = flows.reduce((total, flow) => total + (flow.validation()?.error_count ?? 0), 0);
|
||||
return {
|
||||
connections: this._connections().length,
|
||||
flows: flows.length,
|
||||
ready: this.submittableFlows().length,
|
||||
incomplete: flows.filter((flow) => flow.status() === 'incomplete').length,
|
||||
rows,
|
||||
errors,
|
||||
};
|
||||
});
|
||||
|
||||
/** How many flows feed each destination entity. */
|
||||
readonly flowsByTarget = computed(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const flow of this._flows()) counts.set(flow.target.key, (counts.get(flow.target.key) ?? 0) + 1);
|
||||
return counts;
|
||||
});
|
||||
|
||||
setDomain(domain: Domain): void {
|
||||
if (!this.domainLocked()) this._domain.set(domain);
|
||||
}
|
||||
|
||||
setOnConflict(strategy: ConflictStrategy): void {
|
||||
this._onConflict.set(strategy);
|
||||
}
|
||||
|
||||
setMergeDuplicates(merge: boolean): void {
|
||||
this._mergeDuplicates.set(merge);
|
||||
}
|
||||
|
||||
/** Adds dropped files as connections; returns the ones no connector reads. */
|
||||
addFiles(files: File[]): File[] {
|
||||
const { connections, rejected } = connectionsForFiles(files, this.connectors());
|
||||
connections.forEach((connection) => this.addConnection(connection));
|
||||
return rejected;
|
||||
}
|
||||
|
||||
addConnection(connection: DataConnection): void {
|
||||
this._connections.update((connections) => [...connections, connection]);
|
||||
connection.load(this.gateway).subscribe();
|
||||
}
|
||||
|
||||
reloadConnection(connection: DataConnection): void {
|
||||
connection.load(this.gateway).subscribe();
|
||||
}
|
||||
|
||||
removeConnection(connection: DataConnection): void {
|
||||
this._flows().filter((flow) => flow.table.connection === connection).forEach((flow) => this.removeFlow(flow));
|
||||
this._connections.update((connections) => connections.filter((existing) => existing !== connection));
|
||||
}
|
||||
|
||||
removeTable(table: SourceTable): void {
|
||||
this._flows().filter((flow) => flow.table === table).forEach((flow) => this.removeFlow(flow));
|
||||
table.connection.removeTable(table);
|
||||
}
|
||||
|
||||
createFlow(table: SourceTable, target: TargetMeta): ImportFlow {
|
||||
const flow = new ImportFlow(table, target);
|
||||
this._flows.update((flows) => [...flows, flow]);
|
||||
this._selectedFlowId.set(flow.id);
|
||||
this._lastBatch.set(null);
|
||||
flow.load(this.gateway).subscribe();
|
||||
return flow;
|
||||
}
|
||||
|
||||
reloadFlow(flow: ImportFlow): void {
|
||||
flow.load(this.gateway).subscribe();
|
||||
}
|
||||
|
||||
removeFlow(flow: ImportFlow): void {
|
||||
const remaining = this._flows().filter((existing) => existing !== flow);
|
||||
this._flows.set(remaining);
|
||||
if (this._selectedFlowId() === flow.id) this._selectedFlowId.set(remaining.at(-1)?.id ?? null);
|
||||
}
|
||||
|
||||
select(flow: ImportFlow | null): void {
|
||||
this._selectedFlowId.set(flow?.id ?? null);
|
||||
}
|
||||
|
||||
flowsOf(table: SourceTable): ImportFlow[] {
|
||||
return this._flows().filter((flow) => flow.table === table);
|
||||
}
|
||||
|
||||
validate(flow: ImportFlow): Promise<void> {
|
||||
return flow.validate(this.importsApi);
|
||||
}
|
||||
|
||||
validateAll(): Promise<void> {
|
||||
return Promise.all(this.submittableFlows().map((flow) => flow.validate(this.importsApi))).then(() => undefined);
|
||||
}
|
||||
|
||||
/** Loads every submittable flow in one request, written in one transaction. */
|
||||
commit(): Observable<BatchResult | null> {
|
||||
const flows = this.submittableFlows();
|
||||
if (flows.length === 0) return of(null);
|
||||
const strategy = this.upsertAvailable() ? this._onConflict() : 'reject';
|
||||
this._committing.set(true);
|
||||
this._commitError.set(null);
|
||||
return from(Promise.all(flows.map((flow) => flow.toPayload()))).pipe(
|
||||
switchMap((payloads) => this.importsApi.commit(payloads, strategy, this._mergeDuplicates())),
|
||||
tap((batch) => {
|
||||
batch.results.forEach((result, index) => flows[index].recordResult(result));
|
||||
this._lastBatch.set(batch);
|
||||
this._committing.set(false);
|
||||
}),
|
||||
catchError((error) => {
|
||||
this._commitError.set(apiErrorMessage(error, 'No se pudo cargar la información.'));
|
||||
this._committing.set(false);
|
||||
return of(null);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user