-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathcomplete-program-applications.ts
More file actions
271 lines (249 loc) · 9 KB
/
Copy pathcomplete-program-applications.ts
File metadata and controls
271 lines (249 loc) · 9 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
import { prisma } from "@dub/prisma";
import { PlatformType, Prisma } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { createId } from "../api/create-id";
import { detectAndRecordFraudApplication } from "../api/fraud/detect-record-fraud-application";
import { notifyPartnerApplication } from "../api/partners/notify-partner-application";
import { markApplicationEventSubmitted } from "../application-events/update-application-event";
import { qstash } from "../cron";
import { buildSocialPlatformLookup } from "../social-utils";
import { sendWorkspaceWebhook } from "../webhook/publish";
import { partnerApplicationWebhookSchema } from "../zod/schemas/program-application";
import { evaluateApplicationRequirements } from "./evaluate-application-requirements";
import {
formatApplicationFormData,
formatWebsiteAndSocialsFields,
} from "./format-application-form-data";
/**
* Completes any outstanding program applications for a user
* by creating a program enrollment for each
*/
export async function completeProgramApplications(userEmail: string) {
try {
const user = await prisma.user.findUniqueOrThrow({
where: { email: userEmail },
select: {
partners: {
select: {
partnerId: true,
partner: {
include: {
platforms: true,
programs: {
select: {
programId: true,
tenantId: true,
status: true,
groupId: true,
},
},
},
},
},
},
},
});
if (!user.partners.length) {
return;
}
const programApplications = await prisma.programApplication.findMany({
where: {
email: userEmail,
enrollment: null,
// Exclude any applications for programs the user is already enrolled in
programId: {
notIn: user.partners
.map((p) => p.partner.programs.map((pp) => pp.programId))
.flat(),
},
},
include: {
program: true,
partnerGroup: true,
},
orderBy: {
createdAt: "desc",
},
});
if (!programApplications.length) {
return;
}
// if there are duplicate program applications
// pick the latest one for each programId
// note: programApplications is already sorted by createdAt desc
const seenProgramIds = new Set<string>();
const filteredProgramApplications = programApplications.filter(
(programApplication) => {
if (seenProgramIds.has(programApplication.programId)) {
return false;
}
seenProgramIds.add(programApplication.programId);
return true;
},
);
const partner = user.partners[0].partner;
// Program enrollments to create
const programEnrollments: Prisma.ProgramEnrollmentCreateManyInput[] =
filteredProgramApplications.map((programApplication) => ({
id: createId({ prefix: "pge_" }),
programId: programApplication.programId,
partnerId: user.partners[0].partnerId,
applicationId: programApplication.id,
groupId: programApplication?.partnerGroup?.id,
clickRewardId: programApplication?.partnerGroup?.clickRewardId,
leadRewardId: programApplication?.partnerGroup?.leadRewardId,
saleRewardId: programApplication?.partnerGroup?.saleRewardId,
discountId: programApplication?.partnerGroup?.discountId,
}));
await prisma.programEnrollment.createMany({
data: programEnrollments,
skipDuplicates: true,
});
// Fetch the programs' workspaces
const workspaces = await prisma.project.findMany({
where: {
defaultProgramId: {
in: filteredProgramApplications.map((p) => p.programId),
},
},
select: {
id: true,
defaultProgramId: true,
webhookEnabled: true,
},
});
// Map workspaces by their defaultProgramId for quick lookup
const workspacesByProgramId = new Map(
workspaces.map((ws) => [ws.defaultProgramId, ws]),
);
for (const programApplication of filteredProgramApplications) {
const application = programApplication;
const program = programApplication.program;
const group = programApplication.partnerGroup;
const programEnrollment = partner.programs.find(
(p) => p.programId === programApplication.programId,
);
const socialPlatforms = buildSocialPlatformLookup(partner.platforms);
const missingSocialFields = {
website:
application.website && !socialPlatforms.website?.identifier
? application.website
: undefined,
youtube:
application.youtube && !socialPlatforms.youtube?.identifier
? application.youtube
: undefined,
twitter:
application.twitter && !socialPlatforms.twitter?.identifier
? application.twitter
: undefined,
linkedin:
application.linkedin && !socialPlatforms.linkedin?.identifier
? application.linkedin
: undefined,
instagram:
application.instagram && !socialPlatforms.instagram?.identifier
? application.instagram
: undefined,
tiktok:
application.tiktok && !socialPlatforms.tiktok?.identifier
? application.tiktok
: undefined,
};
const hasMissingSocialFields = Object.values(missingSocialFields).some(
(field) => field !== undefined,
);
const applicationFormData = formatApplicationFormData(application).map(
({ title, value }) => ({
label: title,
value: value !== "" ? value : null,
}),
);
const { valid: validApplication } = evaluateApplicationRequirements({
applicationRequirements: program.applicationRequirements,
context: {
country: partner.country,
email: partner.email,
},
});
await Promise.allSettled([
...(validApplication
? [
notifyPartnerApplication({
partner,
program,
group,
application,
}),
// Auto-approve the partner if the group has auto-approval enabled
group?.autoApprovePartnersEnabledAt
? qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/auto-approve`,
body: {
programId: program.id,
partnerId: partner.id,
},
})
: Promise.resolve(null),
// Send "partner.application_submitted" webhook
workspacesByProgramId.has(program.id) &&
sendWorkspaceWebhook({
workspace: workspacesByProgramId.get(program.id)!,
trigger: "partner.application_submitted",
data: partnerApplicationWebhookSchema.parse({
id: application.id,
createdAt: application.createdAt,
partner: {
...partner,
...programEnrollment,
id: partner.id,
status: "pending",
...formatWebsiteAndSocialsFields(application),
},
applicationFormData,
}),
}),
]
: [
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/auto-reject`,
delay: 5 * 60, // 5 minutes
body: {
programId: program.id,
partnerId: partner.id,
},
}),
]),
// if the application has any website or social fields but the partner doesn't have the corresponding one (maybe they forgot to add during onboarding)
// update the partner to use the website they applied with
hasMissingSocialFields &&
prisma.partnerPlatform.createMany({
data: Object.entries(missingSocialFields)
.filter(([, identifier]) => identifier !== undefined)
.map(([platform, identifier]) => ({
partnerId: partner.id,
type: platform as PlatformType,
identifier: identifier as string,
})),
skipDuplicates: true,
}),
// Detect and record fraud events for the partner when they apply to a program
detectAndRecordFraudApplication({
context: {
program,
partner,
},
}),
]);
}
await Promise.allSettled(
programEnrollments.map((programEnrollment) =>
markApplicationEventSubmitted(programEnrollment, {
partnerNetworkStatus: partner.networkStatus,
}),
),
);
} catch (error) {
console.error("Failed to complete program applications", error);
}
}