-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathdiscount-provider-shopify.ts
More file actions
358 lines (317 loc) · 10.1 KB
/
Copy pathdiscount-provider-shopify.ts
File metadata and controls
358 lines (317 loc) · 10.1 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import { decryptOrPassthrough } from "@/lib/encryption";
import { prisma } from "@/lib/prisma";
import { SHOPIFY_INTEGRATION_ID, nanoid } from "@dub/utils";
import { Discount, Project } from "@prisma/client";
import {
ShopifyAdminGraphqlError,
shopifyAdminGraphql,
} from "../integrations/shopify/admin-graphql";
import { integrationCredentialsSchema } from "../integrations/shopify/schema";
import { DiscountProviderError } from "./discount-error";
interface ShopifyDiscountCodeBasicCreate {
codeDiscountNode: {
id: string;
codeDiscount: {
codes: { nodes: { code: string }[] };
};
} | null;
userErrors: {
field: string[] | null;
message: string;
code: string;
}[];
}
interface ShopifyDiscountCodeDelete {
deletedCodeDiscountId: string | null;
userErrors: {
field: string[] | null;
message: string;
code: string;
}[];
}
const MAX_ATTEMPTS = 3;
async function requireInstalledIntegration(
workspace: Pick<Project, "id" | "shopifyStoreId">,
) {
if (!workspace.shopifyStoreId) {
throw new DiscountProviderError(
"shopify",
"INTEGRATION_NOT_AVAILABLE",
"SHOPIFY_CONNECTION_REQUIRED: Your workspace isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create a discount.",
);
}
const installation = await prisma.installedIntegration.findFirst({
where: {
projectId: workspace.id,
integrationId: SHOPIFY_INTEGRATION_ID,
},
});
if (!installation) {
throw new DiscountProviderError(
"shopify",
"INTEGRATION_NOT_AVAILABLE",
"SHOPIFY_CONNECTION_REQUIRED: Your workspace isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create a discount.",
);
}
let credentials = integrationCredentialsSchema.parse(
installation.credentials || {},
);
if (!credentials?.scope?.includes("write_discounts")) {
throw new DiscountProviderError(
"shopify",
"PERMISSIONS_REQUIRED",
"SHOPIFY_APP_UPGRADE_REQUIRED: Your connected Shopify store doesn't have permission to create discount codes. Please reinstall or upgrade the Dub Shopify app.",
);
}
return {
...installation,
credentials: {
...credentials,
accessToken: credentials.accessToken
? decryptOrPassthrough(credentials.accessToken)
: credentials.accessToken,
},
};
}
function createShopifyDiscountProvider() {
const getCoupon = async () => {
throw new Error("Shopify does not this method.");
};
const createCoupon = async () => {
throw new Error("Shopify does not this method.");
};
const createDiscountCode = async ({
workspace,
discount,
code,
shouldRetry = true,
}: {
workspace: Pick<Project, "id" | "shopifyStoreId">;
discount: Pick<Discount, "id" | "amount" | "type" | "maxDuration">;
code: string;
shouldRetry?: boolean;
}) => {
const { credentials } = await requireInstalledIntegration(workspace);
// Map Dub's maxDuration (months) to Shopify's recurringCycleLimit (subscription billing cycles):
// - null -> 0 (Shopify: applies indefinitely / forever)
// - 0 -> 1 (one-time only -> only first subscription cycle)
// - N -> N (applies for N billing cycles)
const recurringCycleLimit =
discount.maxDuration === null
? 0
: discount.maxDuration === 0
? 1
: discount.maxDuration;
let attempt = 0;
let currentCode = code;
while (attempt < MAX_ATTEMPTS) {
try {
const data = await shopifyAdminGraphql<{
discountCodeBasicCreate: ShopifyDiscountCodeBasicCreate;
}>({
shopifyStoreId: workspace.shopifyStoreId!,
accessToken: credentials.accessToken!,
query: /* GraphQL */ `
mutation DiscountCodeBasicCreate(
$basicCodeDiscount: DiscountCodeBasicInput!
) {
discountCodeBasicCreate(basicCodeDiscount: $basicCodeDiscount) {
codeDiscountNode {
id
codeDiscount {
... on DiscountCodeBasic {
codes(first: 1) {
nodes {
code
}
}
}
}
}
userErrors {
field
message
code
}
}
}
`,
variables: {
basicCodeDiscount: {
title: `Dub Discount (${currentCode})`,
code: currentCode.toUpperCase(),
startsAt: new Date().toISOString(),
customerSelection: { all: true },
appliesOncePerCustomer: true,
recurringCycleLimit,
customerGets: {
items: { all: true },
appliesOnOneTimePurchase: true,
appliesOnSubscription: true,
value:
discount.type === "percentage"
? { percentage: discount.amount / 100 }
: {
discountAmount: {
amount: (discount.amount / 100).toFixed(2),
appliesOnEachItem: false,
},
},
},
},
},
});
const { codeDiscountNode, userErrors } = data.discountCodeBasicCreate;
if (userErrors.length > 0) {
throw new ShopifyAdminGraphqlError(
userErrors[0].code,
userErrors[0].message,
userErrors,
);
}
if (!codeDiscountNode) {
throw new ShopifyAdminGraphqlError(
"no_node_returned",
"Shopify did not return a discount code. Please try again.",
);
}
return {
code: codeDiscountNode.codeDiscount.codes.nodes[0].code,
};
} catch (error) {
const isDuplicate =
error instanceof ShopifyAdminGraphqlError &&
(error.code === "TAKEN" || error.code === "DUPLICATE");
if (isDuplicate) {
if (!shouldRetry) {
throw new DiscountProviderError(
"shopify",
"DISCOUNT_ALREADY_EXISTS",
`The discount code ${currentCode} is already in use. Please choose a different code.`,
);
}
attempt++;
if (attempt >= MAX_ATTEMPTS) {
throw new DiscountProviderError(
"shopify",
"DISCOUNT_ALREADY_EXISTS",
`The discount code ${currentCode} is already in use. Please choose a different code.`,
);
}
const newCode = `${currentCode}${nanoid(2)}`;
console.warn(
`Discount code "${currentCode}" already exists in Shopify. Retrying with "${newCode}" (attempt ${attempt}/${MAX_ATTEMPTS}).`,
);
currentCode = newCode;
continue;
}
if (error instanceof ShopifyAdminGraphqlError) {
if (error.code === "unauthorized") {
throw new DiscountProviderError(
"shopify",
"PERMISSIONS_REQUIRED",
error.message,
);
}
throw new DiscountProviderError(
"shopify",
"CREATE_FAILED",
error.code === "no_node_returned"
? "Shopify did not return a discount code. Please try again."
: error.code === "http_error" || error.code === "graphql_error"
? `Unable to create the discount code in Shopify. ${error.message}`
: error.message,
);
}
throw new DiscountProviderError(
"shopify",
"CREATE_FAILED",
error instanceof Error
? error.message
: "Failed to create Shopify discount code.",
);
}
}
throw new DiscountProviderError(
"shopify",
"CREATE_FAILED",
"Failed to create Shopify discount code.",
);
};
const disableDiscountCode = async ({
workspace,
code,
}: {
workspace: Pick<Project, "id" | "shopifyStoreId">;
code: string;
}) => {
const { credentials } = await requireInstalledIntegration(workspace);
const lookup = await shopifyAdminGraphql<{
codeDiscountNodeByCode: { id: string } | null;
}>({
shopifyStoreId: workspace.shopifyStoreId!,
accessToken: credentials.accessToken!,
query: /* GraphQL */ `
query CodeDiscountNodeByCode($code: String!) {
codeDiscountNodeByCode(code: $code) {
id
}
}
`,
variables: { code },
});
const id = lookup.codeDiscountNodeByCode?.id;
if (!id) {
console.error(
`Shopify discount code ${code} not found (shopifyStoreId=${workspace.shopifyStoreId!}).`,
);
return;
}
const data = await shopifyAdminGraphql<{
discountCodeDelete: ShopifyDiscountCodeDelete;
}>({
shopifyStoreId: workspace.shopifyStoreId!,
accessToken: credentials.accessToken!,
query: /* GraphQL */ `
mutation DiscountCodeDelete($id: ID!) {
discountCodeDelete(id: $id) {
deletedCodeDiscountId
userErrors {
field
message
code
}
}
}
`,
variables: { id },
});
const { userErrors } = data.discountCodeDelete;
if (userErrors.length > 0) {
throw new ShopifyAdminGraphqlError(
userErrors[0].code,
userErrors[0].message,
userErrors,
);
}
console.info(
`Deleted Shopify discount code ${code} (id=${id}, shopifyStoreId=${workspace.shopifyStoreId}).`,
);
return { id, code };
};
const assertDiscountIntegration = async ({
workspace,
}: {
workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;
}) => {
await requireInstalledIntegration(workspace);
};
return {
getCoupon,
createCoupon,
createDiscountCode,
disableDiscountCode,
assertDiscountIntegration,
};
}
export const shopifyDiscountProvider = createShopifyDiscountProvider();