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 actions and schema, remove promotion code cron

Kiran Ke64deb87a750
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
deleted file mode 100644
index 51d18fa91d..0000000000
--- a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { qstash } from "@/lib/cron";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { createStripePromotionCode } from "@/lib/stripe/create-stripe-promotion-code";
-import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK, chunk, log } from "@dub/utils";
-import { z } from "zod";
-
-export const dynamic = "force-dynamic";
-
-const schema = z.object({
- discountId: z.string(),
- page: z.number().optional().default(1),
-});
-
-const PAGE_LIMIT = 20;
-const MAX_BATCHES = 5;
-
-// POST /api/cron/links/create-promotion-codes
-export async function POST(req: Request) {
- let parsedBody: z.infer<typeof schema> | undefined;
-
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- parsedBody = schema.parse(JSON.parse(rawBody));
- const { discountId, page } = parsedBody;
-
- const {
- couponId,
- programId,
- program: { couponCodeTrackingEnabledAt, workspace },
- } = await prisma.discount.findUniqueOrThrow({
- where: {
- id: discountId,
- },
- select: {
- couponId: true,
- programId: true,
- program: {
- select: {
- couponCodeTrackingEnabledAt: true,
- workspace: {
- select: {
- stripeConnectId: true,
- },
- },
- },
- },
- },
- });
-
- if (!couponCodeTrackingEnabledAt) {
- return new Response(
- "couponCodeTrackingEnabledAt is not set for the program. Skipping promotion code creation.",
- );
- }
-
- if (!couponId) {
- return new Response(
- "couponId doesn't set for the discount. Skipping promotion code creation.",
- );
- }
-
- let hasMore = true;
- let currentPage = page;
- let processedBatches = 0;
-
- while (hasMore && processedBatches < MAX_BATCHES) {
- const enrollments = await prisma.programEnrollment.findMany({
- where: {
- programId,
- discountId,
- },
- select: {
- partnerId: true,
- },
- orderBy: {
- id: "desc",
- },
- take: PAGE_LIMIT,
- skip: (currentPage - 1) * PAGE_LIMIT,
- });
-
- if (enrollments.length === 0) {
- console.log("No more enrollments found.");
- hasMore = false;
- break;
- }
-
- const links = await prisma.link.findMany({
- where: {
- programId,
- partnerId: {
- in: enrollments.map(({ partnerId }) => partnerId),
- },
- couponCode: null,
- },
- select: {
- id: true,
- key: true,
- },
- });
-
- if (links.length === 0) {
- console.log("No more links found.");
- currentPage++;
- processedBatches++;
- continue;
- }
-
- const linksChunks = chunk(links, 10);
- const failedRequests: Error[] = [];
-
- for (const linksChunk of linksChunks) {
- const results = await Promise.allSettled(
- linksChunk.map((link) =>
- createStripePromotionCode({
- link,
- couponId,
- stripeConnectId: workspace.stripeConnectId,
- }),
- ),
- );
-
- results.forEach((result) => {
- if (result.status === "rejected") {
- failedRequests.push(result.reason);
- }
- });
-
- await new Promise((resolve) => setTimeout(resolve, 2000));
- }
-
- if (failedRequests.length > 0) {
- console.error(failedRequests);
- }
-
- currentPage++;
- processedBatches++;
- }
-
- if (hasMore) {
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,
- body: {
- discountId,
- page: currentPage,
- },
- });
- }
-
- return new Response("OK");
- } catch (error) {
- console.error(parsedBody);
-
- await log({
- message: `Error creating Stripe promotion codes: ${error.message} - ${JSON.stringify(parsedBody)}`,
- type: "errors",
- });
-
- return handleAndReturnErrorResponse(error);
- }
-}
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 8850664e59..5f7e348cf3 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -16,8 +16,15 @@ export const createDiscountAction = authActionClient
.schema(createDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
- let { amount, type, maxDuration, couponId, couponTestId, groupId, enableCouponTracking } =
- parsedInput;
+ let {
+ amount,
+ type,
+ maxDuration,
+ couponId,
+ couponTestId,
+ groupId,
+ enableCouponTracking,
+ } = parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
@@ -69,13 +76,9 @@ export const createDiscountAction = authActionClient
maxDuration,
couponId,
couponTestId,
- },
- include: {
- program: {
- select: {
- couponCodeTrackingEnabledAt: true,
- },
- },
+ ...(enableCouponTracking && {
+ couponCodeTrackingEnabledAt: new Date(),
+ }),
},
});
@@ -110,14 +113,6 @@ export const createDiscountAction = authActionClient
},
}),
- discount.program.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 432dee6724..e4397c41a7 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -4,7 +4,6 @@ import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
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";
-import { deleteStripeCoupon } from "@/lib/stripe/delete-stripe-coupon";
import { prisma } from "@dub/prisma";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
@@ -66,14 +65,6 @@ export const deleteDiscountAction = authActionClient
},
}),
- // Question:
- // Would this be a problem if the coupon is used in their application?
- discount.couponId &&
- deleteStripeCoupon({
- couponId: discount.couponId,
- stripeConnectId: workspace.stripeConnectId,
- }),
-
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
new file mode 100644
index 0000000000..90a82bbdc5
--- /dev/null
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -0,0 +1,70 @@
+"use server";
+
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+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";
+import { updateDiscountSchema } from "@/lib/zod/schemas/discount";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { authActionClient } from "../safe-action";
+
+export const updateDiscountAction = authActionClient
+ .schema(updateDiscountSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace, user } = ctx;
+ let { discountId, couponId, couponTestId } = parsedInput;
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const discount = await getDiscountOrThrow({
+ programId,
+ discountId,
+ });
+
+ const { partnerGroup, ...updatedDiscount } = await prisma.discount.update({
+ where: {
+ id: discountId,
+ },
+ data: {
+ couponId,
+ couponTestId,
+ },
+ include: {
+ partnerGroup: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ await Promise.allSettled([
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
+ body: {
+ groupId: partnerGroup?.id,
+ },
+ }),
+
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "discount.updated",
+ description: `Discount ${discount.id} updated`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: discount.id,
+ metadata: updatedDiscount,
+ },
+ ],
+ }),
+ ]);
+ })(),
+ );
+ });
diff --git a/apps/web/lib/api/partners/get-discount-or-throw.ts b/apps/web/lib/api/partners/get-discount-or-throw.ts
index 4b82013b0c..1d15b7e6e4 100644
--- a/apps/web/lib/api/partners/get-discount-or-throw.ts
+++ b/apps/web/lib/api/partners/get-discount-or-throw.ts
@@ -1,29 +1,19 @@
import { DiscountSchema } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
-import { Discount } from "@prisma/client";
import { DubApiError } from "../errors";
export async function getDiscountOrThrow({
discountId,
programId,
- includePartnersCount = false,
}: {
discountId: string;
programId: string;
- includePartnersCount?: boolean;
}) {
- const discount = (await prisma.discount.findUnique({
+ const discount = await prisma.discount.findUnique({
where: {
id: discountId,
},
- ...(includePartnersCount && {
- include: {
- _count: {
- select: { programEnrollments: true },
- },
- },
- }),
- })) as Discount & { _count?: { programEnrollments: number } };
+ });
if (!discount) {
throw new DubApiError({
@@ -39,10 +29,5 @@ export async function getDiscountOrThrow({
});
}
- return DiscountSchema.parse({
- ...discount,
- ...(includePartnersCount && {
- partnersCount: discount._count?.programEnrollments,
- }),
- });
+ return DiscountSchema.parse(discount);
}
diff --git a/apps/web/lib/stripe/delete-stripe-coupon.ts b/apps/web/lib/stripe/delete-stripe-coupon.ts
deleted file mode 100644
index dc5496db53..0000000000
--- a/apps/web/lib/stripe/delete-stripe-coupon.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { stripeAppClient } from ".";
-
-const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
-});
-
-// Delete a coupon on Stripe for connected accounts
-export async function deleteStripeCoupon({
- couponId,
- stripeConnectId,
-}: {
- couponId: string;
- stripeConnectId: string | null;
-}) {
- if (!stripeConnectId) {
- console.error(
- "stripeConnectId not found for the workspace. Stripe coupon creation skipped.",
- );
- return;
- }
-
- try {
- return await stripe.coupons.del(couponId, {
- stripeAccount: stripeConnectId,
- });
- } catch (error) {
- console.error(
- `Failed to delete Stripe coupon for ${stripeConnectId}: ${error}`,
- );
- return null;
- }
-}
diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.ts
index 856e7bf91e..938b2695b6 100644
--- a/apps/web/lib/zod/schemas/discount.ts
+++ b/apps/web/lib/zod/schemas/discount.ts
@@ -35,6 +35,8 @@ export const createDiscountSchema = z.object({
export const updateDiscountSchema = createDiscountSchema
.pick({
workspaceId: true,
+ couponId: true,
+ couponTestId: true,
})
.extend({
discountId: z.string(),
diff --git a/packages/prisma/schema/discount.prisma b/packages/prisma/schema/discount.prisma
index 153d606999..d5a50cfe5f 100644
--- a/packages/prisma/schema/discount.prisma
+++ b/packages/prisma/schema/discount.prisma
@@ -1,14 +1,15 @@
model Discount {
- id String @id @default(cuid())
- programId String
- amount Int @default(0)
- type RewardStructure @default(percentage)
- maxDuration Int? // in months (0 -> not recurring, null -> lifetime)
- description String?
- couponId String?
- couponTestId String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ programId String
+ amount Int @default(0)
+ type RewardStructure @default(percentage)
+ maxDuration Int? // in months (0 -> not recurring, null -> lifetime)
+ description String?
+ couponId String?
+ couponTestId String?
+ couponCodeTrackingEnabledAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
programEnrollments ProgramEnrollment[]
program Program @relation("ProgramDiscounts", fields: [programId], references: [id], onDelete: Cascade, onUpdate: Cascade)
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 61b47f914a..3cb00b85c0 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -56,7 +56,6 @@ model Program {
supportEmail String?
ageVerification Int?
autoApprovePartnersEnabledAt DateTime?
- couponCodeTrackingEnabledAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt