integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -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