-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtrack-sale.ts
More file actions
698 lines (638 loc) · 18.1 KB
/
Copy pathtrack-sale.ts
File metadata and controls
698 lines (638 loc) · 18.1 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
import { DubApiError } from "@/lib/api/errors";
import { includeTags } from "@/lib/api/links/include-tags";
import { generateRandomName } from "@/lib/names";
import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { prisma } from "@/lib/prisma";
import { isStored, storage } from "@/lib/storage";
import {
getClickEvent,
getLeadEvent,
recordLead,
recordSale,
} from "@/lib/tinybird";
import {
ClickEventTB,
CustomerSource,
LeadEventTB,
WorkspaceProps,
} from "@/lib/types";
import { redis } from "@/lib/upstash";
import { publishWorkspaceClicksUsageEvent } from "@/lib/upstash/redis-streams/workspace-clicks-usage";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
transformLeadEventData,
transformSaleEventData,
} from "@/lib/webhook/transform";
import {
trackSaleRequestSchema,
trackSaleResponseSchema,
} from "@/lib/zod/schemas/sales";
import { nanoid, R2_URL } from "@dub/utils";
import { Customer, Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { createId } from "../create-id";
import { syncPartnerLinksStats } from "../partners/sync-partner-links-stats";
import { executeWorkflows } from "../workflows/execute-workflows";
type TrackSaleParams = z.input<typeof trackSaleRequestSchema> & {
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
source?: CustomerSource; // default is "tracked"
};
export const trackSale = async ({
clickId,
customerExternalId,
customerName,
customerEmail,
customerAvatar,
amount,
currency = "usd",
eventName,
paymentProcessor,
invoiceId,
leadEventName,
metadata,
workspace,
source = "tracked",
}: TrackSaleParams) => {
let existingCustomer: Customer | null = null;
let newCustomer: Customer | null = null;
let leadEventData: LeadEventTB | null = null;
let shouldTrackDirectSaleLead = false;
// Return idempotent response if invoiceId is already processed
if (invoiceId) {
const cachedResponse = await redis.get(
`trackSale:${workspace.id}:invoiceId:${invoiceId}`,
);
if (cachedResponse) {
return cachedResponse;
}
}
// Find existing customer
existingCustomer = await prisma.customer.findUnique({
where: {
projectId_externalId: {
projectId: workspace.id,
externalId: customerExternalId,
},
},
});
// Existing customer is found, find the lead event to associate the sale with
if (existingCustomer) {
const leadEvent = await getLeadEvent({
customerId: existingCustomer.id,
eventName: leadEventName,
});
if (!leadEvent) {
const errorMessage = `Lead event not found for externalId: ${customerExternalId} and leadEventName: ${leadEventName}`;
throw new DubApiError({
code: "not_found",
message: errorMessage,
});
}
leadEventData = {
...leadEvent,
workspace_id: leadEvent.workspace_id || workspace.id, // in case for some reason the lead event doesn't have workspace_id
};
}
// If no existing customer is found and no clickId is provided, return an error
if (!existingCustomer && !clickId) {
return {
eventName,
customer: null,
sale: null,
};
}
let clickData: ClickEventTB | null = null;
// Find the click event for the given clickId
if (clickId) {
clickData = await getClickEvent({
clickId,
});
if (!clickData) {
throw new DubApiError({
code: "not_found",
message: `Click event not found for clickId: ${clickId}`,
});
}
// For the same customer, a sale event might come from a different link click than the original lead event.
// We want to attribute the sale to the correct link (the one from the clickId) for direct sale tracking.
if (leadEventData) {
leadEventData = {
...leadEventData,
...clickData,
};
}
}
// Direct sale tracking: create the customer from the click event.
// On concurrent requests, fall back to fetching the existing row (P2002) instead of failing.
if (!existingCustomer && clickData) {
const link = await prisma.link.findUnique({
where: {
id: clickData.link_id,
},
select: {
id: true,
projectId: true,
disabledAt: true,
},
});
if (!link) {
throw new DubApiError({
code: "not_found",
message: `Link not found for clickId: ${clickData.click_id}`,
});
}
if (link.projectId !== workspace.id) {
throw new DubApiError({
code: "not_found",
message: `Link ${link.id} for clickId ${clickData.click_id} does not belong to the workspace`,
});
}
if (link.disabledAt) {
throw new DubApiError({
code: "not_found",
message: `Link ${link.id} for clickId ${clickData.click_id} is disabled, sale not tracked`,
});
}
const finalCustomerId = createId({ prefix: "cus_" });
const finalCustomerName =
customerName || customerEmail || generateRandomName();
const finalCustomerAvatar =
customerAvatar && !isStored(customerAvatar)
? `${R2_URL}/customers/${finalCustomerId}/avatar_${nanoid(7)}`
: customerAvatar;
try {
newCustomer = await prisma.customer.create({
data: {
id: finalCustomerId,
name: finalCustomerName,
email: customerEmail,
avatar: finalCustomerAvatar,
externalId: customerExternalId,
linkId: clickData.link_id,
clickId: clickData.click_id,
country: clickData.country,
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
clickedAt: new Date(clickData.timestamp + "Z"),
},
});
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === "P2002"
) {
existingCustomer = await prisma.customer.findUniqueOrThrow({
where: {
projectId_externalId: {
projectId: workspace.id,
externalId: customerExternalId,
},
},
});
} else {
throw error;
}
}
// Persist customer avatar to R2 if it's not already stored
if (customerAvatar && !isStored(customerAvatar) && finalCustomerAvatar) {
waitUntil(
storage
.upload({
key: finalCustomerAvatar.replace(`${R2_URL}/`, ""),
body: customerAvatar,
opts: {
width: 128,
height: 128,
},
})
.catch(async (error) => {
console.error("Error persisting customer avatar to R2", error);
// if the avatar fails to upload to R2, set the avatar to null in the database
if (newCustomer) {
await prisma.customer.update({
where: {
id: newCustomer.id,
},
data: {
avatar: null,
},
});
}
}),
);
}
// if leadEventName is provided, use it
// otherwise use "Direct sale tracking lead event" (since it's for direct sale tracking)
const finalLeadEventName =
leadEventName ?? "Direct sale tracking lead event";
if (newCustomer) {
leadEventData = {
...clickData,
event_id: nanoid(16),
event_name: finalLeadEventName,
customer_id: newCustomer.id,
metadata: metadata ? JSON.stringify(metadata) : "",
};
} else if (existingCustomer) {
const leadEvent = await getLeadEvent({
customerId: existingCustomer.id,
eventName: leadEventName,
});
leadEventData = leadEvent
? {
...leadEvent,
...clickData,
}
: {
...clickData,
event_id: nanoid(16),
event_name: finalLeadEventName,
customer_id: existingCustomer.id,
metadata: metadata ? JSON.stringify(metadata) : "",
};
}
// Deduplicate lead events across concurrent direct sale requests
if (leadEventData) {
const cacheKey = `directSaleTrackLead:${workspace.id}:${customerExternalId}:${finalLeadEventName.toLowerCase().replaceAll(" ", "-")}`;
const cachedLeadEvent = await redis.set(
cacheKey,
{
timestamp: Date.now(),
},
{
ex: 30, // 30 seconds
nx: true,
},
);
shouldTrackDirectSaleLead = cachedLeadEvent !== null;
}
}
const customer = existingCustomer ?? newCustomer;
// This should never happen, but just in case
if (!customer) {
return {
eventName,
customer: null,
sale: null,
};
}
const [_, trackedSale] = await Promise.all([
shouldTrackDirectSaleLead &&
_trackLead({
workspace,
leadEventData,
customer,
}),
_trackSale({
amount,
currency,
eventName,
paymentProcessor,
invoiceId,
metadata,
workspace,
leadEventData,
customer,
source,
}),
]);
return trackedSale;
};
// Track the lead event
const _trackLead = async ({
workspace,
leadEventData,
customer,
}: Pick<TrackSaleParams, "workspace"> & {
leadEventData: LeadEventTB | null;
customer: Customer;
}) => {
if (!leadEventData) {
throw new DubApiError({
code: "not_found",
message: `Lead event data not found for the customer ${customer.id}`,
});
}
waitUntil(
(async () => {
const [_leadEvent, link, _workspace] = await Promise.all([
// Record the lead event for the customer
recordLead({
...leadEventData,
workspace_id: leadEventData.workspace_id || workspace.id, // in case for some reason the lead event doesn't have workspace_id
}),
// Update link leads count + lastLeadAt date
prisma.link.update({
where: {
id: leadEventData.link_id,
},
data: {
leads: {
increment: 1,
},
lastLeadAt: new Date(),
},
include: includeTags,
}),
// Update workspace events usage
prisma.project.update({
where: {
id: workspace.id,
},
data: {
usage: {
increment: 1,
},
},
}),
]);
// Create partner commission and execute workflows
if (link.programId && link.partnerId && customer) {
await Promise.allSettled([
executeWorkflows({
trigger: "partnerMetricsUpdated",
reason: "lead",
identity: {
workspaceId: workspace.id,
programId: link.programId,
partnerId: link.partnerId,
},
metrics: {
current: {
leads: 1,
},
},
}),
syncPartnerLinksStats({
partnerId: link.partnerId,
programId: link.programId,
eventType: "lead",
}),
]);
}
await Promise.allSettled([
sendWorkspaceWebhook({
trigger: "lead.created",
data: transformLeadEventData({
...leadEventData,
link,
customer,
}),
workspace,
}),
...(link.partnerId
? [
sendPartnerPostback({
partnerId: link.partnerId,
event: "lead.created",
data: {
...leadEventData,
link,
customer,
},
}),
]
: []),
]);
})(),
);
};
// Track the sale event
const _trackSale = async ({
amount,
currency = "usd",
eventName,
paymentProcessor,
invoiceId,
metadata,
workspace,
leadEventData,
customer,
source,
}: Omit<TrackSaleParams, "customerExternalId"> & {
leadEventData: LeadEventTB | null;
customer: Customer;
}) => {
if (!leadEventData) {
throw new DubApiError({
code: "not_found",
message: `Lead event data not found for the customer ${customer.id}`,
});
}
// Skip if amount is 0 or less
if (amount <= 0) {
return {
eventName,
customer: null,
sale: null,
};
}
// if currency is not USD, convert it to USD based on the current FX rate
// TODO: allow custom "defaultCurrency" on workspace table in the future
if (currency !== "usd") {
const { currency: convertedCurrency, amount: convertedAmount } =
await convertCurrency({
currency,
amount,
});
currency = convertedCurrency;
amount = convertedAmount;
}
const saleData = {
...leadEventData,
workspace_id: leadEventData.workspace_id || workspace.id, // in case for some reason the lead event doesn't have workspace_id
event_id: nanoid(16),
event_name: eventName,
customer_id: customer.id,
payment_processor: paymentProcessor,
amount,
currency,
invoice_id: invoiceId || "",
metadata: metadata ? JSON.stringify(metadata) : "",
};
let firstConversionFlag = isFirstConversion({
customer,
linkId: saleData.link_id,
});
// Deduplicate concurrent first sales for the same customer + link so only one
// request is counted as the first conversion.
if (firstConversionFlag) {
const claim = await redis.set(
`firstConversion:${customer.id}:${saleData.link_id}`,
1,
{
ex: 30,
nx: true,
},
);
firstConversionFlag = claim !== null;
}
waitUntil(
(async () => {
// Update link conversions, sales, and saleAmount
const link = await prisma.link.update({
where: {
id: saleData.link_id,
},
data: {
...(firstConversionFlag && {
conversions: {
increment: 1,
},
lastConversionAt: new Date(),
}),
sales: {
increment: 1,
},
saleAmount: {
increment: amount,
},
},
include: includeTags,
});
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,
customerId: customer.id,
eventId: saleData.event_id,
amount: saleData.amount,
quantity: 1,
invoiceId,
currency,
context: {
customer: {
country: customer.country,
signupDate: customer.createdAt,
source,
},
sale: {
productId: metadata?.productId,
amount: saleData.amount,
...(metadata != null && { metadata }),
},
},
clickEvent: {
url: saleData.url,
referer: saleData.referer,
},
isFirstConversion: firstConversionFlag,
});
await Promise.allSettled([
executeWorkflows({
trigger: "partnerMetricsUpdated",
reason: "sale",
identity: {
workspaceId: workspace.id,
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",
}),
]);
}
await Promise.allSettled([
recordSale({
...saleData,
timestamp: undefined,
}),
sendWorkspaceWebhook({
trigger: "sale.created",
data: transformSaleEventData({
...saleData,
clickedAt: customer.clickedAt || customer.createdAt,
link,
customer,
partner: result?.webhookPartner,
metadata,
}),
workspace,
}),
...(link.partnerId
? [
sendPartnerPostback({
partnerId: link.partnerId,
event: "sale.created",
data: {
...saleData,
clickedAt: customer.clickedAt || customer.createdAt,
link,
customer,
},
}),
]
: []),
publishWorkspaceClicksUsageEvent({
linkId: link.id,
workspaceId: workspace.id,
timestamp: new Date().toISOString(),
}),
]);
// Update customer stats + program/partner associations
await prisma.customer.update({
where: {
id: customer.id,
},
data: {
...(link.programId && {
programId: link.programId,
}),
...(link.partnerId && {
partnerId: link.partnerId,
}),
sales: {
increment: 1,
},
saleAmount: {
increment: amount,
},
firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
},
});
})(),
);
const trackSaleResponse = trackSaleResponseSchema.parse({
eventName,
customer,
sale: {
amount,
currency,
invoiceId,
paymentProcessor,
metadata,
},
});
if (invoiceId) {
waitUntil(
redis.set(
`trackSale:${workspace.id}:invoiceId:${invoiceId}`,
trackSaleResponse,
{
ex: 60 * 60 * 24 * 7, // cache for 1 week
},
),
);
}
return trackSaleResponse;
};