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 discounts

Kiran K61e4cf5379ec
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
new file mode 100644
index 0000000000..af0f3ba264
--- /dev/null
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -0,0 +1,70 @@
+"use server";
+
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { createId } from "@/lib/api/utils";
+import { createDiscountSchema } from "@/lib/zod/schemas/discount";
+import { prisma } from "@dub/prisma";
+import { authActionClient } from "../safe-action";
+
+export const createDiscountAction = authActionClient
+ .schema(createDiscountSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const { programId, partnerIds, amount, maxDuration, isDefault } =
+ parsedInput;
+
+ const program = await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ let programEnrollments: { id: string }[] = [];
+
+ if (partnerIds) {
+ programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ programId,
+ partnerId: {
+ in: partnerIds,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (programEnrollments.length !== partnerIds.length) {
+ throw new Error("Invalid partner IDs provided.");
+ }
+ }
+
+ const discount = await prisma.discount.create({
+ data: {
+ id: createId({ prefix: "dis_" }),
+ workspaceId: workspace.id,
+ programId,
+ amount,
+ maxDuration,
+ ...(programEnrollments && {
+ partners: {
+ createMany: {
+ data: programEnrollments.map(({ id }) => ({
+ programEnrollmentId: id,
+ })),
+ },
+ },
+ }),
+ },
+ });
+
+ if (isDefault && !program.defaultDiscountId) {
+ await prisma.program.update({
+ where: {
+ id: programId,
+ },
+ data: {
+ defaultDiscountId: discount.id,
+ },
+ });
+ }
+ });
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..1fdaeff96e
--- /dev/null
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -0,0 +1,68 @@
+"use server";
+
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { updateDiscountSchema } from "@/lib/zod/schemas/discount";
+import { prisma } from "@dub/prisma";
+import { authActionClient } from "../safe-action";
+
+export const updateDiscountAction = authActionClient
+ .schema(updateDiscountSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const { programId, partnerIds, discountId, amount, maxDuration } =
+ parsedInput;
+
+ const program = await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ const discount = await prisma.discount.findUniqueOrThrow({
+ where: {
+ id: discountId,
+ },
+ });
+
+ if (discount.workspaceId !== workspace.id) {
+ throw new Error("Discount not found");
+ }
+
+ let programEnrollments: { id: string }[] = [];
+
+ if (partnerIds) {
+ programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ programId,
+ partnerId: {
+ in: partnerIds,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (programEnrollments.length !== partnerIds.length) {
+ throw new Error("Invalid partner IDs provided.");
+ }
+ }
+
+ await prisma.discount.update({
+ where: {
+ id: discountId,
+ },
+ data: {
+ amount,
+ maxDuration,
+ ...(programEnrollments && {
+ partners: {
+ createMany: {
+ data: programEnrollments.map(({ id }) => ({
+ programEnrollmentId: id,
+ })),
+ },
+ },
+ }),
+ },
+ });
+ });
diff --git a/apps/web/lib/api/utils.ts b/apps/web/lib/api/utils.ts
index 31186dbc9e..01a915209d 100644
--- a/apps/web/lib/api/utils.ts
+++ b/apps/web/lib/api/utils.ts
@@ -73,6 +73,7 @@ const prefixes = [
"inv_",
"rew_",
"fold_",
+ "dis_",
] as const;
export const createId = ({
diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.ts
index b50198b6d5..df359eb15f 100644
--- a/apps/web/lib/zod/schemas/discount.ts
+++ b/apps/web/lib/zod/schemas/discount.ts
@@ -1,5 +1,6 @@
import { CommissionInterval, CommissionType } from "@dub/prisma/client";
import { z } from "zod";
+import { RECURRING_MAX_DURATIONS } from "./rewards";
export const DiscountSchema = z.object({
id: z.string(),
@@ -10,3 +11,23 @@ export const DiscountSchema = z.object({
duration: z.number().nullable(),
interval: z.nativeEnum(CommissionInterval).nullable(),
});
+
+export const createDiscountSchema = z.object({
+ amount: z.number().min(0),
+ maxDuration: z.coerce
+ .number()
+ .refine((val) => RECURRING_MAX_DURATIONS.includes(val), {
+ message: `Max duration must be ${RECURRING_MAX_DURATIONS.join(", ")}`,
+ })
+ .nullish(),
+ isDefault: z.boolean().optional().default(false),
+ partnerIds: z.array(z.string()).nullish(),
+ workspaceId: z.string(),
+ programId: z.string(),
+});
+
+export const updateDiscountSchema = createDiscountSchema.merge(
+ z.object({
+ discountId: z.string(),
+ }),
+);
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index 092453ac9b..9ac6ee30ca 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -19,6 +19,7 @@ export const ProgramSchema = z.object({
type: z.nativeEnum(ProgramType),
cookieLength: z.number(),
defaultRewardId: z.string().nullable(),
+ defaultDiscountId: z.string().nullable(),
rewards: z.array(RewardSchema).nullish(),
holdingPeriodDays: z.number(),
diff --git a/packages/prisma/schema/discount.prisma b/packages/prisma/schema/discount.prisma
index 87dc878fe8..010cb74bd4 100644
--- a/packages/prisma/schema/discount.prisma
+++ b/packages/prisma/schema/discount.prisma
@@ -1,21 +1,42 @@
model Discount {
- id String @id @default(cuid())
+ id String @id @default(cuid())
- amount Int @default(0)
- type CommissionType @default(percentage)
- duration Int?
- interval CommissionInterval?
- couponId String?
- couponTestId String?
+ amount Int @default(0)
+ type CommissionType @default(percentage)
+ maxDuration Int? // in months (0 -> not recurring, null -> lifetime)
- workspaceId String
- programId String
+ couponId String?
+ couponTestId String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ workspaceId String
+ programId String
- program Program @relation(fields: [programId], references: [id])
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ program Program @relation(fields: [programId], references: [id])
programEnrollments ProgramEnrollment[]
+ partners PartnerDiscount[]
+
+ // TO be removed
+ duration Int?
+ interval CommissionInterval?
+
+ @@index(programId)
+}
+
+model PartnerDiscount {
+ id String @id @default(cuid())
+ programEnrollmentId String
+ discountId String
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ programEnrollment ProgramEnrollment @relation(fields: [programEnrollmentId], references: [id], onDelete: Cascade)
+ discount Discount @relation(fields: [discountId], references: [id], onDelete: Cascade)
- @@index([programId])
+ @@unique([programEnrollmentId, discountId])
+ @@index(programEnrollmentId)
+ @@index(discountId)
}
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 726eea1c5c..c173ee4f6a 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -39,6 +39,7 @@ model Program {
cookieLength Int @default(90)
holdingPeriodDays Int @default(0) // number of days to wait before earnings are added to a payout
defaultRewardId String? // default reward for the program
+ defaultDiscountId String? // default discount for the program
landerData Json? @db.Json
// Commission details
@@ -87,6 +88,7 @@ model ProgramEnrollment {
discount Discount? @relation(fields: [discountId], references: [id])
application ProgramApplication? @relation(fields: [applicationId], references: [id])
rewards PartnerReward[]
+ discounts PartnerDiscount[]
@@unique([partnerId, programId])
@@unique([tenantId, programId])