Spaces:
Sleeping

File size: 4,930 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
import { BaseService } from "../../../../../libs/shared/application/BaseService";
import { TenantContext } from "../../../../../libs/shared/domain/valueObjects/TenantContext";
import { IShopifyGraphQLClient } from "../../../domain/repositories/IShopifyGraphQLClient";
import { IConnectorRepository } from "../../../domain/repositories/IConnectorRepository";
import { IStagingRepository } from "../../../domain/repositories/IStagingRepository";
import { ChangeDetectionService } from "../../../domain/services/ChangeDetectionService";
import { ShopifyEntityType } from "../../../domain/valueObjects/ShopifyEntityType";
import { logger } from "../../../../../libs/common/logger";
import { N8nForwardingService } from "../../../../n8n/N8nForwardingService";

export class ProcessCustomerWebhookUseCase extends BaseService {
    constructor(
        tenantContext: TenantContext,
        private readonly shopifyClient: IShopifyGraphQLClient,
        private readonly connectorRepository: IConnectorRepository,
        private readonly stagingRepository: IStagingRepository,
        private readonly changeDetectionService: ChangeDetectionService,
        private readonly n8nForwardingService: N8nForwardingService,
        private readonly uowFactory: any // UnitOfWorkFactory
    ) {
        super(tenantContext);
    }

    async execute(input: {
        tenantId: string;
        eventType: string;
        entityId: string;
    }): Promise<void> {
        const entityType = ShopifyEntityType.fromString("customer");

        if (input.eventType === "shopify.customers.delete") {
            await this.stagingRepository.markDeleted(input.tenantId, entityType, input.entityId);

            // Forward deletion to n8n
            await this.n8nForwardingService.forwardWebhookEvent({
                organizationId: this.tenantContext.organizationId!,
                topic: input.eventType,
                tenantId: input.tenantId,
                payload: { id: input.entityId, deleted: true }
            });

            logger.info("webhook.customer_marked_deleted", {
                tenantId: input.tenantId,
                externalId: input.entityId,
            });
            return;
        }

        const credentials = await this.connectorRepository.getCredentials(input.tenantId);
        const customer = await this.shopifyClient.fetchCustomerById({
            credentials,
            externalId: input.entityId,
        });

        if (!customer) {
            logger.warn("webhook.customer_not_found_in_shopify", {
                tenantId: input.tenantId,
                externalId: input.entityId,
            });
            return;
        }

        const hash = this.changeDetectionService.computeHash(customer);
        const stored = await this.stagingRepository.findByExternalId(
            input.tenantId,
            entityType,
            input.entityId
        );

        if (!this.changeDetectionService.hasChanged(hash, stored)) {
            return;
        }

        // ── Atomic Update via Unit of Work ────────────────────────────────
        await this.uowFactory.execute(async ({ customers }: any) => {
            // 1. Update Core Structured Table
            await customers.upsert({
                tenantId: input.tenantId,
                shopifyId: input.entityId,
                email: customer.email,
                phone: customer.phone,
                firstName: customer.firstName,
                lastName: customer.lastName,
                ordersCount: customer.ordersCount,
                totalSpent: customer.totalSpent,
                tags: customer.tags,
                data: customer,
                shopifyUpdatedAt: customer.updatedAt,
            });

            // 2. Update Legacy Staging table
            await this.stagingRepository.upsert({
                tenantId: input.tenantId,
                entityType,
                externalId: input.entityId,
                parentExternalId: null,
                payload: customer,
                payloadHash: hash.value,
                deleted: false,
                shopifyUpdatedAt: customer.updatedAt,
                embedStatus: "pending",
                enrichStatus: "skip",
            });
        });

        // ── Forward to n8n ────────────────────────────────────────────────
        await this.n8nForwardingService.forwardWebhookEvent({
            organizationId: this.tenantContext.organizationId!,
            topic: input.eventType,
            tenantId: input.tenantId,
            payload: customer
        });

        logger.info("webhook.customer_migrated", {
            tenantId: input.tenantId,
            externalId: input.entityId,
            eventType: input.eventType,
        });
    }
}