-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathroute.ts
More file actions
110 lines (96 loc) · 2.61 KB
/
Copy pathroute.ts
File metadata and controls
110 lines (96 loc) · 2.61 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
import { DubApiError } from "@/lib/api/errors";
import { withCron } from "@/lib/cron/with-cron";
import { createDiscountCode } from "@/lib/discounts/create-discount-code";
import { isNonRecoverableDiscountError } from "@/lib/discounts/discount-error";
import { prisma } from "@/lib/prisma";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
export const dynamic = "force-dynamic";
const inputSchema = z.object({
linkId: z
.string()
.describe("The ID of the link to create a discount code for."),
});
// POST /api/cron/discount-codes/create
export const POST = withCron(async ({ rawBody }) => {
const { linkId } = inputSchema.parse(JSON.parse(rawBody));
const link = await prisma.link.findUnique({
where: {
id: linkId,
},
select: {
id: true,
discountCode: true,
partnerGroupDefaultLinkId: true,
programEnrollment: {
select: {
discount: true,
partner: {
select: {
id: true,
name: true,
},
},
program: {
select: {
id: true,
},
},
},
},
project: {
select: {
id: true,
webhookEnabled: true,
stripeConnectId: true,
shopifyStoreId: true,
},
},
},
});
if (!link || !link.project) {
return logAndRespond(`Link ${linkId} not found. Skipping...`);
}
if (link.discountCode) {
return logAndRespond(
`Link ${linkId} already has a discount code. Skipping...`,
);
}
if (link.partnerGroupDefaultLinkId === null) {
return logAndRespond(`Link ${linkId} is not a default link. Skipping...`);
}
if (!link.programEnrollment) {
return logAndRespond(
`Link ${linkId} is not associated with a program enrollment. Skipping...`,
);
}
const {
project: workspace,
programEnrollment: { program, partner, discount },
} = link;
if (!discount) {
return logAndRespond(
`Partner ${partner.id} does not have a discount with program ${program.id}. Skipping...`,
);
}
try {
await createDiscountCode({
workspace,
partner,
link,
discount,
});
} catch (error) {
if (isNonRecoverableDiscountError(error)) {
return logAndRespond(error.message, { logLevel: "warn" });
}
if (
error instanceof DubApiError &&
(error.code === "conflict" || error.code === "bad_request")
) {
return logAndRespond(error.message, { logLevel: "warn" });
}
throw error;
}
return logAndRespond(`Discount code created for link ${linkId}.`);
});