Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

fix discount code creation

Kiran K098d7db94a56
diff --git a/apps/web/app/(ee)/api/discount-codes/route.ts b/apps/web/app/(ee)/api/discount-codes/route.ts
index c76d55dd97..4a1ead6a10 100644
--- a/apps/web/app/(ee)/api/discount-codes/route.ts
+++ b/apps/web/app/(ee)/api/discount-codes/route.ts
@@ -110,39 +110,30 @@ export const POST = withWorkspace(
});
}
- // Create discount code on Stripe
- const stripeDiscountCode = await createStripeDiscountCode({
- workspace: {
- id: workspace.id,
- stripeConnectId: workspace.stripeConnectId,
- },
- discount: {
- id: discount.id,
- couponId: discount.couponId,
- },
- code,
- });
+ try {
+ const stripeDiscountCode = await createStripeDiscountCode({
+ workspace,
+ discount,
+ code,
+ });
+
+ const discountCode = await prisma.discountCode.create({
+ data: {
+ code: stripeDiscountCode?.code,
+ programId,
+ partnerId,
+ linkId,
+ discountId: discount.id,
+ },
+ });
- if (!stripeDiscountCode) {
+ return NextResponse.json(DiscountCodeSchema.parse(discountCode));
+ } catch (error) {
throw new DubApiError({
code: "bad_request",
- message: "Failed to create discount code on Stripe.",
+ message: error.message,
});
}
-
- const discountCode = await prisma.discountCode.create({
- data: {
- code,
- programId,
- partnerId,
- linkId,
- discountId: discount.id,
- },
- });
-
- const response = DiscountCodeSchema.parse(discountCode);
-
- return NextResponse.json(response);
},
{
requiredPlan: [
diff --git a/apps/web/lib/stripe/create-stripe-discount-code.ts b/apps/web/lib/stripe/create-stripe-discount-code.ts
index 4ce3ac8202..d66a2af1af 100644
--- a/apps/web/lib/stripe/create-stripe-discount-code.ts
+++ b/apps/web/lib/stripe/create-stripe-discount-code.ts
@@ -1,3 +1,4 @@
+import { nanoid } from "@dub/utils";
import { stripeAppClient } from ".";
import { DiscountProps, WorkspaceProps } from "../types";
@@ -5,36 +6,84 @@ const stripe = stripeAppClient({
...(process.env.VERCEL_ENV && { livemode: true }),
});
+const MAX_ATTEMPTS = 3;
+
export async function createStripeDiscountCode({
workspace,
discount,
code,
}: {
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;
- discount: Pick<DiscountProps, "id" | "couponId">;
+ discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;
code: string;
}) {
if (!workspace.stripeConnectId) {
- console.error(
- `stripeConnectId not found for the workspace ${workspace.id}. Stripe promotion code creation skipped.`,
+ throw new Error(
+ `stripeConnectId not found for workspace ${workspace.id}. Stripe promotion code creation skipped.`,
);
- return;
}
if (!discount.couponId) {
- console.error(
- `couponId not found for the discount ${discount.id}. Stripe promotion code creation skipped.`,
+ throw new Error(
+ `couponId not found for discount ${discount.id}. Stripe promotion code creation skipped.`,
);
- return;
}
- return await stripe.promotionCodes.create(
- {
- coupon: discount.couponId,
- code: code.toUpperCase(),
- },
- {
- stripeAccount: workspace.stripeConnectId,
- },
- );
-}
\ No newline at end of file
+ let attempt = 0;
+ let currentCode = code;
+
+ while (attempt < MAX_ATTEMPTS) {
+ try {
+ return await stripe.promotionCodes.create(
+ {
+ coupon: discount.couponId,
+ code: currentCode.toUpperCase(),
+ },
+ {
+ stripeAccount: workspace.stripeConnectId,
+ },
+ );
+ } catch (error: any) {
+ const errorMessage = error.raw?.message || error.message;
+ const isDuplicateError = errorMessage?.includes("already exists");
+
+ if (!isDuplicateError) {
+ throw error;
+ }
+
+ attempt++;
+
+ if (attempt >= MAX_ATTEMPTS) {
+ throw error;
+ }
+
+ const newCode = constructDiscountCode({
+ code: currentCode,
+ discount,
+ });
+
+ console.warn(
+ `Discount code "${currentCode}" already exists. Retrying with "${newCode}" (attempt ${attempt}/${MAX_ATTEMPTS}).`,
+ );
+
+ currentCode = newCode;
+ }
+ }
+}
+
+export function constructDiscountCode({
+ code,
+ discount,
+}: {
+ code: string;
+ discount: Pick<DiscountProps, "amount" | "type">;
+}) {
+ const amount =
+ discount.type === "percentage" ? discount.amount : discount.amount / 100;
+
+ if (!code.endsWith(amount.toString())) {
+ return `${code}${amount}`;
+ }
+
+ return `${code}${nanoid(4)}`;
+}