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 /api/cron/links/create-promotion-codes and /api/cron/links/delete-promotion-codes

Kiran K347dc43122a6
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
new file mode 100644
index 0000000000..02c9869acd
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts
@@ -0,0 +1,165 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { createStripePromotionCode } from "@/lib/stripe/create-stripe-promotion-code";
+import { prisma } from "@dub/prisma";
+import { chunk } from "@dub/utils";
+import { z } from "zod";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ discountId: z.string(),
+});
+
+// POST /api/cron/links/create-promotion-codes
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+ await verifyQstashSignature({ req, rawBody });
+
+ const { discountId } = schema.parse(JSON.parse(rawBody));
+
+ const discount = await prisma.discount.findUnique({
+ where: {
+ id: discountId,
+ },
+ include: {
+ partnerGroup: true,
+ program: true,
+ },
+ });
+
+ if (!discount) {
+ return logAndRespond({
+ message: `Discount ${discountId} not found.`,
+ logLevel: "error",
+ });
+ }
+
+ if (!discount.couponId) {
+ return logAndRespond({
+ message: `Discount ${discountId} does not have a couponId set.`,
+ logLevel: "error",
+ });
+ }
+
+ if (!discount.couponCodeTrackingEnabledAt) {
+ return logAndRespond({
+ message: `Discount ${discountId} is not enabled for coupon code tracking.`,
+ });
+ }
+
+ if (!discount.partnerGroup) {
+ return logAndRespond({
+ message: `Discount ${discountId} is not associated with a partner group.`,
+ logLevel: "error",
+ });
+ }
+
+ // Find the workspace for the program
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: discount.program.workspaceId,
+ },
+ select: {
+ stripeConnectId: true,
+ },
+ });
+
+ if (!workspace) {
+ return logAndRespond({
+ message: `Workspace ${discount.program.workspaceId} not found.`,
+ logLevel: "error",
+ });
+ }
+
+ if (!workspace.stripeConnectId) {
+ return logAndRespond({
+ message: `Workspace ${discount.program.workspaceId} does not have a stripeConnectId set.`,
+ logLevel: "error",
+ });
+ }
+
+ let page = 0;
+ let hasMore = true;
+ const pageSize = 50;
+
+ while (hasMore) {
+ // Find all enrollments for the partner group
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId: discount.partnerGroup.id,
+ },
+ orderBy: {
+ id: "desc",
+ },
+ take: pageSize,
+ skip: page * pageSize,
+ });
+
+ if (enrollments.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ // Find all links for the enrollments
+ const links = await prisma.link.findMany({
+ where: {
+ programId: discount.programId,
+ partnerId: {
+ in: enrollments.map(({ partnerId }) => partnerId),
+ },
+ couponCode: null,
+ },
+ select: {
+ id: true,
+ key: true,
+ },
+ });
+
+ if (links.length === 0) {
+ page++;
+ continue;
+ }
+
+ const linksChunks = chunk(links, 50);
+ const failedRequests: Error[] = [];
+
+ // Create promotion codes in batches for the partner links
+ for (const linksChunk of linksChunks) {
+ const results = await Promise.allSettled(
+ linksChunk.map((link) =>
+ createStripePromotionCode({
+ link,
+ coupon: discount,
+ stripeConnectId: workspace.stripeConnectId,
+ }),
+ ),
+ );
+
+ results.forEach((result) => {
+ if (result.status === "rejected") {
+ failedRequests.push(result.reason);
+ }
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ }
+
+ if (failedRequests.length > 0) {
+ console.error(failedRequests);
+ }
+
+ page++;
+ }
+
+ return logAndRespond({
+ message: `Promotion codes created for discount ${discountId}.`,
+ });
+ } catch (error) {
+ console.log(error);
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
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
new file mode 100644
index 0000000000..90b23b3c50
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/links/delete-promotion-codes/route.ts
@@ -0,0 +1,156 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { disableStripePromotionCode } from "@/lib/stripe/disable-stripe-promotion-code";
+import { prisma } from "@dub/prisma";
+import { chunk } from "@dub/utils";
+import { z } from "zod";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ groupId: z.string(),
+});
+
+// POST /api/cron/links/delete-promotion-codes
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+ await verifyQstashSignature({ req, rawBody });
+
+ const { groupId } = schema.parse(JSON.parse(rawBody));
+
+ const group = await prisma.partnerGroup.findUnique({
+ where: {
+ id: groupId,
+ },
+ include: {
+ program: true,
+ },
+ });
+
+ if (!group) {
+ return logAndRespond({
+ message: `Partner group ${groupId} not found.`,
+ logLevel: "error",
+ });
+ }
+
+ // Find the workspace for the program
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: group.program.workspaceId,
+ },
+ select: {
+ stripeConnectId: true,
+ },
+ });
+
+ if (!workspace) {
+ return logAndRespond({
+ message: `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",
+ });
+ }
+
+ let page = 0;
+ let hasMore = true;
+ const pageSize = 50;
+
+ while (hasMore) {
+ // Find all enrollments for the partner group
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId: group.id,
+ },
+ orderBy: {
+ id: "desc",
+ },
+ take: pageSize,
+ skip: page * pageSize,
+ });
+
+ if (enrollments.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ // Find all links for the enrollments
+ const links = await prisma.link.findMany({
+ where: {
+ programId: group.program.id,
+ partnerId: {
+ in: enrollments.map(({ partnerId }) => partnerId),
+ },
+ couponCode: {
+ not: null,
+ },
+ },
+ select: {
+ id: true,
+ couponCode: true,
+ },
+ });
+
+ if (links.length === 0) {
+ page++;
+ continue;
+ }
+
+ const linksChunks = chunk(links, 50);
+ const failedRequests: Error[] = [];
+
+ // Disable promotion codes in batches for the partner links
+ for (const linksChunk of linksChunks) {
+ const results = await Promise.allSettled(
+ linksChunk.map((link) =>
+ disableStripePromotionCode({
+ promotionCode: link.couponCode,
+ stripeConnectId: workspace.stripeConnectId,
+ }),
+ ),
+ );
+
+ results.forEach((result) => {
+ if (result.status === "rejected") {
+ failedRequests.push(result.reason);
+ }
+ });
+
+ await prisma.link.updateMany({
+ where: {
+ id: {
+ in: linksChunk.map(({ id }) => id),
+ },
+ },
+ data: {
+ couponCode: null,
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ }
+
+ if (failedRequests.length > 0) {
+ console.error(failedRequests);
+ }
+
+ page++;
+ }
+
+ return logAndRespond({
+ message: `Promotion codes deleted for group ${groupId}.`,
+ });
+ } catch (error) {
+ console.log(error);
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/(ee)/api/cron/utils.ts b/apps/web/app/(ee)/api/cron/utils.ts
new file mode 100644
index 0000000000..fa98fbbdfe
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/utils.ts
@@ -0,0 +1,12 @@
+export function logAndRespond({
+ message,
+ status = 200,
+ logLevel = "info",
+}: {
+ message: string;
+ status?: number;
+ logLevel?: "error" | "warn" | "info";
+}) {
+ console[logLevel](message);
+ return new Response(message, { status });
+}
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 1a86e39f04..d4abf2499e 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -115,6 +115,14 @@ export const createDiscountAction = authActionClient
},
}),
+ discount.couponCodeTrackingEnabledAt &&
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,
+ body: {
+ discountId: discount.id,
+ },
+ }),
+
recordAuditLog({
workspaceId: workspace.id,
programId,
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index e4397c41a7..7ef0873548 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -65,6 +65,14 @@ export const deleteDiscountAction = authActionClient
},
}),
+ discount.couponCodeTrackingEnabledAt &&
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete-promotion-codes`,
+ body: {
+ groupId: group.id,
+ },
+ }),
+
recordAuditLog({
workspaceId: workspace.id,
programId,
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index 90a82bbdc5..a4dc7c585f 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -10,6 +10,11 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { authActionClient } from "../safe-action";
+// TODO:
+// Allow updating couponCodeTrackingEnabledAt
+// If couponCodeTrackingEnabledAt is set to true, create promotion codes for all links in the group
+// If couponCodeTrackingEnabledAt is set to false, remove promotion codes for all links in the group
+
export const updateDiscountAction = authActionClient
.schema(updateDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
@@ -40,9 +45,13 @@ export const updateDiscountAction = authActionClient
},
});
- waitUntil(
- (async () => {
- await Promise.allSettled([
+ const discountChanged =
+ discount.couponId !== updatedDiscount.couponId ||
+ discount.couponTestId !== updatedDiscount.couponTestId;
+
+ if (discountChanged) {
+ waitUntil(
+ Promise.allSettled([
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
body: {
@@ -64,7 +73,7 @@ export const updateDiscountAction = authActionClient
},
],
}),
- ]);
- })(),
- );
+ ]),
+ );
+ }
});
diff --git a/apps/web/lib/api/links/bulk-delete-links.ts b/apps/web/lib/api/links/bulk-delete-links.ts
index 8157e9e457..33ba76e670 100644
--- a/apps/web/lib/api/links/bulk-delete-links.ts
+++ b/apps/web/lib/api/links/bulk-delete-links.ts
@@ -50,7 +50,7 @@ export async function bulkDeleteLinks({
.filter((link) => link.couponCode)
.map((link) =>
disableStripePromotionCode({
- couponCode: link.couponCode,
+ 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 9fdebba521..2cd0b4c89d 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"
+ "couponId" | "couponCodeTrackingEnabledAt" | "amount" | "type"
> | null;
skipCouponCreation?: boolean; // Skip Stripe promotion code creation for the link
};
@@ -193,6 +193,8 @@ export async function createLink(link: CreateLinkProps) {
select: {
couponId: true,
couponCodeTrackingEnabledAt: true,
+ amount: true,
+ type: true,
},
},
},
@@ -201,14 +203,6 @@ export async function createLink(link: CreateLinkProps) {
discount = programEnrollment.discount;
}
- const shouldCreateCouponCode = Boolean(
- !skipCouponCreation &&
- link.projectId &&
- discount?.couponId &&
- discount?.couponCodeTrackingEnabledAt &&
- workspace?.stripeConnectId,
- );
-
Promise.allSettled([
// cache link in Redis
linkCache.set({
@@ -266,10 +260,13 @@ export async function createLink(link: CreateLinkProps) {
testVariants && testCompletedAt && scheduleABTestCompletion(response),
- shouldCreateCouponCode &&
+ // Create promotion code for the link
+ !skipCouponCreation &&
+ link.projectId &&
+ discount?.couponCodeTrackingEnabledAt &&
createStripePromotionCode({
link: response,
- couponId: discount?.couponId!,
+ coupon: discount,
stripeConnectId: workspace?.stripeConnectId!,
}),
]);
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index c11f931bc3..59fb557d7e 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -52,7 +52,7 @@ export async function deleteLink(linkId: string) {
link.project &&
link.couponCode &&
disableStripePromotionCode({
- couponCode: link.couponCode,
+ promotionCode: link.couponCode,
stripeConnectId: link.project.stripeConnectId,
}),
]),
diff --git a/apps/web/lib/stripe/create-stripe-promotion-code.ts b/apps/web/lib/stripe/create-stripe-promotion-code.ts
index 8b1c78966b..db55e96bf8 100644
--- a/apps/web/lib/stripe/create-stripe-promotion-code.ts
+++ b/apps/web/lib/stripe/create-stripe-promotion-code.ts
@@ -1,6 +1,6 @@
import { prisma } from "@dub/prisma";
import { stripeAppClient } from ".";
-import { LinkProps } from "../types";
+import { DiscountProps, LinkProps } from "../types";
const stripe = stripeAppClient({
...(process.env.VERCEL_ENV && { livemode: true }),
@@ -10,14 +10,14 @@ const MAX_RETRIES = 2;
export async function createStripePromotionCode({
link,
- couponId,
+ coupon,
stripeConnectId,
}: {
link: Pick<LinkProps, "id" | "key">;
- couponId: string | null;
+ coupon: Pick<DiscountProps, "couponId" | "amount" | "type">;
stripeConnectId: string | null;
}) {
- if (!couponId) {
+ if (!coupon.couponId) {
console.error(
"couponId not found for the discount. Stripe promotion code creation skipped.",
);
@@ -34,14 +34,16 @@ export async function createStripePromotionCode({
let lastError: Error | null = null;
let couponCode: string | undefined;
+ const amount =
+ coupon.type === "percentage" ? coupon.amount : coupon.amount / 100;
+
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
- // Add DUB_ prefix after first retry
- couponCode = attempt === 1 ? link.key : `DUB_${link.key}`;
+ couponCode = attempt === 1 ? link.key : `${link.key}${amount}`; // eg: DAVID30
const promotionCode = await stripe.promotionCodes.create(
{
- coupon: couponId,
+ coupon: coupon.couponId,
code: couponCode.toUpperCase(),
},
{
diff --git a/apps/web/lib/stripe/disable-stripe-promotion-code.ts b/apps/web/lib/stripe/disable-stripe-promotion-code.ts
index ab3bf99bd8..041a1be8e8 100644
--- a/apps/web/lib/stripe/disable-stripe-promotion-code.ts
+++ b/apps/web/lib/stripe/disable-stripe-promotion-code.ts
@@ -5,19 +5,19 @@ const stripe = stripeAppClient({
});
export async function disableStripePromotionCode({
- couponCode,
+ promotionCode,
stripeConnectId,
}: {
- couponCode: string | null;
+ promotionCode: string | null;
stripeConnectId: string | null;
}) {
- if (!couponCode || !stripeConnectId) {
+ if (!promotionCode || !stripeConnectId) {
return;
}
const promotionCodes = await stripe.promotionCodes.list(
{
- code: couponCode,
+ code: promotionCode,
limit: 1,
},
{
@@ -43,7 +43,7 @@ export async function disableStripePromotionCode({
);
} catch (error) {
console.error(
- `Failed to disable Stripe promotion code ${couponCode} for ${stripeConnectId}: ${error}`,
+ `Failed to disable Stripe promotion code ${promotionCode} for ${stripeConnectId}: ${error}`,
);
throw new Error(error instanceof Error ? error.message : "Unknown error");
diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
index 4337235ece..fce5323b23 100644
--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
@@ -88,6 +88,7 @@ function DiscountSheetContent({
maxDuration: 6,
couponId: "",
couponTestId: "",
+ couponCodeTrackingEnabledAt: null,
}; // default is 10% for 6 months
const form = useForm<FormData>({
@@ -103,6 +104,8 @@ function DiscountSheetContent({
: defaultValuesSource.maxDuration,
couponId: defaultValuesSource.couponId,
couponTestId: defaultValuesSource.couponTestId,
+ enableCouponTracking:
+ defaultValuesSource.couponCodeTrackingEnabledAt !== null,
},
});
@@ -297,8 +300,9 @@ function DiscountSheetContent({
<input
type="text"
id="couponId"
- className="border-border-subtle block w-full rounded-lg bg-white px-3 py-2 text-neutral-800 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ className="border-border-subtle block w-full rounded-lg bg-white px-3 py-2 text-neutral-800 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
{...register("couponId")}
+ placeholder="XZuejd0Q"
/>
</div>
</div>
@@ -341,8 +345,9 @@ function DiscountSheetContent({
<input
type="text"
id="couponTestId"
- className="border-border-subtle block w-full rounded-lg px-3 py-2 text-neutral-800 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ className="border-border-subtle block w-full rounded-lg px-3 py-2 text-neutral-800 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
{...register("couponTestId")}
+ placeholder="2NMXz81x"
/>
</div>
</div>
@@ -510,8 +515,8 @@ function DiscountSheetContent({
variant="primary"
text={discount ? "Update discount" : "Create discount"}
className="w-fit"
- loading={isCreating || isDeleting || isUpdating}
- disabled={!discount && amount == null}
+ loading={isCreating || isUpdating}
+ disabled={(!discount && amount == null) || isDeleting}
/>
</div>
</div>
diff --git a/packages/prisma/schema/discount.prisma b/packages/prisma/schema/discount.prisma
index 744d1a1f63..6655a9ff1c 100644
--- a/packages/prisma/schema/discount.prisma
+++ b/packages/prisma/schema/discount.prisma
@@ -15,5 +15,5 @@ model Discount {
program Program @relation("ProgramDiscounts", fields: [programId], references: [id], onDelete: Cascade, onUpdate: Cascade)
partnerGroup PartnerGroup?
- @@unique(programId)
+ @@index(programId)
}