diff --git a/apps/api/src/integrations/montify/sync.service.ts b/apps/api/src/integrations/montify/sync.service.ts index 1a2f6e6..dc6fe1f 100644 --- a/apps/api/src/integrations/montify/sync.service.ts +++ b/apps/api/src/integrations/montify/sync.service.ts @@ -156,10 +156,11 @@ export class MontifySyncService { ): Promise { const row = await this.connections.getOrThrow(organizationId, connectionId); if (!row.enabled) throw new BadRequestException('این اتصال غیرفعال است'); - if (this.running.has(connectionId)) { - throw new BadRequestException('همگام‌سازی این فروشگاه در حال اجراست'); + if (!this.running.has(connectionId)) { + await new Promise((started) => { + void this.runSync(row, mode, started); + }); } - void this.runSync(row, mode); return this.connections.getDto(organizationId, connectionId); } @@ -175,8 +176,15 @@ export class MontifySyncService { } } - private async runSync(row: MontifyConnection, mode: 'incremental' | 'full'): Promise { - if (this.running.has(row.id)) return; + private async runSync( + row: MontifyConnection, + mode: 'incremental' | 'full', + onStarted?: () => void, + ): Promise { + if (this.running.has(row.id)) { + onStarted?.(); + return; + } this.running.add(row.id); const startedAt = new Date(); const result: MontifySyncResultDto = { @@ -196,14 +204,22 @@ export class MontifySyncService { data: { lastSyncResult: result as unknown as Prisma.InputJsonValue }, }); - await this.prisma.montifyConnection.update({ - where: { id: row.id }, - data: { - syncStatus: 'running', - syncStartedAt: startedAt, - lastSyncResult: result as unknown as Prisma.InputJsonValue, - }, - }); + try { + await this.prisma.montifyConnection.update({ + where: { id: row.id }, + data: { + syncStatus: 'running', + syncStartedAt: startedAt, + lastSyncResult: result as unknown as Prisma.InputJsonValue, + }, + }); + } catch (e) { + this.running.delete(row.id); + this.logger.warn(`Montify sync ${row.id} start: ${e instanceof Error ? e.message : e}`); + return; + } finally { + onStarted?.(); + } let cursor = row.customersCursor; let fatal: string | null = null;