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 discount code deletion logic and API usage

Kiran Kce0046288985
diff --git a/apps/web/lib/actions/partners/ban-partner.ts b/apps/web/lib/actions/partners/ban-partner.ts
index 838d644ada..9c654fca34 100644
--- a/apps/web/lib/actions/partners/ban-partner.ts
+++ b/apps/web/lib/actions/partners/ban-partner.ts
@@ -1,6 +1,7 @@
"use server";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { queueDiscountCodeDeletion } from "@/lib/api/discounts/queue-discount-code-deletion";
import { linkCache } from "@/lib/api/links/cache";
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
@@ -84,47 +85,48 @@ export const banPartnerAction = authActionClient
waitUntil(
(async () => {
- // sync total commissions
+ // Sync total commissions
await syncTotalCommissions({ partnerId, programId });
- const { program, partner } = programEnrollment;
-
- if (!partner.email) {
- console.error("Partner has no email address.");
- return;
- }
-
- const supportEmail = program.supportEmail || "[email protected]";
-
// Expire links from cache
const links = await prisma.link.findMany({
where,
select: {
domain: true,
key: true,
+ discountCode: true,
},
});
- await linkCache.expireMany(links);
+ const { program, partner } = programEnrollment;
await Promise.allSettled([
- sendEmail({
- subject: `You've been banned from the ${program.name} Partner Program`,
- to: partner.email,
- replyTo: supportEmail,
- react: PartnerBanned({
- partner: {
- name: partner.name,
- email: partner.email,
- },
- program: {
- name: program.name,
- slug: program.slug,
- },
- bannedReason: BAN_PARTNER_REASONS[parsedInput.reason],
+ linkCache.expireMany(links),
+
+ ...links.map((link) =>
+ queueDiscountCodeDeletion({
+ discountCodeId: link.discountCode?.id,
+ }),
+ ),
+
+ partner.email &&
+ sendEmail({
+ subject: `You've been banned from the ${program.name} Partner Program`,
+ to: partner.email,
+ replyTo: program.supportEmail || "[email protected]",
+ react: PartnerBanned({
+ partner: {
+ name: partner.name,
+ email: partner.email,
+ },
+ program: {
+ name: program.name,
+ slug: program.slug,
+ },
+ bannedReason: BAN_PARTNER_REASONS[parsedInput.reason],
+ }),
+ variant: "notifications",
}),
- variant: "notifications",
- }),
recordAuditLog({
workspaceId: workspace.id,
diff --git a/apps/web/lib/actions/partners/bulk-ban-partners.ts b/apps/web/lib/actions/partners/bulk-ban-partners.ts
index 956f771e37..c22f300cc9 100644
--- a/apps/web/lib/actions/partners/bulk-ban-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-ban-partners.ts
@@ -1,6 +1,7 @@
"use server";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { queueDiscountCodeDeletion } from "@/lib/api/discounts/queue-discount-code-deletion";
import { linkCache } from "@/lib/api/links/cache";
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
@@ -9,7 +10,6 @@ import {
bulkBanPartnersSchema,
} from "@/lib/zod/schemas/partners";
import { sendBatchEmail } from "@dub/email";
-import { resend } from "@dub/email/resend";
import PartnerBanned from "@dub/email/templates/partner-banned";
import { prisma } from "@dub/prisma";
import { ProgramEnrollmentStatus } from "@prisma/client";
@@ -47,6 +47,7 @@ export const bulkBanPartnersAction = authActionClient
select: {
domain: true,
key: true,
+ discountCode: true,
},
},
},
@@ -122,28 +123,37 @@ export const bulkBanPartnersAction = authActionClient
),
);
- // Expire links from cache
- await linkCache.expireMany(
- programEnrollments.flatMap(({ links }) => links),
- );
+ const links = programEnrollments.flatMap(({ links }) => links);
- // Record audit log for each partner
- await recordAuditLog(
- programEnrollments.map(({ partner }) => ({
- workspaceId: workspace.id,
- programId,
- action: "partner.banned",
- description: `Partner ${partner.id} banned`,
- actor: user,
- targets: [
- {
- type: "partner",
- id: partner.id,
- metadata: partner,
- },
- ],
- })),
- );
+ await Promise.allSettled([
+ // Expire links from cache
+ linkCache.expireMany(links),
+
+ // Queue discount code deletions
+ ...links.map((link) =>
+ queueDiscountCodeDeletion({
+ discountCodeId: link.discountCode?.id,
+ }),
+ ),
+
+ // Record audit log for each partner
+ recordAuditLog(
+ programEnrollments.map(({ partner }) => ({
+ workspaceId: workspace.id,
+ programId,
+ action: "partner.banned",
+ description: `Partner ${partner.id} banned`,
+ actor: user,
+ targets: [
+ {
+ type: "partner",
+ id: partner.id,
+ metadata: partner,
+ },
+ ],
+ })),
+ ),
+ ]);
// Send email
const program = await prisma.program.findUniqueOrThrow({
@@ -156,11 +166,6 @@ export const bulkBanPartnersAction = authActionClient
},
});
- if (!resend) {
- console.error("Resend is not configured, skipping email sending.");
- return;
- }
-
await sendBatchEmail(
programEnrollments
.filter(({ partner }) => partner.email)
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index a95873ce72..a9b43dd9b4 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -1,7 +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 { queueDiscountCodeDeletion } 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";
@@ -67,7 +67,9 @@ export const deleteDiscountAction = authActionClient
}),
discount.couponCodeTrackingEnabledAt &&
- queueDiscountCodeDeletionJobs(discountId),
+ queueDiscountCodeDeletion({
+ 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 acd3fc3790..71454ee764 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -1,7 +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 { queueDiscountCodeDeletion } 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";
@@ -62,7 +62,10 @@ export const updateDiscountAction = authActionClient
},
}),
- trackingDisabled && queueDiscountCodeDeletionJobs(discountId),
+ trackingDisabled &&
+ queueDiscountCodeDeletion({
+ discountId,
+ }),
recordAuditLog({
workspaceId: workspace.id,
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 803e723a66..390cff04c5 100644
--- a/apps/web/lib/api/discounts/queue-discount-code-deletion.ts
+++ b/apps/web/lib/api/discounts/queue-discount-code-deletion.ts
@@ -6,50 +6,74 @@ const queue = qstash.queue({
queueName: "discount-code-deletion",
});
-export async function queueDiscountCodeDeletionJobs(discountId: string) {
+// Triggered in the following cases:
+// 1. When a discount is deleted
+// 2. When coupon tracking is disabled for a discount
+// 3. When a link is deleted that has a discount code associated with it
+export async function queueDiscountCodeDeletion({
+ discountId,
+ discountCodeId,
+}: {
+ discountId?: string;
+ discountCodeId?: string;
+}) {
await queue.upsert({
parallelism: 10,
});
- let cursor: undefined | string = undefined;
-
- while (true) {
- const discountCodes = await prisma.discountCode.findMany({
- where: {
- discountId,
- },
- select: {
- id: true,
- },
- orderBy: {
- createdAt: "asc",
+ // Delete a discount code
+ if (discountCodeId) {
+ return await queue.enqueueJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/delete-discount-code`,
+ method: "POST",
+ body: {
+ discountCodeId,
},
- cursor: {
- id: cursor,
- },
- take: 100,
});
+ }
- if (discountCodes.length === 0) {
- break;
- }
+ // Delete all codes for a discount
+ if (discountId) {
+ 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,
+ });
- console.log("discountCodes", discountCodes);
+ if (discountCodes.length === 0) {
+ break;
+ }
- 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("discountCodes", discountCodes);
- console.log("response", response);
+ 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,
+ },
+ }),
+ ),
+ );
- cursor = discountCodes[discountCodes.length - 1].id;
+ console.log("response", response);
+
+ cursor = discountCodes[discountCodes.length - 1].id;
+ }
}
}
diff --git a/apps/web/lib/api/links/bulk-delete-links.ts b/apps/web/lib/api/links/bulk-delete-links.ts
index a26e67c1de..413250e225 100644
--- a/apps/web/lib/api/links/bulk-delete-links.ts
+++ b/apps/web/lib/api/links/bulk-delete-links.ts
@@ -2,7 +2,6 @@ import { storage } from "@/lib/storage";
import { recordLinkTB, transformLinkTB } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
import { R2_URL } from "@dub/utils";
-import { enqueueCouponCodeDeleteJobs } from "../discounts/queue-discount-code-deletion";
import { linkCache } from "./cache";
import { ExpandedLink } from "./utils";
@@ -37,7 +36,5 @@ export async function bulkDeleteLinks(links: ExpandedLink[]) {
totalLinks: { decrement: links.length },
},
}),
-
- enqueueCouponCodeDeleteJobs(links),
]);
}
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 2086f9e8c6..78ab8a0141 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -3,7 +3,7 @@ import { recordLinkTB, transformLinkTB } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
import { R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
-import { enqueueCouponCodeDeleteJobs } from "../discounts/queue-discount-code-deletion";
+import { queueDiscountCodeDeletion } from "../discounts/queue-discount-code-deletion";
import { linkCache } from "./cache";
import { includeTags } from "./include-tags";
import { transformLink } from "./utils";
@@ -21,6 +21,7 @@ export async function deleteLink(linkId: string) {
stripeConnectId: true,
},
},
+ discountCode: true,
},
});
@@ -50,8 +51,10 @@ export async function deleteLink(linkId: string) {
},
}),
- // Delete the coupon code for the link if it exists
- link.couponCode && enqueueCouponCodeDeleteJobs(link),
+ link.discountCode &&
+ queueDiscountCodeDeletion({
+ discountCodeId: link.discountCode.id,
+ }),
]),
);