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 reward schemas and routes with improved type handling

Kiran Kf903263ca26f
diff --git a/apps/web/app/api/programs/[programId]/rewards/[rewardId]/route.ts b/apps/web/app/api/programs/[programId]/rewards/[rewardId]/route.ts
new file mode 100644
index 0000000000..6c3abe8967
--- /dev/null
+++ b/apps/web/app/api/programs/[programId]/rewards/[rewardId]/route.ts
@@ -0,0 +1,106 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { rewardSchema, updateRewardSchema } from "@/lib/zod/schemas/rewards";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// PATCH /api/programs/[programId]/rewards/[rewardId] - update a reward
+export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
+ const { programId, rewardId } = params;
+
+ await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ await prisma.reward.findUniqueOrThrow({
+ where: {
+ id: rewardId,
+ programId,
+ },
+ });
+
+ const { partnerIds, ...data } = updateRewardSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ if (partnerIds) {
+ const partners = await prisma.programEnrollment.findMany({
+ where: {
+ programId,
+ partnerId: {
+ in: partnerIds,
+ },
+ },
+ });
+
+ if (partners.length !== partnerIds.length) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid partner IDs provided.",
+ });
+ }
+ }
+
+ const reward = await prisma.reward.update({
+ where: {
+ id: rewardId,
+ },
+ data: {
+ ...data,
+ ...(partnerIds && {
+ partners: {
+ deleteMany: {},
+ createMany: {
+ data: partnerIds.map((partnerId) => ({
+ partnerId,
+ programId,
+ })),
+ },
+ },
+ }),
+ },
+ });
+
+ // TODO:
+ // Send an email to the partners about the reward being updated.
+
+ return NextResponse.json(rewardSchema.parse(reward));
+});
+
+// DELETE /api/programs/[programId]/rewards/[rewardId] - delete a reward
+export const DELETE = withWorkspace(async ({ workspace, params }) => {
+ const { programId, rewardId } = params;
+
+ const program = await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ await prisma.reward.findUniqueOrThrow({
+ where: {
+ id: rewardId,
+ programId,
+ },
+ });
+
+ if (program.defaultRewardId === rewardId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Default reward cannot be deleted.",
+ });
+ }
+
+ await prisma.reward.delete({
+ where: {
+ id: rewardId,
+ },
+ });
+
+ // TODO:
+ // Send an email to the partners about the reward being deleted.
+
+ return NextResponse.json({ id: rewardId });
+});
diff --git a/apps/web/app/api/programs/[programId]/rewards/route.ts b/apps/web/app/api/programs/[programId]/rewards/route.ts
index c723ec03ba..8407c94302 100644
--- a/apps/web/app/api/programs/[programId]/rewards/route.ts
+++ b/apps/web/app/api/programs/[programId]/rewards/route.ts
@@ -64,7 +64,7 @@ export const POST = withWorkspace(async ({ workspace, params, req }) => {
});
}
- if (data.type !== "sale") {
+ if (data.event !== "sale") {
throw new DubApiError({
code: "bad_request",
message: "Default reward must be of type `sale`.",
@@ -113,5 +113,8 @@ export const POST = withWorkspace(async ({ workspace, params, req }) => {
});
}
+ // TODO:
+ // Send an email to the partners about the reward being created.
+
return NextResponse.json(rewardSchema.parse(reward));
});
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 0d20d79ad7..30634f2258 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -5,8 +5,8 @@ export const rewardSchema = z.object({
id: z.string(),
programId: z.string(),
name: z.string().nullable(),
- type: z.nativeEnum(EventType),
- rewardType: z.nativeEnum(CommissionType),
+ event: z.nativeEnum(EventType),
+ type: z.nativeEnum(CommissionType),
amount: z.number(),
duration: z.number().nullable(),
interval: z.nativeEnum(CommissionInterval).nullable(),
@@ -14,13 +14,47 @@ export const rewardSchema = z.object({
updatedAt: z.date(),
});
-export const createRewardSchema = z.object({
- name: z.string().max(190).nullish(),
- type: z.nativeEnum(EventType),
- rewardType: z.nativeEnum(CommissionType).default(CommissionType.percentage),
+export const createOrUpdateRewardSchema = z.object({
+ event: z.nativeEnum(EventType),
+ type: z.nativeEnum(CommissionType).default("flat"),
amount: z.number().int().min(0),
duration: z.number().int().positive().nullish(),
interval: z.nativeEnum(CommissionInterval).nullish(),
partnerIds: z.array(z.string()).nullish(),
isDefault: z.boolean().default(false),
});
+
+export const createRewardSchema = createOrUpdateRewardSchema.superRefine(
+ (data, ctx) => {
+ if (data.event !== EventType.sale) {
+ if (data.duration) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Duration is only allowed for sale rewards.",
+ path: ["duration"],
+ });
+ }
+
+ if (data.interval) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Interval is only allowed for sale rewards.",
+ });
+ }
+
+ if (data.type !== "flat") {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Type must be flat for ${data.event} rewards.`,
+ });
+ }
+ }
+ },
+);
+
+export const updateRewardSchema = createOrUpdateRewardSchema
+ .omit({
+ event: true,
+ isDefault: true,
+ })
+ .partial();
diff --git a/packages/prisma/schema/reward.prisma b/packages/prisma/schema/reward.prisma
index 1f872d962a..69f9ce2f78 100644
--- a/packages/prisma/schema/reward.prisma
+++ b/packages/prisma/schema/reward.prisma
@@ -2,12 +2,12 @@ model Reward {
id String @id @default(cuid())
programId String
- name String?
- type EventType
- rewardType CommissionType @default(percentage) // TODO: Can we do something better here?
- amount Int @default(0)
- duration Int?
- interval CommissionInterval?
+ name String?
+ event EventType
+ type CommissionType @default(percentage)
+ amount Int @default(0)
+ duration Int?
+ interval CommissionInterval?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt