-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathcreate-discount-code.ts
More file actions
88 lines (79 loc) · 2.28 KB
/
Copy pathcreate-discount-code.ts
File metadata and controls
88 lines (79 loc) · 2.28 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
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { prisma } from "@/lib/prisma";
import { Discount, Link, Partner, Prisma, Project } from "@prisma/client";
import { constructDiscountCode } from "./construct-discount-code";
import { getDiscountProvider } from "./discount-provider";
interface CreateDiscountCodeArgs {
workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;
partner: Pick<Partner, "id" | "name">;
link: Pick<Link, "id">;
discount: Discount;
code?: string;
}
export async function createDiscountCode({
workspace,
partner,
link,
discount,
code,
}: CreateDiscountCodeArgs) {
const finalCode =
code ||
constructDiscountCode({
partner,
discount,
});
const linkWithCode = await prisma.link.findUnique({
where: { id: link.id },
select: { discountCode: { select: { code: true } } },
});
if (linkWithCode?.discountCode) {
throw new DubApiError({
code: "bad_request",
message: `This link already has a discount code (${linkWithCode.discountCode.code}) assigned.`,
});
}
const discountProvider = getDiscountProvider(discount.provider);
const externalDiscountCode = await discountProvider.createDiscountCode({
workspace,
discount,
code: finalCode,
shouldRetry: code ? false : true,
});
try {
return await prisma.discountCode.create({
data: {
id: createId({ prefix: "dcode_" }),
code: externalDiscountCode.code,
programId: discount.programId,
partnerId: partner.id,
linkId: link.id,
discountId: discount.id,
},
});
} catch (error) {
try {
await discountProvider.disableDiscountCode({
workspace,
code: externalDiscountCode.code,
});
} catch (rollbackError) {
console.error("Failed to rollback external discount code", {
code: externalDiscountCode.code,
rollbackError,
});
}
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === "P2002"
) {
throw new DubApiError({
code: "conflict",
message:
"This discount code is already in use, or this link already has a code. Please refresh and try again.",
});
}
throw error;
}
}