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.

Refactor Stripe promotion code and coupon APIs

Kiran Kebf3178c1296
diff --git a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts
index 26418a148c..1cc060e7f1 100644
--- a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts
+++ b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts
@@ -68,6 +68,7 @@ export async function POST(req: Request) {
id: program.workspaceId,
},
select: {
+ id: true,
stripeConnectId: true,
},
});
@@ -137,9 +138,20 @@ export async function POST(req: Request) {
const results = await Promise.allSettled(
linksChunk.map((link) =>
createStripePromotionCode({
- link,
- coupon: discount,
- stripeConnectId: workspace.stripeConnectId,
+ workspace: {
+ id: workspace.id,
+ stripeConnectId: workspace.stripeConnectId,
+ },
+ link: {
+ id: link.id,
+ key: link.key,
+ },
+ discount: {
+ id: discount.id,
+ couponId: discount.couponId,
+ amount: discount.amount,
+ type: discount.type,
+ },
}),
),
);
diff --git a/apps/web/app/(ee)/api/cron/links/delete-promotion-codes/route.ts b/apps/web/app/(ee)/api/cron/links/delete-promotion-codes/route.ts
index 90b23b3c50..e5825fd9a4 100644
--- a/apps/web/app/(ee)/api/cron/links/delete-promotion-codes/route.ts
+++ b/apps/web/app/(ee)/api/cron/links/delete-promotion-codes/route.ts
@@ -30,8 +30,7 @@ export async function POST(req: Request) {
});
if (!group) {
- return logAndRespond({
- message: `Partner group ${groupId} not found.`,
+ return logAndRespond(`Partner group ${groupId} not found.`, {
logLevel: "error",
});
}
@@ -42,22 +41,27 @@ export async function POST(req: Request) {
id: group.program.workspaceId,
},
select: {
+ id: true,
stripeConnectId: true,
},
});
if (!workspace) {
- return logAndRespond({
- message: `Workspace ${group.program.workspaceId} not found.`,
- logLevel: "error",
- });
+ return logAndRespond(
+ `Workspace ${group.program.workspaceId} not found.`,
+ {
+ logLevel: "error",
+ },
+ );
}
if (!workspace.stripeConnectId) {
- return logAndRespond({
- message: `Workspace ${group.program.workspaceId} does not have a stripeConnectId set.`,
- logLevel: "error",
- });
+ return logAndRespond(
+ `Workspace ${group.program.workspaceId} does not have a stripeConnectId set.`,
+ {
+ logLevel: "error",
+ },
+ );
}
let page = 0;
@@ -112,8 +116,11 @@ export async function POST(req: Request) {
const results = await Promise.allSettled(
linksChunk.map((link) =>
disableStripePromotionCode({
+ workspace: {
+ id: workspace.id,
+ stripeConnectId: workspace.stripeConnectId,
+ },
promotionCode: link.couponCode,
- stripeConnectId: workspace.stripeConnectId,
}),
),
);
@@ -145,9 +152,7 @@ export async function POST(req: Request) {
page++;
}
- return logAndRespond({
- message: `Promotion codes deleted for group ${groupId}.`,
- });
+ return logAndRespond(`Promotion codes deleted for group ${groupId}.`);
} catch (error) {
console.log(error);
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 7abc1776ea..f2beab8f04 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -50,15 +50,15 @@ export const createDiscountAction = authActionClient
}
const stripeCoupon = await createStripeCoupon({
- coupon: {
- amount,
- type,
- maxDuration: maxDuration ?? null,
- },
workspace: {
id: workspace.id,
stripeConnectId: workspace.stripeConnectId,
},
+ discount: {
+ amount,
+ type,
+ maxDuration: maxDuration ?? null,
+ },
});
if (!stripeCoupon) {
diff --git a/apps/web/lib/api/links/bulk-delete-links.ts b/apps/web/lib/api/links/bulk-delete-links.ts
index 33ba76e670..efe2142872 100644
--- a/apps/web/lib/api/links/bulk-delete-links.ts
+++ b/apps/web/lib/api/links/bulk-delete-links.ts
@@ -50,8 +50,11 @@ export async function bulkDeleteLinks({
.filter((link) => link.couponCode)
.map((link) =>
disableStripePromotionCode({
+ workspace: {
+ id: workspace.id,
+ stripeConnectId: workspace.stripeConnectId,
+ },
promotionCode: link.couponCode,
- stripeConnectId: workspace.stripeConnectId,
}),
)
: [],
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
index 2cd0b4c89d..044b08efad 100644
--- a/apps/web/lib/api/links/create-link.ts
+++ b/apps/web/lib/api/links/create-link.ts
@@ -28,7 +28,7 @@ type CreateLinkProps = ProcessedLinkProps & {
workspace?: Pick<WorkspaceProps, "id" | "stripeConnectId">;
discount?: Pick<
DiscountProps,
- "couponId" | "couponCodeTrackingEnabledAt" | "amount" | "type"
+ "id" | "couponId" | "couponCodeTrackingEnabledAt" | "amount" | "type"
> | null;
skipCouponCreation?: boolean; // Skip Stripe promotion code creation for the link
};
@@ -191,6 +191,7 @@ export async function createLink(link: CreateLinkProps) {
select: {
discount: {
select: {
+ id: true,
couponId: true,
couponCodeTrackingEnabledAt: true,
amount: true,
@@ -262,12 +263,25 @@ export async function createLink(link: CreateLinkProps) {
// Create promotion code for the link
!skipCouponCreation &&
- link.projectId &&
+ link &&
discount?.couponCodeTrackingEnabledAt &&
+ workspace &&
+ link.id &&
createStripePromotionCode({
- link: response,
- coupon: discount,
- stripeConnectId: workspace?.stripeConnectId!,
+ workspace: {
+ id: workspace.id,
+ stripeConnectId: workspace.stripeConnectId,
+ },
+ link: {
+ id: link.id,
+ key: link.key,
+ },
+ discount: {
+ id: discount.id,
+ couponId: discount.couponId,
+ amount: discount.amount,
+ type: discount.type,
+ },
}),
]);
})(),
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 59fb557d7e..7cc3e75485 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -17,12 +17,15 @@ export async function deleteLink(linkId: string) {
...includeTags,
project: {
select: {
+ id: true,
stripeConnectId: true,
},
},
},
});
+ const { project: workspace } = link;
+
waitUntil(
Promise.allSettled([
// if there's a valid image and it has the same link ID, delete it
@@ -49,11 +52,13 @@ export async function deleteLink(linkId: string) {
},
}),
- link.project &&
- link.couponCode &&
+ workspace &&
disableStripePromotionCode({
+ workspace: {
+ id: workspace.id,
+ stripeConnectId: workspace.stripeConnectId,
+ },
promotionCode: link.couponCode,
- stripeConnectId: link.project.stripeConnectId,
}),
]),
);
diff --git a/apps/web/lib/stripe/create-stripe-coupon.ts b/apps/web/lib/stripe/create-stripe-coupon.ts
index 4b28b283dc..015f0eb34e 100644
--- a/apps/web/lib/stripe/create-stripe-coupon.ts
+++ b/apps/web/lib/stripe/create-stripe-coupon.ts
@@ -8,11 +8,11 @@ const stripe = stripeAppClient({
// Create a coupon on Stripe for connected accounts
export async function createStripeCoupon({
- coupon,
workspace,
+ discount,
}: {
- coupon: Pick<Discount, "amount" | "type" | "maxDuration">;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;
+ discount: Pick<Discount, "amount" | "type" | "maxDuration">;
}) {
if (!workspace.stripeConnectId) {
console.error(
@@ -24,16 +24,16 @@ export async function createStripeCoupon({
let duration: "once" | "repeating" | "forever" = "once";
let durationInMonths: number | undefined = undefined;
- if (coupon.maxDuration === null) {
+ if (discount.maxDuration === null) {
duration = "forever";
- } else if (coupon.maxDuration === 0) {
+ } else if (discount.maxDuration === 0) {
duration = "once";
} else {
duration = "repeating";
}
- if (duration === "repeating" && coupon.maxDuration) {
- durationInMonths = coupon.maxDuration;
+ if (duration === "repeating" && discount.maxDuration) {
+ durationInMonths = discount.maxDuration;
}
try {
@@ -44,9 +44,9 @@ export async function createStripeCoupon({
...(duration === "repeating" && {
duration_in_months: durationInMonths,
}),
- ...(coupon.type === "percentage"
- ? { percent_off: coupon.amount }
- : { amount_off: coupon.amount }),
+ ...(discount.type === "percentage"
+ ? { percent_off: discount.amount }
+ : { amount_off: discount.amount }),
},
{
stripeAccount: workspace.stripeConnectId,
@@ -61,7 +61,7 @@ export async function createStripeCoupon({
} catch (error) {
console.log(`Failed create Stripe coupon for workspace ${workspace.id}.`, {
error,
- coupon,
+ discount,
});
return null;
diff --git a/apps/web/lib/stripe/create-stripe-promotion-code.ts b/apps/web/lib/stripe/create-stripe-promotion-code.ts
index db55e96bf8..aeb7dd2cb2 100644
--- a/apps/web/lib/stripe/create-stripe-promotion-code.ts
+++ b/apps/web/lib/stripe/create-stripe-promotion-code.ts
@@ -1,32 +1,32 @@
import { prisma } from "@dub/prisma";
import { stripeAppClient } from ".";
-import { DiscountProps, LinkProps } from "../types";
+import { DiscountProps, LinkProps, WorkspaceProps } from "../types";
const stripe = stripeAppClient({
...(process.env.VERCEL_ENV && { livemode: true }),
});
-const MAX_RETRIES = 2;
+const MAX_RETRIES = 3;
export async function createStripePromotionCode({
+ workspace,
+ discount,
link,
- coupon,
- stripeConnectId,
}: {
+ workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;
+ discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;
link: Pick<LinkProps, "id" | "key">;
- coupon: Pick<DiscountProps, "couponId" | "amount" | "type">;
- stripeConnectId: string | null;
}) {
- if (!coupon.couponId) {
+ if (!workspace.stripeConnectId) {
console.error(
- "couponId not found for the discount. Stripe promotion code creation skipped.",
+ `stripeConnectId not found for the workspace ${workspace.id}. Stripe promotion code creation skipped.`,
);
return;
}
- if (!stripeConnectId) {
+ if (!discount.couponId) {
console.error(
- "stripeConnectId not found for the workspace. Stripe promotion code creation skipped.",
+ `couponId not found for the discount ${discount.id}. Stripe promotion code creation skipped.`,
);
return;
}
@@ -35,7 +35,7 @@ export async function createStripePromotionCode({
let couponCode: string | undefined;
const amount =
- coupon.type === "percentage" ? coupon.amount : coupon.amount / 100;
+ discount.type === "percentage" ? discount.amount : discount.amount / 100;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
@@ -43,11 +43,11 @@ export async function createStripePromotionCode({
const promotionCode = await stripe.promotionCodes.create(
{
- coupon: coupon.couponId,
+ coupon: discount.couponId,
code: couponCode.toUpperCase(),
},
{
- stripeAccount: stripeConnectId,
+ stripeAccount: workspace.stripeConnectId,
},
);
@@ -60,19 +60,23 @@ export async function createStripePromotionCode({
couponCode: promotionCode.code,
},
});
+
+ console.info(
+ `Promotion code ${promotionCode.code} created for link ${link.id} for the discount ${discount.id}.`,
+ );
}
return promotionCode;
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
- console.error(lastError);
-
const isDuplicateError =
error instanceof Error &&
error.message.includes("An active promotion code with `code:") &&
error.message.includes("already exists");
+ console.error(error.message);
+
if (isDuplicateError) {
if (attempt === MAX_RETRIES) {
throw lastError;
diff --git a/apps/web/lib/stripe/disable-stripe-promotion-code.ts b/apps/web/lib/stripe/disable-stripe-promotion-code.ts
index a906807a60..861c0b5116 100644
--- a/apps/web/lib/stripe/disable-stripe-promotion-code.ts
+++ b/apps/web/lib/stripe/disable-stripe-promotion-code.ts
@@ -1,17 +1,25 @@
import { stripeAppClient } from ".";
+import { WorkspaceProps } from "../types";
const stripe = stripeAppClient({
...(process.env.VERCEL_ENV && { livemode: true }),
});
export async function disableStripePromotionCode({
+ workspace,
promotionCode,
- stripeConnectId,
}: {
+ workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;
promotionCode: string | null;
- stripeConnectId: string | null;
}) {
- if (!promotionCode || !stripeConnectId) {
+ if (!promotionCode) {
+ return;
+ }
+
+ if (!workspace.stripeConnectId) {
+ console.error(
+ `stripeConnectId not found for the workspace ${workspace.id}. Skipping Stripe coupon creation.`,
+ );
return;
}
@@ -21,13 +29,13 @@ export async function disableStripePromotionCode({
limit: 1,
},
{
- stripeAccount: stripeConnectId,
+ stripeAccount: workspace.stripeConnectId,
},
);
if (promotionCodes.data.length === 0) {
console.error(
- `Stripe promotion code ${promotionCode} not found in the connected account ${stripeConnectId}.`,
+ `Stripe promotion code ${promotionCode} not found in the connected account ${workspace.stripeConnectId}.`,
);
return;
}
@@ -41,18 +49,18 @@ export async function disableStripePromotionCode({
active: false,
},
{
- stripeAccount: stripeConnectId,
+ stripeAccount: workspace.stripeConnectId,
},
);
console.info(
- `Stripe promotion code ${promotionCode} in the connected account ${stripeConnectId} has been disabled.`,
+ `Stripe promotion code ${promotionCode} in the connected account ${workspace.stripeConnectId} has been disabled.`,
);
return promotionCode;
} catch (error) {
console.error(
- `Failed to disable Stripe promotion code ${promotionCode} in the connected account ${stripeConnectId}.`,
+ `Failed to disable Stripe promotion code ${promotionCode} in the connected account ${workspace.stripeConnectId}.`,
error,
);