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.

Add delete discount code API endpoint and refactor discount deletion logic

Kiran K237f139ad9a0
diff --git a/apps/web/app/(ee)/api/cron/discounts/delete-discount-code/route.ts b/apps/web/app/(ee)/api/cron/discounts/delete-discount-code/route.ts
new file mode 100644
index 0000000000..17356e51d8
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/discounts/delete-discount-code/route.ts
@@ -0,0 +1,75 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { disableStripeDiscountCode } from "@/lib/stripe/delete-stripe-discount-code";
+import { prisma } from "@dub/prisma";
+import { z } from "zod";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ discountCodeId: z.string(),
+});
+
+// POST /api/cron/discounts/delete-discount-code
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+ await verifyQstashSignature({ req, rawBody });
+
+ const { discountCodeId } = schema.parse(JSON.parse(rawBody));
+
+ // Find the discount code
+ const discountCode = await prisma.discountCode.findUnique({
+ where: {
+ id: discountCodeId,
+ },
+ select: {
+ code: true,
+ program: {
+ select: {
+ id: true,
+ workspace: {
+ select: {
+ stripeConnectId: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!discountCode) {
+ return logAndRespond(`Discount code ${discountCodeId} not found.`);
+ }
+
+ const program = discountCode.program;
+ const workspace = program.workspace;
+
+ if (!workspace.stripeConnectId) {
+ return logAndRespond(
+ `stripeConnectId not found for the program ${program.id}.`,
+ {
+ status: 400,
+ logLevel: "error",
+ },
+ );
+ }
+
+ // Disable the discount code on Stripe
+ await disableStripeDiscountCode({
+ stripeConnectId: workspace.stripeConnectId,
+ code: discountCode.code,
+ });
+
+ await prisma.discountCode.delete({
+ where: {
+ id: discountCodeId,
+ },
+ });
+
+ return logAndRespond(`Discount code ${discountCodeId} deleted.`);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/(ee)/api/cron/discounts/queue-coupon-code-delete-jobs/route.ts b/apps/web/app/(ee)/api/cron/discounts/queue-coupon-code-delete-jobs/route.ts
deleted file mode 100644
index f63014754c..0000000000
--- a/apps/web/app/(ee)/api/cron/discounts/queue-coupon-code-delete-jobs/route.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { enqueueCouponCodeDeleteJobs } from "@/lib/api/discounts/queue-discount-code-deletion";
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { qstash } from "@/lib/cron";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";
-import { z } from "zod";
-import { logAndRespond } from "../../utils";
-
-export const dynamic = "force-dynamic";
-
-const PAGE_SIZE = 100;
-const MAX_BATCH = 10;
-
-const schema = z.object({
- groupId: z.string(),
- cursor: z.string().optional(),
-});
-
-// POST /api/cron/discounts/enqueue-coupon-code-delete-jobs
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- let { groupId, cursor } = schema.parse(JSON.parse(rawBody));
-
- // Find the group
- const group = await prisma.partnerGroup.findUnique({
- where: {
- id: groupId,
- },
- });
-
- if (!group) {
- return logAndRespond(`Group ${groupId} not found.`, {
- logLevel: "error",
- });
- }
-
- let hasMore = true;
- let processedBatches = 0;
-
- while (processedBatches < MAX_BATCH) {
- // Find program enrollments for the group
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- groupId: group.id,
- ...(cursor && {
- id: {
- gt: cursor,
- },
- }),
- },
- select: {
- id: true,
- links: {
- select: {
- id: true,
- couponCode: true,
- projectId: true,
- },
- },
- },
- take: PAGE_SIZE,
- orderBy: {
- id: "asc",
- },
- });
-
- if (programEnrollments.length === 0) {
- hasMore = false;
- break;
- }
-
- // Find links with a coupon code
- const links = programEnrollments.flatMap(({ links }) =>
- links.filter(({ couponCode }) => couponCode),
- );
-
- // Enqueue the coupon deletion job for each link
- if (links.length > 0) {
- const linkChunks = chunk(links, 100);
-
- for (const linkChunk of linkChunks) {
- await enqueueCouponCodeDeleteJobs(linkChunk);
- await new Promise((resolve) => setTimeout(resolve, 2000));
- }
- }
-
- cursor = programEnrollments[programEnrollments.length - 1].id;
- processedBatches++;
- }
-
- if (hasMore) {
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/enqueue-coupon-code-delete-jobs`,
- body: {
- groupId,
- cursor,
- },
- });
- }
-
- return new Response("Enqueued coupon deletion job for the links.");
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
diff --git a/apps/web/app/(ee)/api/cron/links/delete-coupon-code/route.ts b/apps/web/app/(ee)/api/cron/links/delete-coupon-code/route.ts
deleted file mode 100644
index a75de5b646..0000000000
--- a/apps/web/app/(ee)/api/cron/links/delete-coupon-code/route.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { disableStripePromotionCode } from "@/lib/stripe/delete-stripe-discount-code";
-import { prisma } from "@dub/prisma";
-import { z } from "zod";
-import { logAndRespond } from "../../utils";
-
-export const dynamic = "force-dynamic";
-
-const schema = z.object({
- linkId: z.string(),
- couponCode: z.string(),
- workspaceId: z.string(),
-});
-
-// POST /api/cron/links/delete-coupon-code
-export async function POST(req: Request) {
- let payload: z.infer<typeof schema> | undefined = undefined;
-
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- payload = schema.parse(JSON.parse(rawBody));
- } catch (error) {
- return logAndRespond(error.message, {
- logLevel: "error",
- });
- }
-
- const { linkId, couponCode, workspaceId } = payload;
-
- // Find the workspace
- const workspace = await prisma.project.findUnique({
- where: {
- id: workspaceId,
- },
- select: {
- id: true,
- stripeConnectId: true,
- },
- });
-
- if (!workspace) {
- return logAndRespond(
- `Workspace with id ${workspaceId} not found. Skipping...`,
- {
- logLevel: "error",
- },
- );
- }
-
- try {
- const updatedCouponCode = await disableStripePromotionCode({
- workspace: {
- id: workspace.id,
- stripeConnectId: workspace.stripeConnectId,
- },
- code: couponCode
- });
-
- if (updatedCouponCode) {
- const link = await prisma.link.findUnique({
- where: {
- id: linkId,
- },
- select: {
- couponCode: true,
- },
- });
-
- // Link won't exists if it's deleted
- if (link && link.couponCode === couponCode) {
- await prisma.link.update({
- where: {
- id: linkId,
- },
- data: {
- couponCode: null,
- },
- });
- }
- }
- } catch (error) {
- return logAndRespond(error.message, {
- status: 400,
- });
- }
-
- return logAndRespond(`Finished executing the job for the link ${linkId}.`);
-}
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index 13f2c3cc03..a95873ce72 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -1,6 +1,7 @@
"use server";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { queueDiscountCodeDeletionJobs } from "@/lib/api/discounts/queue-discount-code-deletion";
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { qstash } from "@/lib/cron";
@@ -66,12 +67,7 @@ export const deleteDiscountAction = authActionClient
}),
discount.couponCodeTrackingEnabledAt &&
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/enqueue-coupon-code-delete-jobs`,
- body: {
- groupId: group.id,
- },
- }),
+ queueDiscountCodeDeletionJobs(discountId),
recordAuditLog({
workspaceId: workspace.id,
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index fc61acbf9b..acd3fc3790 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -1,6 +1,7 @@
"use server";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { queueDiscountCodeDeletionJobs } from "@/lib/api/discounts/queue-discount-code-deletion";
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { qstash } from "@/lib/cron";
@@ -61,14 +62,7 @@ export const updateDiscountAction = authActionClient
},
}),
- trackingDisabled &&
- partnerGroup &&
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/enqueue-coupon-code-delete-jobs`,
- body: {
- groupId: partnerGroup.id,
- },
- }),
+ trackingDisabled && queueDiscountCodeDeletionJobs(discountId),
recordAuditLog({
workspaceId: workspace.id,
@@ -108,50 +102,3 @@ function detectDiscountChanges(
trackingDisabled,
};
}
-
-async function queueDiscountCodeDeletionJobs(discountId: string) {
- const queue = qstash.queue({
- queueName: "discount-code-deletion",
- });
-
- await queue.upsert({
- parallelism: 10,
- });
-
- // take 100 and do pagination
-
- const pageSize = 100
- let hasMore = true
- let cursor = null
-
- while (hasMore) {
- const discountCode = await prisma.discountCode.findMany({
- where: {
- discountId,
- },
- select: {
- id: true,
- },
- take: pageSize,
- orderBy: {
- createdAt: "asc",
- },
- ...(cursor ? {
- cursor: {
- id: cursor,
- },
- }),
- });
- }
-
-
-
-
- // const response = await queue.enqueueJSON({
- // url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/delete-discount-code`,
- // method: "POST",
- // body: {
- // discountCodeId =
- // },
- // });
-}
diff --git a/apps/web/lib/api/discounts/queue-discount-code-deletion.ts b/apps/web/lib/api/discounts/queue-discount-code-deletion.ts
index f743fa0c1a..803e723a66 100644
--- a/apps/web/lib/api/discounts/queue-discount-code-deletion.ts
+++ b/apps/web/lib/api/discounts/queue-discount-code-deletion.ts
@@ -1,30 +1,55 @@
import { qstash } from "@/lib/cron";
-import { APP_DOMAIN_WITH_NGROK, isRejected } from "@dub/utils";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
const queue = qstash.queue({
queueName: "discount-code-deletion",
});
-
-interface QueueDiscountCodeDeletionInput {
- code: string;
-
-}
-
-export async function queueDiscountCodeDeletion() {
+export async function queueDiscountCodeDeletionJobs(discountId: string) {
await queue.upsert({
parallelism: 10,
});
- const response = await Promise.allSettled(
- codes.map((code) =>
- queue.enqueueJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete-coupon-code`,
- method: "POST",
- body: {
- code,
- },
- }),
- ),
- );
+ let cursor: undefined | string = undefined;
+
+ while (true) {
+ const discountCodes = await prisma.discountCode.findMany({
+ where: {
+ discountId,
+ },
+ select: {
+ id: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ cursor: {
+ id: cursor,
+ },
+ take: 100,
+ });
+
+ if (discountCodes.length === 0) {
+ break;
+ }
+
+ console.log("discountCodes", discountCodes);
+
+ const response = await Promise.allSettled(
+ discountCodes.map(({ id }) =>
+ queue.enqueueJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/delete-discount-code`,
+ method: "POST",
+ body: {
+ discountCodeId: id,
+ },
+ }),
+ ),
+ );
+
+ console.log("response", response);
+
+ cursor = discountCodes[discountCodes.length - 1].id;
+ }
}
diff --git a/apps/web/lib/stripe/delete-stripe-discount-code.ts b/apps/web/lib/stripe/delete-stripe-discount-code.ts
index a47e5c97ad..0f195d88ae 100644
--- a/apps/web/lib/stripe/delete-stripe-discount-code.ts
+++ b/apps/web/lib/stripe/delete-stripe-discount-code.ts
@@ -1,20 +1,19 @@
import { stripeAppClient } from ".";
-import { WorkspaceProps } from "../types";
const stripe = stripeAppClient({
...(process.env.VERCEL_ENV && { livemode: true }),
});
-export async function disableStripePromotionCode({
- workspace,
+export async function disableStripeDiscountCode({
+ stripeConnectId,
code,
}: {
- workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;
+ stripeConnectId: string;
code: string;
}) {
- if (!workspace.stripeConnectId) {
+ if (!stripeConnectId) {
console.error(
- `stripeConnectId not found for the workspace ${workspace.id}. Skipping...`,
+ `stripeConnectId is required to disable a Stripe discount code.`,
);
return;
}
@@ -25,13 +24,13 @@ export async function disableStripePromotionCode({
limit: 1,
},
{
- stripeAccount: workspace.stripeConnectId,
+ stripeAccount: stripeConnectId,
},
);
if (promotionCodes.data.length === 0) {
console.error(
- `Stripe promotion code ${code} not found (stripeConnectId=${workspace.stripeConnectId}).`,
+ `Stripe promotion code ${code} not found (stripeConnectId=${stripeConnectId}).`,
);
return;
}
@@ -44,12 +43,12 @@ export async function disableStripePromotionCode({
active: false,
},
{
- stripeAccount: workspace.stripeConnectId,
+ stripeAccount: stripeConnectId,
},
);
console.info(
- `Disabled Stripe promotion code ${promotionCode.code} (id=${promotionCode.id}, stripeConnectId=${workspace.stripeConnectId}).`,
+ `Disabled Stripe promotion code ${promotionCode.code} (id=${promotionCode.id}, stripeConnectId=${stripeConnectId}).`,
);
return promotionCode;