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 { AuthService } from '../../auth/auth.service'; import { dominiosPermitidos } from '../../auth/dominios'; 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: 'Cáncer cervicouterino', description: 'Cáncer cervicouterino' }, { id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' }, { id: 'tea', label: 'Trastorno del espectro autista', 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 auth = inject(AuthService); 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())); /** The destination database: the account's own when it only reaches one. */ private readonly _domain = signal(this.dominioInicial()); 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(null); private readonly _commitError = signal(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); /** Unwritten flows into a keyed target: what `mergeDuplicates` may combine, complete or not. */ 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(); 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 writes: the complete ones, plus incomplete ones another flow may complete when merging. */ 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(); 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.auth.puedeVer(domain)) this._domain.set(domain); } /** The first domain the account may see; every account has at least one (`WebApi` gives none other). */ private dominioInicial(): Domain { return dominiosPermitidos(this.auth, DOMAINS)[0]?.id ?? 'cacu'; } 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 { return flow.validate(this.importsApi); } validateAll(): Promise { 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 { 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); }), ); } }