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.

improve the cron job

Kiran Kd4d515ad1120
diff --git a/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.ts b/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.ts
index 0b6508a3c5..5f15bda44d 100644
--- a/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.ts
+++ b/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.ts
@@ -100,7 +100,10 @@ export async function POST(req: Request) {
const linkChunks = chunk(links, 100);
for (const linkChunk of linkChunks) {
- await dispatchPromotionCodeCreationJob(linkChunk);
+ await dispatchPromotionCodeCreationJob({
+ links: linkChunk,
+ });
+
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
diff --git a/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.ts b/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.ts
index 44cd40f7b6..a6dce71bba 100644
--- a/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.ts
+++ b/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.ts
@@ -1,5 +1,7 @@
+import { dispatchPromotionCodeCreationJob } from "@/lib/api/discounts/promotion-code-creation-job";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { createStripePromotionCode } from "@/lib/stripe/create-stripe-promotion-code";
+import { DiscountProps } from "@/lib/types";
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { z } from "zod";
@@ -15,7 +17,6 @@ const schema = z.object({
// POST /api/cron/links/create-promotion-code
export async function POST(req: Request) {
let payload: z.infer<typeof schema> | undefined = undefined;
- const allHeaders = req.headers;
try {
const rawBody = await req.text();
@@ -87,13 +88,9 @@ export async function POST(req: Request) {
});
}
- const retried = Number(allHeaders.get("upstash-retried"));
- const amount =
- discount.type === "percentage" ? discount.amount : discount.amount / 100;
-
try {
// Create the promotion code using Stripe API
- const promotionCode = await createStripePromotionCode({
+ const stripePromotionCode = await createStripePromotionCode({
workspace: {
id: workspace.id,
stripeConnectId: workspace.stripeConnectId,
@@ -101,29 +98,71 @@ export async function POST(req: Request) {
discount: {
id: discount.id,
couponId: discount.couponId,
- amount: discount.amount,
- type: discount.type,
},
- code: retried === 0 ? `${code}${amount}` : `${code}${nanoid(4)}`,
+ code,
});
- if (promotionCode?.code) {
+ // Update the link with the promotion code
+ if (stripePromotionCode?.code) {
console.log(
- `Stripe promotion code ${promotionCode.code} created for the link ${linkId}.`,
+ `Stripe promotion code ${stripePromotionCode.code} created for the link ${link.id}.`,
);
await prisma.link.update({
where: {
- id: linkId,
+ id: link.id,
},
data: {
- couponCode: promotionCode.code,
+ couponCode: stripePromotionCode.code,
},
});
}
} catch (error) {
- return logAndRespond(error.raw?.message, { status: 400 });
+ if (error?.type === "StripeInvalidRequestError") {
+ const errorMessage = error.raw?.message || error.message;
+ const isDuplicateError = errorMessage?.includes("already exists");
+
+ if (isDuplicateError) {
+ const newCode = constructPromotionCode({
+ code,
+ discount: {
+ amount: discount.amount,
+ type: discount.type,
+ },
+ });
+
+ await dispatchPromotionCodeCreationJob({
+ link: {
+ id: link.id,
+ key: newCode,
+ },
+ });
+
+ return logAndRespond(`${errorMessage} Retrying...`, {
+ logLevel: "info",
+ });
+ }
+ }
+
+ return logAndRespond(error.raw?.message || error.message, { status: 400 });
}
return logAndRespond(`Finished executing the job for the link ${linkId}.`);
}
+
+function constructPromotionCode({
+ 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)}`;
+}
diff --git a/apps/web/lib/api/discounts/promotion-code-creation-job.ts b/apps/web/lib/api/discounts/promotion-code-creation-job.ts
index 6becc515d2..94fa637d3f 100644
--- a/apps/web/lib/api/discounts/promotion-code-creation-job.ts
+++ b/apps/web/lib/api/discounts/promotion-code-creation-job.ts
@@ -7,8 +7,12 @@ const queue = qstash.queue({
});
type DispatchPromotionCodeCreationJobInput =
- | Pick<Link, "id" | "key">
- | Pick<Link, "id" | "key">[];
+ | {
+ link: Pick<Link, "id" | "key">;
+ }
+ | {
+ links: Pick<Link, "id" | "key">[];
+ };
// Dispatch promotion code creation job for a link or multiple links
export async function dispatchPromotionCodeCreationJob(
@@ -18,7 +22,7 @@ export async function dispatchPromotionCodeCreationJob(
parallelism: 10,
});
- const finalLinks = Array.isArray(input) ? input : [input];
+ const finalLinks = "links" in input ? input.links : [input.link];
const response = await Promise.allSettled(
finalLinks.map((link) =>
diff --git a/apps/web/lib/stripe/create-stripe-promotion-code.ts b/apps/web/lib/stripe/create-stripe-promotion-code.ts
index 24c8387733..0b260f414b 100644
--- a/apps/web/lib/stripe/create-stripe-promotion-code.ts
+++ b/apps/web/lib/stripe/create-stripe-promotion-code.ts
@@ -11,7 +11,7 @@ export async function createStripePromotionCode({
code,
}: {
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;
- discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;
+ discount: Pick<DiscountProps, "id" | "couponId">;
code: string;
}) {
if (!workspace.stripeConnectId) {