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 to use partner groups

Kiran Kee054f080113
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 44bbca3348..3f68170621 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -2,8 +2,8 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { createId } from "@/lib/api/create-id";
+import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { qstash } from "@/lib/cron";
import { createDiscountSchema } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
@@ -15,106 +15,48 @@ export const createDiscountAction = authActionClient
.schema(createDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
- let {
- amount,
- type,
- maxDuration,
- couponId,
- couponTestId,
- isDefault,
- includedPartnerIds,
- excludedPartnerIds,
- } = parsedInput;
-
- includedPartnerIds = includedPartnerIds || [];
- excludedPartnerIds = excludedPartnerIds || [];
+ const { amount, type, maxDuration, couponId, couponTestId, groupId } =
+ parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
- await getProgramOrThrow({
- workspaceId: workspace.id,
+ await getGroupOrThrow({
+ groupId,
programId,
});
- // A program can have only one default discount
- if (isDefault) {
- const defaultDiscount = await prisma.discount.findFirst({
- where: {
+ const discount = await prisma.$transaction(async (tx) => {
+ const discount = await tx.discount.create({
+ data: {
+ id: createId({ prefix: "disc_" }),
programId,
- default: true,
+ amount,
+ type,
+ maxDuration,
+ couponId,
+ couponTestId,
},
});
- if (defaultDiscount) {
- throw new Error(
- "There is an existing default discount already. A program can only have one default discount.",
- );
- }
- }
-
- const finalPartnerIds = [...includedPartnerIds, ...excludedPartnerIds];
-
- if (finalPartnerIds && finalPartnerIds.length > 0) {
- const programEnrollments = await prisma.programEnrollment.findMany({
+ await tx.partnerGroup.update({
where: {
- programId,
- partnerId: {
- in: finalPartnerIds,
- },
+ id: groupId,
},
- select: {
- partnerId: true,
- discountId: true,
- partner: true,
+ data: {
+ discountId: discount.id,
},
});
- const invalidPartnerIds = finalPartnerIds.filter(
- (id) =>
- !programEnrollments.some((enrollment) => enrollment.partnerId === id),
- );
-
- if (invalidPartnerIds.length > 0) {
- throw new Error(
- `Invalid partner IDs provided: ${invalidPartnerIds.join(", ")}`,
- );
- }
- }
-
- const discount = await prisma.discount.create({
- data: {
- id: createId({ prefix: "disc_" }),
- programId,
- amount,
- type,
- maxDuration,
- couponId,
- couponTestId,
- default: isDefault,
- },
- });
+ await tx.programEnrollment.updateMany({
+ where: {
+ groupId,
+ },
+ data: {
+ discountId: discount.id,
+ },
+ });
- await prisma.programEnrollment.updateMany({
- where: {
- programId,
- ...(discount.default
- ? {
- discountId: null,
- ...(excludedPartnerIds.length > 0 && {
- partnerId: {
- notIn: excludedPartnerIds,
- },
- }),
- }
- : {
- partnerId: {
- in: includedPartnerIds,
- },
- }),
- },
- data: {
- discountId: discount.id,
- },
+ return discount;
});
waitUntil(
@@ -125,7 +67,6 @@ export const createDiscountAction = authActionClient
body: {
programId,
discountId: discount.id,
- isDefault,
action: "discount-created",
},
}),
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index 99099c846a..c2d4695cc0 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -3,9 +3,7 @@
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 { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { qstash } from "@/lib/cron";
-import { redis } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
@@ -25,109 +23,63 @@ export const deleteDiscountAction = authActionClient
const programId = getDefaultProgramIdOrThrow(workspace);
- const program = await getProgramOrThrow({
- workspaceId: workspace.id,
- programId,
- });
-
const discount = await getDiscountOrThrow({
programId,
discountId,
});
- if (!discount.default) {
- let offset = 0;
-
- while (true) {
- const partners = await prisma.programEnrollment.findMany({
- where: {
- programId,
- discountId,
- },
- select: {
- partnerId: true,
- },
- skip: offset,
- take: 1000,
- });
-
- if (partners.length === 0) {
- break;
- }
-
- await redis.lpush(
- `discount-partners:${discountId}`,
- partners.map((partner) => partner.partnerId),
- );
-
- offset += 1000;
- }
- }
-
- const deletedDiscountId = await prisma.$transaction(async (tx) => {
- // 1. Find the default discount (if it exists)
- const defaultDiscount = await tx.discount.findFirst({
+ await prisma.$transaction(async (tx) => {
+ await tx.partnerGroup.update({
where: {
- programId,
- default: true,
+ discountId: discount.id,
+ },
+ data: {
+ discountId: null,
},
});
- // 2. Update current associations
await tx.programEnrollment.updateMany({
where: {
- programId,
discountId: discount.id,
},
data: {
- // Replace the current discount with the default discount if it exists
- // and the discount we're deleting is not the default discount
- discountId: discount.default
- ? null
- : defaultDiscount
- ? defaultDiscount.id
- : null,
+ discountId: null,
},
});
- // 3. Finally, delete the current discount
await tx.discount.delete({
where: {
id: discount.id,
},
});
-
- return discountId;
});
- if (deletedDiscountId) {
- waitUntil(
- Promise.allSettled([
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- programId,
- discountId,
- isDefault: discount.default,
- action: "discount-deleted",
- },
- }),
-
- recordAuditLog({
- workspaceId: workspace.id,
+ waitUntil(
+ Promise.allSettled([
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
+ body: {
programId,
- action: "discount.deleted",
- description: `Discount ${discountId} deleted`,
- actor: user,
- targets: [
- {
- type: "discount",
- id: discountId,
- metadata: discount,
- },
- ],
- }),
- ]),
- );
- }
+ discountId,
+ isDefault: discount.default,
+ action: "discount-deleted",
+ },
+ }),
+
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "discount.deleted",
+ description: `Discount ${discountId} deleted`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: discountId,
+ metadata: discount,
+ },
+ ],
+ }),
+ ]),
+ );
});
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index 3c2f388cc6..d4c5134953 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -6,7 +6,6 @@ import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-progr
import { qstash } from "@/lib/cron";
import { updateDiscountSchema } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
-import { Discount } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK, deepEqual } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { authActionClient } from "../safe-action";
@@ -15,19 +14,8 @@ export const updateDiscountAction = authActionClient
.schema(updateDiscountSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
- let {
- discountId,
- amount,
- type,
- maxDuration,
- couponId,
- couponTestId,
- includedPartnerIds,
- excludedPartnerIds,
- } = parsedInput;
-
- includedPartnerIds = includedPartnerIds || [];
- excludedPartnerIds = excludedPartnerIds || [];
+ const { discountId, amount, type, maxDuration, couponId, couponTestId } =
+ parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
@@ -36,32 +24,6 @@ export const updateDiscountAction = authActionClient
discountId,
});
- const finalPartnerIds = [...includedPartnerIds, ...excludedPartnerIds];
-
- if (finalPartnerIds && finalPartnerIds.length > 0) {
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- programId,
- partnerId: {
- in: finalPartnerIds,
- },
- },
- select: {
- partnerId: true,
- },
- });
-
- const invalidPartnerIds = finalPartnerIds.filter(
- (id) => !programEnrollments.some(({ partnerId }) => partnerId === id),
- );
-
- if (invalidPartnerIds.length > 0) {
- throw new Error(
- `Invalid partner IDs provided: ${invalidPartnerIds.join(", ")}`,
- );
- }
- }
-
const updatedDiscount = await prisma.discount.update({
where: {
id: discountId,
@@ -75,19 +37,6 @@ export const updateDiscountAction = authActionClient
},
});
- // Update partners associated with the discount
- if (updatedDiscount.default) {
- await updateDefaultDiscountPartners({
- discount: updatedDiscount,
- partnerIds: excludedPartnerIds,
- });
- } else {
- await updateNonDefaultDiscountPartners({
- discount: updatedDiscount,
- partnerIds: includedPartnerIds,
- });
- }
-
waitUntil(
(async () => {
const shouldExpireCache = !deepEqual(
@@ -134,131 +83,3 @@ export const updateDiscountAction = authActionClient
})(),
);
});
-
-// Update default discount
-const updateDefaultDiscountPartners = async ({
- discount,
- partnerIds,
-}: {
- discount: Discount;
- partnerIds: string[]; // Excluded partners
-}) => {
- const existingPartners = await prisma.programEnrollment.findMany({
- where: {
- programId: discount.programId,
- discountId: null,
- },
- select: {
- partnerId: true,
- },
- });
-
- const existingPartnerIds = existingPartners.map(({ partnerId }) => partnerId);
-
- const excludedPartnerIds = partnerIds.filter(
- (id) => !existingPartnerIds.includes(id),
- );
-
- const includedPartnerIds = existingPartnerIds.filter(
- (id) => !partnerIds.includes(id),
- );
-
- // Exclude partners from the default discount
- if (excludedPartnerIds.length > 0) {
- await prisma.programEnrollment.updateMany({
- where: {
- programId: discount.programId,
- partnerId: {
- in: excludedPartnerIds,
- },
- },
- data: {
- discountId: null,
- },
- });
- }
-
- // Include partners in the default discount
- if (includedPartnerIds.length > 0) {
- await prisma.programEnrollment.updateMany({
- where: {
- programId: discount.programId,
- discountId: null,
- partnerId: {
- in: includedPartnerIds,
- },
- },
- data: {
- discountId: discount.id,
- },
- });
- }
-};
-
-// Update non-default discount
-const updateNonDefaultDiscountPartners = async ({
- discount,
- partnerIds,
-}: {
- discount: Discount;
- partnerIds: string[]; // Included partners
-}) => {
- const existingPartners = await prisma.programEnrollment.findMany({
- where: {
- programId: discount.programId,
- discountId: discount.id,
- },
- select: {
- partnerId: true,
- },
- });
-
- const existingPartnerIds = existingPartners.map(({ partnerId }) => partnerId);
-
- const includedPartnerIds = partnerIds.filter(
- (id) => !existingPartnerIds.includes(id),
- );
-
- const excludedPartnerIds = existingPartnerIds.filter(
- (id) => !partnerIds.includes(id),
- );
-
- // Include partners in the discount
- if (includedPartnerIds.length > 0) {
- await prisma.programEnrollment.updateMany({
- where: {
- programId: discount.programId,
- partnerId: {
- in: includedPartnerIds,
- },
- },
- data: {
- discountId: discount.id,
- },
- });
- }
-
- // Exclude partners from the discount
- if (excludedPartnerIds.length > 0) {
- const defaultDiscount = await prisma.discount.findFirst({
- where: {
- programId: discount.programId,
- default: true,
- },
- });
-
- await prisma.programEnrollment.updateMany({
- where: {
- programId: discount.programId,
- discountId: discount.id,
- partnerId: {
- in: excludedPartnerIds,
- },
- },
- data: {
- // Replace the discount with the default discount if it exists
- discountId: defaultDiscount ? defaultDiscount.id : null,
- },
- });
- }
-};
diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.ts
index bb3fabc8d4..244b8b7935 100644
--- a/apps/web/lib/zod/schemas/discount.ts
+++ b/apps/web/lib/zod/schemas/discount.ts
@@ -29,20 +29,16 @@ export const createDiscountSchema = z.object({
maxDuration: maxDurationSchema,
couponId: z.string(),
couponTestId: z.string().nullish(),
- isDefault: z.boolean(),
- includedPartnerIds: z
- .array(z.string())
- .nullish()
- .describe("Only applicable for non-default discounts"),
- excludedPartnerIds: z
- .array(z.string())
- .nullish()
- .describe("Only applicable for default discounts"),
+ groupId: z.string(),
});
-export const updateDiscountSchema = createDiscountSchema.extend({
- discountId: z.string(),
-});
+export const updateDiscountSchema = createDiscountSchema
+ .omit({
+ groupId: true,
+ })
+ .extend({
+ discountId: z.string(),
+ });
export const discountPartnersQuerySchema = z
.object({