-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathcreate-sale.ts
More file actions
226 lines (209 loc) · 5.69 KB
/
Copy pathcreate-sale.ts
File metadata and controls
226 lines (209 loc) · 5.69 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
import { includeTags } from "@/lib/api/links/include-tags";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { recordSale } from "@/lib/tinybird";
import { LeadEventTB } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { orderSchema } from "./schema";
export async function createShopifySale({
event,
customerId,
workspaceId,
leadData,
}: {
event: any;
customerId: string;
workspaceId: string;
leadData: LeadEventTB;
}) {
const order = orderSchema.parse(event);
const {
checkout_token: checkoutToken,
confirmation_number: invoiceId,
current_subtotal_price_set: { shop_money: shopMoney },
} = order;
const amount = Math.round(Number(shopMoney.amount) * 100); // round to nearest cent
const { link_id: linkId } = leadData;
const currency = shopMoney.currency_code.toLowerCase();
// Skip if invoice id is already processed
const ok = await redis.set(
`dub_sale_events:linkId:${linkId}:invoiceId:${invoiceId}`,
1,
{
ex: 60 * 60 * 24 * 7,
nx: true,
},
);
if (!ok) {
return new Response(
`[Shopify] Order has been processed already. Skipping...`,
);
}
const saleData = {
...leadData,
workspace_id: leadData.workspace_id || workspaceId, // in case for some reason the lead event doesn't have workspace_id
event_id: nanoid(16),
event_name: "Purchase",
payment_processor: "shopify",
amount,
currency,
invoice_id: invoiceId,
metadata: JSON.stringify(order),
};
const existingCustomer = await prisma.customer.findUniqueOrThrow({
where: {
id: customerId,
},
});
const firstConversionFlag = isFirstConversion({
customer: existingCustomer,
linkId,
});
const [_sale, link, workspace, customer] = await Promise.all([
// record sale
recordSale(saleData),
// update link sales count
prisma.link.update({
where: {
id: linkId,
},
data: {
...(firstConversionFlag && {
conversions: {
increment: 1,
},
lastConversionAt: new Date(),
}),
sales: {
increment: 1,
},
saleAmount: {
increment: amount,
},
},
include: includeTags,
}),
// update workspace sales usage
prisma.project.update({
where: {
id: workspaceId,
},
data: {
usage: {
increment: 1,
},
},
}),
prisma.customer.update({
where: {
id: existingCustomer.id,
},
data: {
sales: {
increment: 1,
},
saleAmount: {
increment: amount,
},
firstSaleAt: existingCustomer.firstSaleAt ? undefined : new Date(),
},
}),
redis.del(`shopify:checkout:${checkoutToken}`),
]);
// for program links
let result:
| Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link.programId && link.partnerId) {
result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
partnerId: link.partnerId,
linkId: link.id,
eventId: saleData.event_id,
customerId: customer.id,
amount: saleData.amount,
quantity: 1,
invoiceId: saleData.invoice_id,
currency: saleData.currency,
context: {
customer: {
country: customer.country,
signupDate: customer.createdAt,
},
sale: {
amount: saleData.amount,
},
},
clickEvent: {
url: saleData.url,
referer: saleData.referer,
},
isFirstConversion: firstConversionFlag,
});
waitUntil(
Promise.allSettled([
executeWorkflows({
trigger: "partnerMetricsUpdated",
reason: "sale",
identity: {
workspaceId: workspaceId,
programId: link.programId,
partnerId: link.partnerId,
customerId: customer.id,
customerFirstSaleAt: customer.firstSaleAt ?? new Date(),
},
metrics: {
current: {
conversions: firstConversionFlag ? 1 : 0,
saleAmount: saleData.amount,
},
},
}),
syncPartnerLinksStats({
partnerId: link.partnerId,
programId: link.programId,
eventType: "sale",
}),
]),
);
}
waitUntil(
Promise.allSettled([
sendWorkspaceWebhook({
trigger: "sale.created",
workspace,
data: transformSaleEventData({
...saleData,
link,
clickedAt: customer.clickedAt || customer.createdAt,
customer,
partner: result?.webhookPartner,
metadata: null,
}),
}),
...(link?.partnerId
? [
sendPartnerPostback({
partnerId: link.partnerId,
event: "sale.created",
data: {
...saleData,
clickedAt: customer.clickedAt || customer.createdAt,
link,
customer,
},
}),
]
: []),
]),
);
}