-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathroute.ts
More file actions
205 lines (183 loc) · 5.39 KB
/
Copy pathroute.ts
File metadata and controls
205 lines (183 loc) · 5.39 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
import { withCron } from "@/lib/cron/with-cron";
import { createDiscountCode } from "@/lib/discounts/create-discount-code";
import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";
import { isDiscountProviderError } from "@/lib/discounts/discount-error";
import { isDiscountEquivalent } from "@/lib/discounts/is-discount-equivalent";
import { prisma } from "@/lib/prisma";
import { DiscountCode } from "@prisma/client";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
export const dynamic = "force-dynamic";
const inputSchema = z.object({
programId: z.string(),
groupId: z.string(),
partnerIds: z.array(z.string()),
isGroupDeleted: z.boolean().optional(),
});
// POST /api/cron/groups/remap-discount-codes
export const POST = withCron(async ({ rawBody }) => {
const { programId, partnerIds, groupId, isGroupDeleted } = inputSchema.parse(
JSON.parse(rawBody),
);
if (partnerIds.length === 0) {
return logAndRespond("No partner IDs provided.");
}
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
partnerId: {
in: partnerIds,
},
programId,
},
include: {
discountCodes: {
include: {
discount: true,
},
},
},
});
const oldDiscount = programEnrollments[0]?.discountCodes[0]?.discount;
if (programEnrollments.length === 0) {
return logAndRespond("No program enrollments found.");
}
const group = await prisma.partnerGroup.findUnique({
where: {
id: groupId,
},
include: {
discount: true,
},
});
if (!group) {
return logAndRespond("Group not found.");
}
const discountCodes = programEnrollments.flatMap(
({ discountCodes }) => discountCodes,
);
// Find the discount codes to update and remove
const discountCodesToUpdate: DiscountCode[] = [];
const discountCodesToRemove: typeof discountCodes = [];
for (const discountCode of discountCodes) {
const keepDiscountCode = isDiscountEquivalent(
group.discount,
discountCode.discount,
);
if (keepDiscountCode) {
discountCodesToUpdate.push(discountCode);
} else {
discountCodesToRemove.push(discountCode);
}
}
// Update the discount codes to use the new discount if they are equivalent
if (discountCodesToUpdate.length > 0) {
console.log(
`Found ${discountCodesToUpdate.length} discount codes equivalent to the new group's discount. Updating them.`,
);
await prisma.discountCode.updateMany({
where: {
id: {
in: discountCodesToUpdate.map(({ id }) => id),
},
},
data: {
discountId: group.discount?.id,
},
});
}
// Remove the previous discount codes
if (discountCodesToRemove.length > 0) {
console.log(
`Found ${discountCodesToRemove.length} discount codes not equivalent to the new group's discount. Deleting them.`,
);
await deleteDiscountCodes(discountCodesToRemove);
}
if (group.discount?.autoProvisionEnabledAt) {
// Find the partner default links that don't have a discount code yet
const links = await prisma.link.findMany({
where: {
partnerId: {
in: partnerIds,
},
programId,
partnerGroupDefaultLinkId: {
not: null,
},
discountCode: {
is: null,
},
},
select: {
id: true,
programEnrollment: {
select: {
partner: {
select: {
id: true,
name: true,
},
},
},
},
},
});
if (links.length > 0) {
const workspace = await prisma.project.findUniqueOrThrow({
where: {
defaultProgramId: programId,
},
select: {
id: true,
webhookEnabled: true,
stripeConnectId: true,
shopifyStoreId: true,
},
});
// Create discount code for the partner default links
for (const link of links) {
try {
await createDiscountCode({
workspace,
partner: link.programEnrollment!.partner,
link,
discount: group.discount,
});
} catch (error) {
if (isDiscountProviderError(error)) {
if (
error.providerCode === "INTEGRATION_NOT_AVAILABLE" ||
error.providerCode === "AUTH_EXPIRED" ||
error.providerCode === "PERMISSIONS_REQUIRED" ||
error.providerCode === "COUPON_NOT_FOUND"
) {
console.warn(
`${error.message} Skipping remaining discount code creation for remap.`,
);
break;
}
}
throw error;
}
}
}
}
// if the group is deleted, need to check if there are any remaining discount codes, if not, delete the discount
if (isGroupDeleted && oldDiscount) {
const remainingDiscountCodes = await prisma.discountCode.count({
where: {
discountId: oldDiscount.id,
},
});
if (remainingDiscountCodes === 0) {
await prisma.discount.deleteMany({
where: {
id: oldDiscount.id,
},
});
console.log(
`Deleted discount ${oldDiscount.id} because it has no remaining discount codes.`,
);
}
}
return logAndRespond("Finished remapping discount codes for the group.");
});