-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathroute.ts
More file actions
373 lines (337 loc) · 10.6 KB
/
Copy pathroute.ts
File metadata and controls
373 lines (337 loc) · 10.6 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
import { createPartnerDefaultLinks } from "@/lib/api/partners/create-partner-default-links";
import { getGroupRewardsAndBounties } from "@/lib/api/partners/get-group-rewards-and-bounties";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { logger } from "@/lib/axiom/server";
import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";
import { getWorkflowConfig } from "@/lib/cron/qstash-workflow";
import { generateDiscountCodeForPartner } from "@/lib/discounts/generate-discount-code-for-partner";
import { createReferralCommission } from "@/lib/partner-referrals/create-referral-commission";
import { prisma } from "@/lib/prisma";
import { polyfillSocialMediaFields } from "@/lib/social-utils";
import { PlanProps } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { EnrolledPartnerSchema } from "@/lib/zod/schemas/partners";
import { ProgramPartnerLinkSchema } from "@/lib/zod/schemas/programs";
import { sendBatchEmail } from "@dub/email";
import PartnerApplicationApproved from "@dub/email/templates/partner-application-approved";
import { NETWORK_PROGRAM_ID } from "@dub/utils";
import { serve } from "@upstash/workflow/nextjs";
import * as z from "zod/v4";
const inputSchema = z.object({
programId: z.string(),
partnerId: z.string(),
userId: z.string(),
});
type Input = z.infer<typeof inputSchema>;
/**
* Partner Approved Workflow
*
* This workflow is triggered when a partner's application to join a program is approved.
* It performs the following steps in sequence:
*
* 1. **Create Default Links**: Creates partner-specific default links based on the group's
* configuration.
*
* 2. **Create Discount Codes**: If the group's discount has auto-provisioning enabled,
* creates a discount code for the partner.
*
* 3. **Send Email Notification**: Sends an approval email to all partner users who have
* opted in to receive application approval notifications.
*
* 4. **Send Webhook**: Notifies the workspace via webhook that a new partner has been
* enrolled in the program.
*
* 5. **Trigger Draft Bounty Submission Creation**: Triggers the creation of
* draft bounty submissions for the partner if they are eligible for performance bounties.
*
* 6. **Execute Dub Workflows**: Executes Dub workflows using the “partnerEnrolled” trigger.
*/
// POST /api/workflows/partner-approved
export const { POST } = serve<Input>(
async (context) => {
const input = context.requestPayload;
const { programId, partnerId, userId } = input;
const {
program,
partner,
links: existingPartnerLinks,
...programEnrollment
} = await getProgramEnrollmentOrThrow({
programId,
partnerId,
include: {
program: true,
partner: true,
links: true,
},
});
const { groupId } = programEnrollment;
const allPartnerLinks =
ProgramPartnerLinkSchema.array().parse(existingPartnerLinks);
// Step 1: Create partner default links
await context.run("create-default-links", async () => {
if (!groupId) {
console.error(
`The partner ${partnerId} is not associated with any group.`,
);
return;
}
let { partnerGroupDefaultLinks, utmTemplate } =
await prisma.partnerGroup.findUniqueOrThrow({
where: {
id: groupId,
},
include: {
partnerGroupDefaultLinks: true,
utmTemplate: true,
},
});
if (partnerGroupDefaultLinks.length === 0) {
console.error(`Group ${groupId} does not have any default links.`);
return;
}
// Skip existing default links (should never happen since it's a new partner, but just in case)
for (const link of existingPartnerLinks) {
if (link.partnerGroupDefaultLinkId) {
partnerGroupDefaultLinks = partnerGroupDefaultLinks.filter(
(defaultLink) => defaultLink.id !== link.partnerGroupDefaultLinkId,
);
}
}
if (partnerGroupDefaultLinks.length === 0) {
console.error(
`Already created default links for partner ${partnerId}.`,
);
return;
}
// Find the workspace
const workspace = await prisma.project.findUniqueOrThrow({
where: {
id: program.workspaceId,
},
select: {
id: true,
plan: true,
webhookEnabled: true,
stripeConnectId: true,
shopifyStoreId: true,
},
});
const partnerLinks = await createPartnerDefaultLinks({
workspace: {
id: workspace.id,
plan: workspace.plan as PlanProps,
},
program: {
id: program.id,
defaultFolderId: program.defaultFolderId,
},
partner: {
id: partner.id,
name: partner.name,
email: partner.email!,
tenantId: programEnrollment.tenantId ?? undefined,
},
group: {
defaultLinks: partnerGroupDefaultLinks,
utmTemplate: utmTemplate,
},
userId,
});
console.info({
message: `Created ${partnerLinks.length} partner default links.`,
data: partnerLinks.map(({ id, url, shortLink }) => ({
id,
url,
shortLink,
})),
});
allPartnerLinks.push(...partnerLinks);
return;
});
// for network program, only need to create default links
if (program.id === NETWORK_PROGRAM_ID) {
return;
}
// Step 2: Auto-provision discount code if enabled
await context.run("create-discount-codes", async () => {
const workspace = await prisma.project.findUniqueOrThrow({
where: {
id: program.workspaceId,
},
select: {
id: true,
plan: true,
webhookEnabled: true,
stripeConnectId: true,
shopifyStoreId: true,
},
});
await generateDiscountCodeForPartner({
workspace,
partner: {
id: partner.id,
name: partner.name,
groupId,
},
});
});
// Step 3: Send email to partner application approved
await context.run("send-email", async () => {
if (!groupId) {
console.error(
`The partner ${partnerId} is not associated with any group.`,
);
return;
}
// Find the partner users to send email notification
const partnerUsers = await prisma.partnerUser.findMany({
where: {
partnerId,
notificationPreferences: {
applicationApproved: true,
},
user: {
email: {
not: null,
},
},
},
select: {
user: {
select: {
id: true,
email: true,
},
},
},
});
if (partnerUsers.length === 0) {
console.log(
`No partner users found for partner ${partnerId} to send email notification.`,
);
return;
}
const rewardsAndBounties = await getGroupRewardsAndBounties({
programId,
groupId: programEnrollment.groupId || program.defaultGroupId,
});
// Resend batch email
const { data, error } = await sendBatchEmail(
partnerUsers.map(({ user }) => ({
variant: "notifications",
to: user.email!,
subject: `Your application to ${program.name} has been approved!`,
replyTo: program.supportEmail || "noreply",
react: PartnerApplicationApproved({
program: {
name: program.name,
logo: program.logo,
slug: program.slug,
},
partner: {
name: partner.name,
email: user.email!,
payoutsEnabled: Boolean(partner.payoutsEnabledAt),
},
...rewardsAndBounties,
}),
})),
{
idempotencyKey: `application-approved/${programEnrollment.id}`,
},
);
if (data) {
console.info({
message: `Sent emails to ${partnerUsers.length} partner users.`,
data: data,
});
}
if (error) {
throw new Error(error.message);
}
});
// Step 4: Send webhook to workspace
await context.run("send-webhook", async () => {
const partnerPlatforms = await prisma.partnerPlatform.findMany({
where: {
partnerId,
},
});
const enrolledPartner = EnrolledPartnerSchema.parse({
...programEnrollment,
...partner,
...polyfillSocialMediaFields(partnerPlatforms),
id: partner.id,
links: allPartnerLinks,
});
const workspace = await prisma.project.findUniqueOrThrow({
where: {
id: program.workspaceId,
},
select: {
id: true,
webhookEnabled: true,
},
});
await sendWorkspaceWebhook({
workspace,
trigger: "partner.enrolled",
data: enrolledPartner,
});
});
// Step 5: Trigger draft bounty submission creation
await context.run("trigger-draft-bounty-submission-creation", async () => {
await triggerDraftBountySubmissionCreation({
programId,
partnerIds: [partnerId],
});
});
// Step 6: Execute Dub workflows using the “partnerEnrolled” trigger.
await context.run("execute-workflows", async () => {
await executeWorkflows({
event: "partnerEnrolled",
identity: {
workspaceId: program.workspaceId,
programId,
partnerId,
},
});
});
// Step 7: Create referral commission if enabled
await context.run("create-referral-commission", async () => {
await createReferralCommission({
partnerId,
programId,
});
});
},
{
initialPayloadParser: (requestPayload) => {
return inputSchema.parse(JSON.parse(requestPayload));
},
failureFunction: async ({
context,
failStatus,
failResponse,
failHeaders,
}) => {
const { correlation } = getWorkflowConfig({
workflowType: "partner-approved",
body: context.requestPayload,
});
logger.error("workflow.failed", {
service: "qstash",
event: "workflow.failed",
workflowType: "partner-approved",
workflowRunId: context.workflowRunId,
failStatus,
failResponse,
failHeaders,
correlation,
});
await logger.flush();
},
},
);