-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathexecute-complete-bounty-workflow.ts
More file actions
259 lines (231 loc) · 6.79 KB
/
Copy pathexecute-complete-bounty-workflow.ts
File metadata and controls
259 lines (231 loc) · 6.79 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
import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
import { WorkflowConditionAttribute, WorkflowContext } from "@/lib/types";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { sendBatchEmail, sendEmail } from "@dub/email";
import BountyCompleted from "@dub/email/templates/bounty-completed";
import NewBountySubmission from "@dub/email/templates/bounty-new-submission";
import { prisma } from "@dub/prisma";
import {
BountySubmissionStatus,
Workflow,
WorkspaceRole,
} from "@dub/prisma/client";
import { createId } from "../create-id";
import { getWorkspaceUsers } from "../get-workspace-users";
import { parseWorkflowConfig } from "./parse-workflow-config";
const terminalStatusReason: Record<
Exclude<BountySubmissionStatus, "draft">,
string
> = {
submitted: "finished",
approved: "been awarded",
rejected: "been rejected",
};
export const executeCompleteBountyWorkflow = async ({
workflow,
context,
}: {
workflow: Workflow;
context: WorkflowContext;
}) => {
const { condition, action } = parseWorkflowConfig(workflow);
if (action.type !== WORKFLOW_ACTION_TYPES.AwardBounty) {
return;
}
const { bountyId } = action.data;
const { identity, metrics } = context;
const { partnerId, groupId, customerId, customerFirstSaleAt } = identity;
if (!groupId) {
console.error("Partner groupId not set in the context.");
return;
}
// Find the bounty
const bounty = await prisma.bounty.findUnique({
where: {
id: bountyId,
},
include: {
program: true,
groups: true,
submissions: {
where: {
partnerId,
},
},
},
});
if (!bounty) {
console.error(`Bounty ${bountyId} not found.`);
return;
}
if (!bounty.rewardAmount) {
console.error(`Bounty ${bountyId} has no reward amount.`);
return;
}
// this won't happen as we create workflows for performance based bounties only
if (bounty.type !== "performance") {
console.error(`Bounty ${bountyId} is not a performance based bounty.`);
return;
}
const now = new Date();
// Check if bounty is active
if (
(bounty.startsAt && bounty.startsAt > now) ||
(bounty.endsAt && bounty.endsAt < now) ||
bounty.archivedAt
) {
console.log(`Bounty ${bounty.id} is no longer active.`);
return;
}
const { groups, submissions } = bounty;
// If the bounty is part of a group, check if the partner is in the group
if (groups.length > 0) {
const groupIds = groups.map(({ groupId }) => groupId);
if (!groupIds.includes(groupId)) {
console.log(
`Partner ${partnerId} is not eligible for bounty ${bounty.id} because they are not in any of the assigned groups. Partner's groupId: ${groupId}. Assigned groupIds: ${groupIds.join(", ")}.`,
);
return;
}
}
if (submissions.length > 0) {
const submission = submissions[0];
if (submission.status !== "draft") {
const reason = terminalStatusReason[submission.status];
if (reason) {
console.log(
`Partner ${partnerId} has already ${reason} this bounty (bountyId: ${bounty.id}, submissionId: ${submission.id}).`,
);
return;
}
}
}
if (
bounty.performanceScope === "new" &&
customerFirstSaleAt &&
customerFirstSaleAt < bounty.startsAt
) {
console.log(
`Bounty ${bounty.id} is for net-new revenue only and partner ${partnerId} referred customer ${customerId} before the bounty started, skipping...`,
);
return;
}
console.log(
`Partner is eligible for bounty ${bounty.id}, executing workflow ${bounty.workflowId}...`,
);
const finalContext: Partial<
Record<WorkflowConditionAttribute, number | null>
> = {
totalLeads: metrics?.current?.leads ?? 0,
totalConversions: metrics?.current?.conversions ?? 0,
totalSaleAmount: metrics?.current?.saleAmount ?? 0,
totalCommissions: metrics?.current?.commissions ?? 0,
};
const performanceCount = finalContext[condition.attribute] ?? 0;
const periodNumber = 1; // Only one submission is allowed for performance based bounties
// Create or update the submission
const bountySubmission = await prisma.bountySubmission.upsert({
where: {
bountyId_partnerId_periodNumber: {
bountyId,
partnerId,
periodNumber,
},
},
create: {
id: createId({ prefix: "bnty_sub_" }),
programId: bounty.programId,
partnerId,
bountyId: bounty.id,
periodNumber,
status: "draft",
performanceCount,
},
update: {
performanceCount: {
increment: performanceCount,
},
},
});
// Check if the bounty submission meet the reward criteria
const shouldExecute = evaluateWorkflowConditions({
conditions: [condition],
attributes: {
[condition.attribute]: Number(bountySubmission.performanceCount ?? 0),
},
});
if (!shouldExecute) {
console.log(
`Bounty submission ${bountySubmission.id} does not meet the trigger condition.`,
);
return;
}
// Mark the bounty as submitted
const { partner } = await prisma.bountySubmission.update({
where: {
id: bountySubmission.id,
status: "draft",
},
data: {
status: "submitted",
completedAt: new Date(),
},
include: {
partner: true,
},
});
if (partner.email) {
await sendEmail({
subject: "Bounty completed!",
to: partner.email,
variant: "notifications",
replyTo: bounty.program.supportEmail || "noreply",
react: BountyCompleted({
email: partner.email,
bounty: {
name: bounty.name,
type: bounty.type,
},
program: {
name: bounty.program.name,
slug: bounty.program.slug,
},
}),
});
// Send email to the program owners
// TODO: combine with what we're doing on createBountySubmissionAction maybe?
const { users, program, ...workspace } = await getWorkspaceUsers({
programId: bounty.programId,
role: WorkspaceRole.owner,
notificationPreference: "newBountySubmitted",
});
if (users.length > 0) {
await sendBatchEmail(
users.map((user) => ({
variant: "notifications",
to: user.email,
subject: "New bounty submission",
react: NewBountySubmission({
email: user.email,
workspace: {
slug: workspace.slug,
},
bounty: {
id: bounty.id,
name: bounty.name,
},
partner: {
id: partner.id,
name: partner.name,
image: partner.image,
email: partner.email!,
},
submission: {
id: bountySubmission.id,
},
}),
})),
);
}
}
};