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.

Drop unused reward/discount endpoints and support additional group discounts.

Kiran K1efe4753e443
diff --git a/apps/web/app/(ee)/api/discounts/route.ts b/apps/web/app/(ee)/api/discounts/route.ts
index dcfcf034e8..1d0e6c93cb 100644
--- a/apps/web/app/(ee)/api/discounts/route.ts
+++ b/apps/web/app/(ee)/api/discounts/route.ts
@@ -1,19 +1,11 @@
-import { listDiscounts } from "@/lib/api/discounts/list-discounts";
-import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { withWorkspace } from "@/lib/auth";
import {
- DiscountSchema,
getDiscountsQuerySchema,
-} from "@/lib/zod/schemas/discount";
+ listDiscounts,
+ listDiscountsResponseSchema,
+} from "@/lib/api/discounts/list-discounts";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
import { NextResponse } from "next/server";
-import * as z from "zod/v4";
-
-const responseSchema = z.array(
- DiscountSchema.extend({
- groupId: z.string().nullable(),
- partnersCount: z.number(),
- }),
-);
// GET /api/discounts - get all discounts for a program
export const GET = withWorkspace(async ({ workspace, searchParams }) => {
@@ -25,5 +17,5 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
groupId,
});
- return NextResponse.json(responseSchema.parse(discounts));
+ return NextResponse.json(listDiscountsResponseSchema.parse(discounts));
});
diff --git a/apps/web/app/(ee)/api/programs/[programId]/discounts/route.ts b/apps/web/app/(ee)/api/programs/[programId]/discounts/route.ts
deleted file mode 100644
index eb1cc96d26..0000000000
--- a/apps/web/app/(ee)/api/programs/[programId]/discounts/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { withWorkspace } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
-import { DiscountSchema } from "@/lib/zod/schemas/discount";
-import { NextResponse } from "next/server";
-import * as z from "zod/v4";
-
-// TODO: Remove once we migrate fully to partner groups
-// GET /api/programs/[programId]/discounts - get all discounts for a program
-export const GET = withWorkspace(async ({ workspace }) => {
- const programId = getDefaultProgramIdOrThrow(workspace);
-
- const discounts = await prisma.discount.findMany({
- where: {
- programId,
- },
- include: {
- _count: {
- select: {
- programEnrollments: true,
- },
- },
- },
- orderBy: {
- createdAt: "desc",
- },
- });
-
- const discountsWithPartnersCount = discounts.map((discount) => ({
- ...discount,
- partnersCount: discount._count.programEnrollments,
- }));
-
- return NextResponse.json(
- z.array(DiscountSchema).parse(discountsWithPartnersCount),
- );
-});
diff --git a/apps/web/app/(ee)/api/rewards/[rewardId]/route.ts b/apps/web/app/(ee)/api/rewards/[rewardId]/route.ts
deleted file mode 100644
index a54acc9da0..0000000000
--- a/apps/web/app/(ee)/api/rewards/[rewardId]/route.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { DubApiError } from "@/lib/api/errors";
-import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { withWorkspace } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
-import { RewardSchema } from "@/lib/zod/schemas/rewards";
-import { NextResponse } from "next/server";
-
-export const GET = withWorkspace(async ({ workspace, params }) => {
- const programId = getDefaultProgramIdOrThrow(workspace);
-
- const reward = await prisma.reward.findUnique({
- where: {
- id: params.rewardId,
- programId,
- },
- });
-
- if (!reward) {
- throw new DubApiError({
- code: "not_found",
- message: "Reward not found.",
- });
- }
-
- return NextResponse.json(RewardSchema.parse(reward));
-});
diff --git a/apps/web/app/(ee)/api/rewards/route.ts b/apps/web/app/(ee)/api/rewards/route.ts
index f7e7c19cc6..2dce04e10f 100644
--- a/apps/web/app/(ee)/api/rewards/route.ts
+++ b/apps/web/app/(ee)/api/rewards/route.ts
@@ -1,16 +1,11 @@
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { listRewards } from "@/lib/api/rewards/list-rewards";
+import {
+ getRewardsQuerySchema,
+ listRewards,
+ listRewardsResponseSchema,
+} from "@/lib/api/rewards/list-rewards";
import { withWorkspace } from "@/lib/auth";
-import { getRewardsQuerySchema, RewardSchema } from "@/lib/zod/schemas/rewards";
import { NextResponse } from "next/server";
-import * as z from "zod/v4";
-
-const responseSchema = z.array(
- RewardSchema.extend({
- groupId: z.string().nullable(),
- partnersCount: z.number(),
- }),
-);
// GET /api/rewards - get all rewards for a program
export const GET = withWorkspace(async ({ workspace, searchParams }) => {
@@ -22,5 +17,5 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
groupId,
});
- return NextResponse.json(responseSchema.parse(rewards));
+ return NextResponse.json(listRewardsResponseSchema.parse(rewards));
});
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 75dbb69e7f..990567ed99 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -6,7 +6,10 @@ import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { qstash } from "@/lib/cron";
import { getDiscountProvider } from "@/lib/discounts/discount-provider";
+import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
+import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";
import { DubDiscountAttributes } from "@/lib/stripe/coupon-discount-converter";
import { createDiscountSchema } from "@/lib/zod/schemas/discount";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -28,6 +31,7 @@ export const createDiscountAction = authActionClient
couponTestId,
groupId,
autoProvision,
+ isDefault,
} = parsedInput;
throwIfNoPermission({
@@ -35,6 +39,13 @@ export const createDiscountAction = authActionClient
requiredRoles: ["owner", "member"],
});
+ if (
+ !isDefault &&
+ !getPlanCapabilities(workspace.plan).canUseAdvancedRewardLogic
+ ) {
+ throw new Error(PARTNER_LEVEL_REWARDS_PLAN_ERROR);
+ }
+
const programId = getDefaultProgramIdOrThrow(workspace);
const group = await getGroupOrThrow({
@@ -42,10 +53,8 @@ export const createDiscountAction = authActionClient
programId,
});
- if (group.discountId) {
- throw new Error(
- `You can't create a discount for this group because it already has a discount.`,
- );
+ if (isDefault && group.discountId) {
+ throw new Error("This group already has a default discount.");
}
const discountProvider = getDiscountProvider(provider);
@@ -78,6 +87,7 @@ export const createDiscountAction = authActionClient
data: {
id: createId({ prefix: "disc_" }),
programId,
+ groupId,
amount,
type,
maxDuration,
@@ -92,46 +102,64 @@ export const createDiscountAction = authActionClient
},
});
- await tx.partnerGroup.update({
- where: {
- id: groupId,
- },
- data: {
- discountId: discount.id,
- },
- });
+ // Assign to the group if it is the default discount
+ if (isDefault) {
+ const { count } = await tx.partnerGroup.updateMany({
+ where: {
+ id: groupId,
+ discountId: null,
+ },
+ data: {
+ discountId: discount.id,
+ },
+ });
- await tx.programEnrollment.updateMany({
- where: {
- groupId,
- },
- data: {
- discountId: discount.id,
- },
- });
+ // This means that the group already has a default discount
+ if (count === 0) {
+ throw new Error("This group already has a default discount.");
+ }
- await tx.discountCode.updateMany({
- where: {
- programEnrollment: {
+ await tx.discountCode.updateMany({
+ where: {
+ programEnrollment: {
+ groupId,
+ discountId: null,
+ },
+ },
+ data: {
+ discountId: discount.id,
+ },
+ });
+
+ await tx.programEnrollment.updateMany({
+ where: {
groupId,
+ discountId: null,
},
- },
- data: {
- discountId: discount.id,
- },
- });
+ data: {
+ discountId: discount.id,
+ },
+ });
+ }
return discount;
});
waitUntil(
Promise.allSettled([
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- groupId,
- },
- }),
+ ...(isDefault
+ ? [
+ invalidateLinksForDiscountsJob.dispatch(
+ {
+ type: "discount",
+ discountId: discount.id,
+ },
+ {
+ label: discount.id,
+ },
+ ),
+ ]
+ : []),
recordAuditLog({
workspaceId: workspace.id,
@@ -160,4 +188,8 @@ export const createDiscountAction = authActionClient
: []),
]),
);
+
+ return {
+ id: discount.id,
+ };
});
diff --git a/apps/web/lib/actions/partners/create-program.ts b/apps/web/lib/actions/partners/create-program.ts
index daab6a29fe..e138ad47c2 100644
--- a/apps/web/lib/actions/partners/create-program.ts
+++ b/apps/web/lib/actions/partners/create-program.ts
@@ -155,6 +155,7 @@ export const createProgram = async ({
rewards: {
create: {
id: createId({ prefix: "rw_" }),
+ groupId: defaultGroupId,
type,
amountInCents: type === "flat" ? amountInCents : null,
amountInPercentage:
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index f141234bb9..fdc4e67767 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -3,10 +3,10 @@
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 { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";
+import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
import { prisma } from "@/lib/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { pluck } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
@@ -45,17 +45,28 @@ export const deleteDiscountAction = authActionClient
},
});
- const group = await prisma.$transaction(async (tx) => {
- const group = await tx.partnerGroup.update({
- where: {
- discountId: discount.id,
- },
- data: {
- discountId: null,
- },
- });
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ discountId: discount.id,
+ },
+ select: {
+ partnerId: true,
+ },
+ });
- await tx.programEnrollment.updateMany({
+ await prisma.$transaction(async (tx) => {
+ const partnerGroup = discount.groupId
+ ? await tx.partnerGroup.findUnique({
+ where: {
+ id: discount.groupId,
+ },
+ select: {
+ discountId: true,
+ },
+ })
+ : null;
+
+ await tx.partnerGroup.updateMany({
where: {
discountId: discount.id,
},
@@ -64,12 +75,13 @@ export const deleteDiscountAction = authActionClient
},
});
- await tx.discountCode.updateMany({
+ // Restore enrollments to the group level discount, or clear them if none
+ await tx.programEnrollment.updateMany({
where: {
discountId: discount.id,
},
data: {
- discountId: null,
+ discountId: partnerGroup?.discountId ?? null,
},
});
@@ -78,18 +90,26 @@ export const deleteDiscountAction = authActionClient
id: discount.id,
},
});
-
- return group;
});
+ const partnerIds = pluck(enrollments, "partnerId");
+
waitUntil(
Promise.allSettled([
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- groupId: group.id,
- },
- }),
+ ...(partnerIds.length > 0
+ ? [
+ invalidateLinksForDiscountsJob.dispatch(
+ {
+ type: "partners",
+ partnerIds,
+ programId,
+ },
+ {
+ label: discountId,
+ },
+ ),
+ ]
+ : []),
deleteDiscountCodes(discountCodes),
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index b83a31d99d..7a190c2dbd 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -5,6 +5,7 @@ import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { revalidateProgramPublicPages } from "@/lib/api/programs/revalidate-program-public-pages";
import { qstash } from "@/lib/cron";
+import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
import { prisma } from "@/lib/prisma";
import { updateDiscountSchema } from "@/lib/zod/schemas/discount";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -30,7 +31,7 @@ export const updateDiscountAction = authActionClient
discountId,
});
- const { partnerGroup, ...updatedDiscount } = await prisma.discount.update({
+ const updatedDiscount = await prisma.discount.update({
where: {
id: discountId,
},
@@ -42,9 +43,6 @@ export const updateDiscountAction = authActionClient
: null,
}),
},
- include: {
- partnerGroup: true,
- },
});
const shouldExpireCache =
@@ -55,45 +53,46 @@ export const updateDiscountAction = authActionClient
}
waitUntil(
- (async () => {
- await Promise.allSettled([
- ...(shouldExpireCache
- ? [
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- groupId: partnerGroup?.id,
- },
- }),
- ]
- : []),
+ Promise.allSettled([
+ ...(shouldExpireCache
+ ? [
+ invalidateLinksForDiscountsJob.dispatch(
+ {
+ type: "discount",
+ discountId: discount.id,
+ },
+ {
+ label: discount.id,
+ },
+ ),
+ ]
+ : []),
- ...(updatedDiscount.autoProvisionEnabledAt
- ? [
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/create/queue-batches`,
- body: {
- discountId: discount.id,
- },
- }),
- ]
- : []),
+ ...(updatedDiscount.autoProvisionEnabledAt
+ ? [
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/create/queue-batches`,
+ body: {
+ discountId: discount.id,
+ },
+ }),
+ ]
+ : []),
- recordAuditLog({
- workspaceId: workspace.id,
- programId,
- action: "discount.updated",
- description: `Discount ${discount.id} updated`,
- actor: user,
- targets: [
- {
- type: "discount",
- id: discount.id,
- metadata: updatedDiscount,
- },
- ],
- }),
- ]);
- })(),
+ 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/discounts/list-discounts.ts b/apps/web/lib/api/discounts/list-discounts.ts
index 15d5dc5513..f6bd425c09 100644
--- a/apps/web/lib/api/discounts/list-discounts.ts
+++ b/apps/web/lib/api/discounts/list-discounts.ts
@@ -1,10 +1,23 @@
import { prisma } from "@/lib/prisma";
+import { DiscountSchema } from "@/lib/zod/schemas/discount";
import { Prisma, type Discount } from "@prisma/client";
+import * as z from "zod/v4";
type DiscountRow = Discount & {
partnersCount: bigint | number;
};
+export const getDiscountsQuerySchema = z.object({
+ groupId: z.string().nullish(),
+});
+
+export const listDiscountsResponseSchema = z.array(
+ DiscountSchema.extend({
+ groupId: z.string().nullable(),
+ partnersCount: z.number(),
+ }),
+);
+
// Lists program discounts (optionally filtered by group) with a partnersCount.
export async function listDiscounts({
programId,
diff --git a/apps/web/lib/api/rewards/list-rewards.ts b/apps/web/lib/api/rewards/list-rewards.ts
index 99714c1413..43451e8b4e 100644
--- a/apps/web/lib/api/rewards/list-rewards.ts
+++ b/apps/web/lib/api/rewards/list-rewards.ts
@@ -1,5 +1,18 @@
import { prisma } from "@/lib/prisma";
+import { RewardSchema } from "@/lib/zod/schemas/rewards";
import { Prisma, type Reward } from "@prisma/client";
+import * as z from "zod/v4";
+
+export const getRewardsQuerySchema = z.object({
+ groupId: z.string().nullish(),
+});
+
+export const listRewardsResponseSchema = z.array(
+ RewardSchema.extend({
+ groupId: z.string().nullable(),
+ partnersCount: z.number(),
+ }),
+);
type RewardRow = Reward & {
partnersCount: bigint | number;
diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.ts
index 8a8b0fbe1e..b51405a8df 100644
--- a/apps/web/lib/zod/schemas/discount.ts
+++ b/apps/web/lib/zod/schemas/discount.ts
@@ -41,10 +41,6 @@ export const createDiscountSchema = z.object({
isDefault: z.boolean().default(true),
});
-export const getDiscountsQuerySchema = z.object({
- groupId: z.string().nullish(),
-});
-
export const updateDiscountSchema = createDiscountSchema
.pick({
workspaceId: true,
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 83f5409f3c..a67f052b85 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -426,10 +426,6 @@ const decimalToNumber = z
.nullable()
.optional();
-export const getRewardsQuerySchema = z.object({
- groupId: z.string().nullish(),
-});
-
export const RewardSchema = z.object({
id: z.string(),
event: z.enum(EventType),