-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathattribute-via-promotion-code-id.ts
More file actions
243 lines (221 loc) · 6.95 KB
/
Copy pathattribute-via-promotion-code-id.ts
File metadata and controls
243 lines (221 loc) · 6.95 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
import { createId } from "@/lib/api/create-id";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
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 { recordLead } from "@/lib/tinybird";
import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
import { StripeMode } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
import { COUNTRIES_TO_CONTINENTS, nanoid } from "@dub/utils";
import { Project } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { getPromotionCode } from "./get-promotion-code";
import { incrementLinkLeads } from "./increment-link-leads";
export type PromoCodeCustomerDetails = {
name?: string | null;
email?: string | null;
address?: Pick<Stripe.Address, "country" | "state"> | null;
};
export async function attributeViaPromotionCodeId({
promotionCodeId,
stripeAccountId,
workspace,
mode,
stripeCustomerId,
customerDetails,
}: {
promotionCodeId: string; // must be Stripe's promotion code ID `promo_xxx`, not the actual promo code
stripeAccountId: string;
workspace: Pick<
Project,
"id" | "defaultProgramId" | "stripeConnectId" | "webhookEnabled"
>;
mode: StripeMode;
stripeCustomerId: string;
customerDetails: PromoCodeCustomerDetails;
}) {
// Find the promotion code for the promotion code id
const promotionCode = await getPromotionCode({
promotionCodeId,
stripeAccountId,
mode,
});
if (!promotionCode) {
console.log(
`Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, skipping...`,
);
return null;
}
if (!workspace.defaultProgramId) {
console.log(
`Workspace with stripeConnectId ${stripeAccountId} has no default program, skipping...`,
);
return null;
}
const discountCode = await prisma.discountCode.findUnique({
where: {
programId_code: {
programId: workspace.defaultProgramId,
code: promotionCode.code,
},
},
include: {
link: true,
},
});
if (!discountCode) {
console.log(
`Couldn't find discount code "${promotionCode.code}" in program "${workspace.defaultProgramId}", skipping...`,
);
return null;
}
if (discountCode.disabledAt) {
console.log(
`Discount code "${discountCode.code}" is disabled, skipping...`,
);
return null;
}
const link = discountCode.link;
const linkId = link.id;
const customerAddress = customerDetails.address;
const customerCountry = customerAddress?.country?.toUpperCase();
// Record a fake click for this event
const clickEvent = await recordFakeClick({
link,
customer: {
continent: customerCountry
? COUNTRIES_TO_CONTINENTS[customerCountry] ?? "Unknown"
: "Unknown",
country: customerCountry ?? "Unknown",
region: customerAddress?.state ?? "Unknown",
},
});
let customer: Awaited<ReturnType<typeof prisma.customer.create>>;
try {
customer = await prisma.customer.create({
data: {
id: createId({ prefix: "cus_" }),
name:
customerDetails.name || customerDetails.email || generateRandomName(),
email: customerDetails.email,
externalId: clickEvent.click_id,
stripeCustomerId,
linkId: clickEvent.link_id,
clickId: clickEvent.click_id,
clickedAt: new Date(clickEvent.timestamp + "Z"),
country: customerAddress?.country,
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
},
});
} catch (error) {
// a concurrent webhook may have created the customer first (unique stripeCustomerId)
if (error.code === "P2002") {
console.log(
`Customer with stripeCustomerId ${stripeCustomerId} was created concurrently, skipping promo code attribution...`,
);
return null;
}
throw error;
}
// Prepare the payload for the lead event
const { timestamp, ...rest } = clickEvent;
const leadEvent = {
...rest,
workspace_id: clickEvent.workspace_id || customer.projectId,
event_id: nanoid(16),
event_name: "Attributed via discount code",
customer_id: customer.id,
metadata: "",
};
await recordLead(leadEvent);
// cache lead event in Redis because the ingested event is not available immediately on Tinybird
// (the sale recording right after this relies on reading the lead event back)
await redis.set(`leadCache:${customer.id}`, leadEvent, {
ex: 60 * 5,
});
// record lead side effects (link stats, partner commissions, workflows, workspace webhook)
waitUntil(
(async () => {
const linkUpdated = await incrementLinkLeads(link.id);
let result:
| Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link.programId && link.partnerId) {
result = await queuePartnerCommissionCreation({
event: "lead",
programId: link.programId,
partnerId: link.partnerId,
linkId: link.id,
eventId: leadEvent.event_id,
customerId: customer.id,
quantity: 1,
context: {
customer: {
country: customer.country,
},
},
});
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",
workspace,
data: transformLeadEventData({
...leadEvent,
link: linkUpdated,
customer,
partner: result?.webhookPartner,
metadata: null,
}),
}),
...(link.partnerId
? [
sendPartnerPostback({
partnerId: link.partnerId,
event: "lead.created",
data: {
...leadEvent,
link: linkUpdated,
customer,
},
}),
]
: []),
]);
})(),
);
return {
linkId,
customer,
clickEvent,
leadEvent,
};
}