Spaces:
Sleeping

File size: 7,533 Bytes
7f81110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { IConnectorRepository } from "../../../domain/repositories/IConnectorRepository";
import { ISyncJobRepository } from "../../../domain/repositories/ISyncJobRepository";
import { IStagingRepository } from "../../../domain/repositories/IStagingRepository";
import { IShopifyGraphQLClient } from "../../../domain/repositories/IShopifyGraphQLClient";
import { ShopifySyncJob } from "../../../domain/entities/ShopifySyncJob";
import { ChangeDetectionService } from "../../../domain/services/ChangeDetectionService";
import { MarkStaleEntitiesUseCase } from "./MarkStaleEntitiesUseCase";
import { ShopifyEntityType } from "../../../domain/valueObjects/ShopifyEntityType";
import { SyncCursor } from "../../../domain/types/SyncCursor";
import { logger } from "../../../../../libs/common/logger";

/**
 * RunSyncJobUseCase — intentionally NOT a BaseService.
 *
 * Workers are NOT request-scoped. This use case is constructed once and
 * processes jobs for any tenant. The tenant identity comes from job.tenantId,
 * NOT from a constructor-injected TenantContext singleton.
 */
export class RunSyncJobUseCase {
    constructor(
        private readonly shopifyClient: IShopifyGraphQLClient,
        private readonly stagingRepository: IStagingRepository,
        private readonly connectorRepository: IConnectorRepository,
        private readonly syncJobRepository: ISyncJobRepository,
        private readonly changeDetectionService: ChangeDetectionService,
        private readonly markStaleEntities: MarkStaleEntitiesUseCase
    ) {}

    async execute(job: ShopifySyncJob): Promise<void> {
        try {
            logger.info(`Starting RunSyncJobUseCase for tenant: ${job.storeId}`, { jobId: job.id });

            // 1. Load credentials — keyed by job.tenantId (the real tenant)
            const credentials = await this.connectorRepository.getCredentials(job.storeId);

            // 2. Restore cursor
            const fullCursor = await this.stagingRepository.getCursor(job.tenantId, job.id) || {
                productsCursor: null,
                customersCursor: null,
                ordersCursor: null,
            };

            // 3. Sync Products
            await this.syncEntityCollection({
                job,
                credentials,
                entityType: "product",
                cursor: fullCursor.productsCursor,
                pageSize: 50,
                fetchFn: this.shopifyClient.fetchProducts.bind(this.shopifyClient),
                onPageProgress: async (cursor) => {
                    fullCursor.productsCursor = cursor;
                    await this.saveCursor(job, fullCursor);
                },
            });

            // 4. Sync Customers
            try {
                await this.syncEntityCollection({
                    job,
                    credentials,
                    entityType: "customer",
                    cursor: fullCursor.customersCursor,
                    pageSize: 50,
                    fetchFn: this.shopifyClient.fetchCustomers.bind(this.shopifyClient),
                    onPageProgress: async (cursor) => {
                        fullCursor.customersCursor = cursor;
                        await this.saveCursor(job, fullCursor);
                    },
                });
            } catch (error: any) {
                if (error.name === "InsufficientScopeError") {
                    logger.warn("Skipping customers sync due to insufficient scope", { tenantId: job.tenantId });
                } else {
                    throw error;
                }
            }

            // 5. Sync Orders
            try {
                await this.syncEntityCollection({
                    job,
                    credentials,
                    entityType: "order",
                    cursor: fullCursor.ordersCursor,
                    pageSize: 50,
                    fetchFn: this.shopifyClient.fetchOrders.bind(this.shopifyClient),
                    onPageProgress: async (cursor) => {
                        fullCursor.ordersCursor = cursor;
                        await this.saveCursor(job, fullCursor);
                    },
                });
            } catch (error: any) {
                if (error.name === "InsufficientScopeError") {
                    logger.warn("Skipping orders sync due to insufficient scope", { tenantId: job.tenantId });
                } else {
                    throw error;
                }
            }

            // 6. Mark Completed
            await this.syncJobRepository.markCompleted(job.id, job.progress);

            logger.info(`Completed RunSyncJobUseCase for tenant: ${job.tenantId}`, { jobId: job.id });
        } catch (error: any) {
            logger.error("RunSyncJobUseCase failed", { jobId: job.id, error: error.message });
            throw error;
        }
    }

    private async syncEntityCollection(params: {
        job: ShopifySyncJob;
        credentials: any;
        entityType: "product" | "customer" | "order";
        cursor: string | null;
        pageSize: number;
        fetchFn: (input: any) => Promise<any>;
        onPageProgress: (cursor: string | null) => Promise<void>;
    }): Promise<void> {
        let currentCursor = params.cursor;
        let hasNextPage = true;
        const seenIds = new Set<string>();
        const shopifyEntityType = ShopifyEntityType.fromString(params.entityType);

        while (hasNextPage) {
            const page = await params.fetchFn({
                credentials: params.credentials,
                cursor: currentCursor,
                pageSize: params.pageSize,
            });

            for (const entity of page.items) {
                const hash = this.changeDetectionService.computeHash(entity);
                const stored = await this.stagingRepository.findByExternalId(
                    params.job.tenantId,
                    shopifyEntityType,
                    entity.externalId
                );

                if (this.changeDetectionService.hasChanged(hash, stored)) {
                    const enrichStatus =
                        this.changeDetectionService.needsImageEnrichment(shopifyEntityType, entity, stored)
                            ? "pending"
                            : "skip";

                    await this.stagingRepository.upsert({
                        tenantId: params.job.tenantId,
                        entityType: shopifyEntityType,
                        externalId: entity.externalId,
                        parentExternalId: (entity as any).productExternalId || null,
                        payload: entity,
                        payloadHash: hash.value,
                        deleted: false,
                        shopifyUpdatedAt: entity.updatedAt,
                        embedStatus: "pending",
                        enrichStatus,
                    });
                }
                seenIds.add(entity.externalId);
            }

            currentCursor = page.nextCursor;
            hasNextPage = page.hasNextPage;

            await params.onPageProgress(currentCursor);
            if (!hasNextPage) break;
        }

        await this.markStaleEntities.execute({
            tenantId: params.job.tenantId,
            entityType: shopifyEntityType,
            seenExternalIds: seenIds,
        });
    }

    private async saveCursor(job: ShopifySyncJob, cursor: SyncCursor): Promise<void> {
        await this.stagingRepository.saveCursor(job.tenantId, job.id, cursor);
    }
}