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.

Allow additional rewards and discounts to be assigned per partner.

Kiran K525496e58121
diff --git a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
index 667ea3ac67..aa11b873b9 100644
--- a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
+++ b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
@@ -1,8 +1,6 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { linkCache } from "@/lib/api/links/cache";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { withCron } from "@/lib/cron/with-cron";
+import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
import { prisma } from "@/lib/prisma";
-import { chunk } from "@dub/utils";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -18,72 +16,49 @@ const schema = z.object({
),
});
-// This route is used to invalidate the partnerlink cache when a discount is created/updated/deleted.
+// Shim for in-flight QStash messages published to the old cron URL.
+// New callers should dispatch invalidateLinksForDiscountsJob.
// POST /api/cron/links/invalidate-for-discounts
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
+export const POST = withCron(async ({ rawBody }) => {
+ const { groupId, partnerIds } = schema.parse(JSON.parse(rawBody));
- const { groupId, partnerIds } = schema.parse(JSON.parse(rawBody));
+ const group = await prisma.partnerGroup.findUnique({
+ where: {
+ id: groupId,
+ },
+ select: {
+ programId: true,
+ },
+ });
- // Find the group
- const group = await prisma.partnerGroup.findUnique({
- where: {
- id: groupId,
- },
+ if (!group) {
+ return logAndRespond(`Group ${groupId} not found.`, {
+ logLevel: "error",
});
+ }
- if (!group) {
- return logAndRespond(`Group ${groupId} not found.`, {
- logLevel: "error",
- });
- }
-
- // Find all the links of the partners in the group
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- groupId,
- ...(partnerIds && {
- partnerId: {
- in: partnerIds,
- },
- }),
- },
- select: {
- links: {
- select: {
- domain: true,
- key: true,
- },
+ const resolvedPartnerIds =
+ partnerIds ??
+ (
+ await prisma.programEnrollment.findMany({
+ where: {
+ groupId,
},
- },
- });
-
- if (programEnrollments.length === 0) {
- return logAndRespond(
- `No program enrollments found for group ${groupId}.`,
- );
- }
-
- const links = programEnrollments.flatMap((enrollment) => enrollment.links);
-
- if (links.length === 0) {
- return logAndRespond(
- `No links found for partners in the group ${groupId}.`,
- );
- }
+ select: {
+ partnerId: true,
+ },
+ })
+ ).map(({ partnerId }) => partnerId);
- const linkChunks = chunk(links, 100);
+ if (resolvedPartnerIds.length === 0) {
+ return logAndRespond(`No program enrollments found for group ${groupId}.`);
+ }
- // Expire the cache for the links
- for (const linkChunk of linkChunks) {
- const toExpire = linkChunk.map(({ domain, key }) => ({ domain, key }));
- await linkCache.expireMany(toExpire);
- }
+ await invalidateLinksForDiscountsJob.dispatch({
+ type: "partners",
+ programId: group.programId,
+ partnerIds: resolvedPartnerIds,
+ });
- return logAndRespond(`Expired cache for ${links.length} links.`);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
+ return logAndRespond(`Expired cache for partners in group ${groupId}.`);
+});
diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.ts
index 948315c6c1..493e4b740a 100644
--- a/apps/web/lib/actions/partners/create-reward.ts
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -10,6 +10,7 @@ import { queueRewardProcessing } from "@/lib/api/rewards/queue-reward-processing
import { validateReward } from "@/lib/api/rewards/validate-reward";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
+import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";
import {
createRewardSchema,
REWARD_EVENT_COLUMN_MAPPING,
@@ -38,6 +39,7 @@ export const createRewardAction = authActionClient
spendLimitAmount,
spendLimitInterval,
activityDescription,
+ isDefault,
} = parsedInput;
throwIfNoPermission({
@@ -58,6 +60,10 @@ export const createRewardAction = authActionClient
);
}
+ if (!isDefault && !canUseAdvancedRewardLogic) {
+ throw new Error(PARTNER_LEVEL_REWARDS_PLAN_ERROR);
+ }
+
if (modifiers && !canUseAdvancedRewardLogic) {
throw new Error(
"Advanced reward structures are only available on the Advanced plan and above.",
@@ -77,10 +83,8 @@ export const createRewardAction = authActionClient
const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
- if (group[rewardIdColumn]) {
- throw new Error(
- `You can't create a ${event} reward for this group because it already has a ${event} reward.`,
- );
+ if (isDefault && group[rewardIdColumn]) {
+ throw new Error(`This group already has a default ${event} reward.`);
}
validateReward(parsedInput);
@@ -90,6 +94,7 @@ export const createRewardAction = authActionClient
data: {
id: createId({ prefix: "rw_" }),
programId,
+ groupId,
event,
type,
maxDuration,
@@ -111,31 +116,41 @@ export const createRewardAction = authActionClient
},
});
- await tx.partnerGroup.update({
- where: {
- id: groupId,
- },
- data: {
- [rewardIdColumn]: reward.id,
- },
- });
+ if (isDefault) {
+ const { count } = await tx.partnerGroup.updateMany({
+ where: {
+ id: groupId,
+ [rewardIdColumn]: null,
+ },
+ data: {
+ [rewardIdColumn]: reward.id,
+ },
+ });
+
+ // This means that the group already has a default reward
+ if (count === 0) {
+ throw new Error(`This group already has a default ${event} reward.`);
+ }
+ }
return reward;
});
- await queueRewardProcessing({
- event: "reward-created",
- groupId,
- occurredAt: new Date().toISOString(),
- rewardSnapshot: {
- id: reward.id,
- event: reward.event,
- description: formatRewardDescription(serializeReward(reward), {
- includeEarnPrefix: false,
- }),
- activityDescription,
- },
- });
+ if (isDefault) {
+ await queueRewardProcessing({
+ event: "reward-created",
+ groupId,
+ occurredAt: new Date().toISOString(),
+ rewardSnapshot: {
+ id: reward.id,
+ event: reward.event,
+ description: formatRewardDescription(serializeReward(reward), {
+ includeEarnPrefix: false,
+ }),
+ activityDescription,
+ },
+ });
+ }
waitUntil(
Promise.allSettled([
@@ -167,4 +182,8 @@ export const createRewardAction = authActionClient
}),
]),
);
+
+ return {
+ id: reward.id,
+ };
});
diff --git a/apps/web/lib/actions/partners/delete-reward.ts b/apps/web/lib/actions/partners/delete-reward.ts
index 20d05018b1..cfffc56c0f 100644
--- a/apps/web/lib/actions/partners/delete-reward.ts
+++ b/apps/web/lib/actions/partners/delete-reward.ts
@@ -44,49 +44,51 @@ export const deleteRewardAction = authActionClient
const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[reward.event];
- const { partnerGroup, deletedReward } = await prisma.$transaction(
- async (tx) => {
- const partnerGroup = await tx.partnerGroup.update({
- // @ts-ignore
+ const group = reward.groupId
+ ? await prisma.partnerGroup.findUnique({
where: {
- [rewardIdColumn]: reward.id,
+ id: reward.groupId,
},
- data: {
- [rewardIdColumn]: null,
- },
- });
-
- // soft delete reward, we will hard delete it in the cron job
- const deletedReward = await tx.reward.update({
- where: {
- id: reward.id,
- },
- data: {
- programId: null,
- },
- });
+ })
+ : null;
- return {
- partnerGroup,
- deletedReward,
- };
- },
- );
+ await prisma.$transaction(async (tx) => {
+ await tx.partnerGroup.updateMany({
+ where: {
+ [rewardIdColumn]: reward.id,
+ },
+ data: {
+ [rewardIdColumn]: null,
+ },
+ });
- await queueRewardProcessing({
- event: "reward-deleted",
- groupId: partnerGroup.id,
- occurredAt: new Date().toISOString(),
- rewardSnapshot: {
- id: deletedReward.id,
- event: deletedReward.event,
- description: formatRewardDescription(serializeReward(deletedReward), {
- includeEarnPrefix: false,
- }),
- activityDescription,
- },
+ // soft delete reward, we will hard delete it in the cron job
+ await tx.reward.update({
+ where: {
+ id: reward.id,
+ },
+ data: {
+ programId: null,
+ },
+ });
});
+ if (group) {
+ await queueRewardProcessing({
+ event: "reward-deleted",
+ groupId: group.id,
+ occurredAt: new Date().toISOString(),
+ rewardSnapshot: {
+ id: reward.id,
+ event: reward.event,
+ description: formatRewardDescription(serializeReward(reward), {
+ includeEarnPrefix: false,
+ }),
+ activityDescription,
+ },
+ });
+ }
+
waitUntil(
Promise.allSettled([
recordAuditLog({
@@ -99,7 +101,7 @@ export const deleteRewardAction = authActionClient
{
type: "reward",
id: rewardId,
- metadata: reward,
+ metadata: serializeReward(reward),
},
],
}),
@@ -110,7 +112,7 @@ export const deleteRewardAction = authActionClient
userId: user.id,
resourceId: reward.id,
parentResourceType: "group",
- parentResourceId: partnerGroup.id,
+ parentResourceId: group?.id ?? reward.groupId,
old: reward,
new: null,
description: activityDescription,
diff --git a/apps/web/lib/actions/partners/update-partner-enrollment.ts b/apps/web/lib/actions/partners/update-partner-enrollment.ts
index 8eb98a3521..74dd70e66e 100644
--- a/apps/web/lib/actions/partners/update-partner-enrollment.ts
+++ b/apps/web/lib/actions/partners/update-partner-enrollment.ts
@@ -1,27 +1,59 @@
"use server";
+import { trackPartnerRewardOverrideLog } from "@/lib/api/activity-log/track-reward-overrides";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { linkCache } from "@/lib/api/links/cache";
import { includeProgramEnrollment } from "@/lib/api/links/include-program-enrollment";
import { includeTags } from "@/lib/api/links/include-tags";
+import { notifyPartnerRewardOverride } from "@/lib/api/partners/notify-partner-reward-change";
import { queuePartnerSearchSync } from "@/lib/api/partners/queue-partner-search-sync";
import { throwIfExistingTenantEnrollmentExists } from "@/lib/api/partners/throw-if-existing-tenant-id-exists";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { hasRewardAssignment } from "@/lib/api/rewards/reward-overrides";
+import { throwIfInvalidRewards } from "@/lib/api/rewards/throw-if-invalid-rewards";
+import { remapDiscountCodesForPartnerJob } from "@/lib/jobs/handlers/remap-discount-codes-for-partner-job";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
+import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";
import { recordLink } from "@/lib/tinybird";
+import { rewardActivityDescriptionSchema } from "@/lib/zod/schemas/rewards";
+import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
import { throwIfNoPermission } from "../throw-if-no-permission";
-const updatePartnerEnrollmentSchema = z.object({
- workspaceId: z.string(),
- partnerId: z.string(),
- tenantId: z.string().nullable(),
- customerDataSharingEnabledAt: z.coerce.date().nullable(),
- groupMoveDisabledAt: z.coerce.date().nullable(),
- riskMonitoringDisabledAt: z.coerce.date().nullable(),
-});
+const updatePartnerEnrollmentSchema = z
+ .object({
+ workspaceId: z.string(),
+ partnerId: z.string(),
+ tenantId: z.string().nullable().optional(),
+ customerDataSharingEnabledAt: z.coerce.date().nullable().optional(),
+ groupMoveDisabledAt: z.coerce.date().nullable().optional(),
+ riskMonitoringDisabledAt: z.coerce.date().nullable().optional(),
+ clickRewardId: z.string().nullish(),
+ leadRewardId: z.string().nullish(),
+ saleRewardId: z.string().nullish(),
+ discountId: z.string().nullish(),
+ })
+ .extend(rewardActivityDescriptionSchema.shape)
+ .refine(
+ (data) =>
+ [
+ data.tenantId,
+ data.customerDataSharingEnabledAt,
+ data.groupMoveDisabledAt,
+ data.riskMonitoringDisabledAt,
+ data.clickRewardId,
+ data.leadRewardId,
+ data.saleRewardId,
+ data.discountId,
+ ].some((value) => value !== undefined),
+ {
+ message: "At least one enrollment field must be provided.",
+ },
+ );
// Update a partner's program enrollment data
export const updatePartnerEnrollmentAction = authActionClient
@@ -29,11 +61,14 @@ export const updatePartnerEnrollmentAction = authActionClient
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
const {
+ workspaceId,
partnerId,
tenantId,
customerDataSharingEnabledAt,
groupMoveDisabledAt,
riskMonitoringDisabledAt,
+ activityDescription,
+ ...rewardIds
} = parsedInput;
throwIfNoPermission({
@@ -43,14 +78,28 @@ export const updatePartnerEnrollmentAction = authActionClient
const programId = getDefaultProgramIdOrThrow(workspace);
- const { partner, tenantId: existingTenantId } =
- await getProgramEnrollmentOrThrow({
- partnerId,
- programId,
- include: {
- partner: true,
- },
- });
+ if (
+ hasRewardAssignment(rewardIds) &&
+ !getPlanCapabilities(workspace.plan).canUseAdvancedRewardLogic
+ ) {
+ throw new Error(PARTNER_LEVEL_REWARDS_PLAN_ERROR);
+ }
+
+ const {
+ partner,
+ tenantId: existingTenantId,
+ groupId,
+ clickRewardId: existingClickRewardId,
+ leadRewardId: existingLeadRewardId,
+ saleRewardId: existingSaleRewardId,
+ discountId: existingDiscountId,
+ } = await getProgramEnrollmentOrThrow({
+ partnerId,
+ programId,
+ include: {
+ partner: true,
+ },
+ });
const where = {
programId,
@@ -64,24 +113,44 @@ export const updatePartnerEnrollmentAction = authActionClient
});
}
+ await throwIfInvalidRewards({
+ programId,
+ groupId,
+ ...rewardIds,
+ });
+
+ const { clickRewardId, leadRewardId, saleRewardId, discountId } = rewardIds;
+
+ const enrollmentData: Prisma.ProgramEnrollmentUpdateInput = {
+ ...(tenantId !== undefined && { tenantId }),
+ ...(customerDataSharingEnabledAt !== undefined && {
+ customerDataSharingEnabledAt,
+ }),
+ ...(groupMoveDisabledAt !== undefined && { groupMoveDisabledAt }),
+ ...(riskMonitoringDisabledAt !== undefined && {
+ riskMonitoringDisabledAt,
+ }),
+ ...(clickRewardId !== undefined && { clickRewardId }),
+ ...(leadRewardId !== undefined && { leadRewardId }),
+ ...(saleRewardId !== undefined && { saleRewardId }),
+ ...(discountId !== undefined && { discountId }),
+ };
+
const programEnrollment = await prisma.$transaction(async (tx) => {
- await tx.link.updateMany({
- where,
- data: {
- tenantId,
- },
- });
+ if (tenantId !== undefined) {
+ await tx.link.updateMany({
+ where,
+ data: {
+ tenantId,
+ },
+ });
+ }
return await tx.programEnrollment.update({
where: {
partnerId_programId: where,
},
- data: {
- tenantId,
- customerDataSharingEnabledAt,
- groupMoveDisabledAt,
- riskMonitoringDisabledAt,
- },
+ data: enrollmentData,
include: {
links: {
include: {
@@ -93,13 +162,69 @@ export const updatePartnerEnrollmentAction = authActionClient
});
});
+ if (discountId !== undefined) {
+ await remapDiscountCodesForPartnerJob.dispatch(
+ {
+ programId,
+ partnerId,
+ },
+ {
+ label: partnerId,
+ },
+ );
+ }
+
waitUntil(
Promise.allSettled([
- recordLink(programEnrollment.links),
+ ...(tenantId !== undefined
+ ? [recordLink(programEnrollment.links)]
+ : []),
+
+ ...(hasRewardAssignment(rewardIds)
+ ? [linkCache.expireMany(programEnrollment.links)]
+ : []),
+
// Queue an index update because the tenant ID changed
- ...(tenantId !== existingTenantId
+ ...(tenantId !== undefined && tenantId !== existingTenantId
? [queuePartnerSearchSync({ enrollmentIds: [programEnrollment.id] })]
: []),
+
+ trackPartnerRewardOverrideLog({
+ workspaceId: workspace.id,
+ programId,
+ partnerId,
+ userId: user.id,
+ description: activityDescription,
+ previous: {
+ clickRewardId: existingClickRewardId,
+ leadRewardId: existingLeadRewardId,
+ saleRewardId: existingSaleRewardId,
+ discountId: existingDiscountId,
+ },
+ next: {
+ clickRewardId: programEnrollment.clickRewardId,
+ leadRewardId: programEnrollment.leadRewardId,
+ saleRewardId: programEnrollment.saleRewardId,
+ discountId: programEnrollment.discountId,
+ },
+ }),
+
+ notifyPartnerRewardOverride({
+ programId,
+ partnerId,
+ previous: {
+ clickRewardId: existingClickRewardId,
+ leadRewardId: existingLeadRewardId,
+ saleRewardId: existingSaleRewardId,
+ },
+ next: {
+ clickRewardId: programEnrollment.clickRewardId,
+ leadRewardId: programEnrollment.leadRewardId,
+ saleRewardId: programEnrollment.saleRewardId,
+ },
+ activityDescription,
+ }),
+
recordAuditLog({
workspaceId: workspace.id,
programId,
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index 7aa0951db2..65d260d65c 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -100,50 +100,24 @@ export const updateRewardAction = authActionClient
amountInPercentage: new Prisma.Decimal(amountInPercentage!),
}),
},
- include: {
- clickPartnerGroup: true,
- leadPartnerGroup: true,
- salePartnerGroup: true,
- referralPartnerGroup: true,
- customPartnerGroup: true,
- },
});
- const {
- clickPartnerGroup,
- leadPartnerGroup,
- salePartnerGroup,
- referralPartnerGroup,
- customPartnerGroup,
- ...rewardMetadata
- } = updatedReward;
-
- // Determine the groupId from the partner group relation
- const partnerGroup =
- clickPartnerGroup ||
- leadPartnerGroup ||
- salePartnerGroup ||
- referralPartnerGroup ||
- customPartnerGroup;
-
- if (!partnerGroup) {
- throw new Error("Partner group not found.");
+ if (updatedReward.groupId) {
+ await queueRewardProcessing({
+ event: "reward-updated",
+ groupId: updatedReward.groupId,
+ occurredAt: new Date().toISOString(),
+ rewardSnapshot: {
+ id: reward.id,
+ event: reward.event,
+ description: formatRewardDescription(serializeReward(updatedReward), {
+ includeEarnPrefix: false,
+ }),
+ activityDescription,
+ },
+ });
}
- await queueRewardProcessing({
- event: "reward-updated",
- groupId: partnerGroup.id,
- occurredAt: new Date().toISOString(),
- rewardSnapshot: {
- id: reward.id,
- event: reward.event,
- description: formatRewardDescription(serializeReward(updatedReward), {
- includeEarnPrefix: false,
- }),
- activityDescription,
- },
- });
-
revalidateProgramPublicPages(programId);
waitUntil(
@@ -158,7 +132,7 @@ export const updateRewardAction = authActionClient
{
type: "reward",
id: rewardId,
- metadata: serializeReward(rewardMetadata),
+ metadata: serializeReward(updatedReward),
},
],
}),
@@ -167,9 +141,9 @@ export const updateRewardAction = authActionClient
workspaceId: workspace.id,
programId,
userId: user.id,
- resourceId: rewardMetadata.id,
+ resourceId: updatedReward.id,
parentResourceType: "group",
- parentResourceId: partnerGroup.id,
+ parentResourceId: updatedReward.groupId,
old: reward,
new: updatedReward,
description: activityDescription,
diff --git a/apps/web/lib/api/activity-log/to-reward-activity-snapshot.ts b/apps/web/lib/api/activity-log/to-reward-activity-snapshot.ts
new file mode 100644
index 0000000000..0432085ad8
--- /dev/null
+++ b/apps/web/lib/api/activity-log/to-reward-activity-snapshot.ts
@@ -0,0 +1,49 @@
+import type { DiscountProps, RewardProps } from "@/lib/types";
+
+export function toRewardActivitySnapshot(
+ reward: Pick<
+ RewardProps,
+ | "id"
+ | "event"
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "maxDuration"
+ | "description"
+ | "tooltipDescription"
+ | "modifiers"
+ | "config"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
+ >,
+) {
+ return {
+ id: reward.id,
+ event: reward.event,
+ type: reward.type,
+ amountInCents: reward.amountInCents ?? null,
+ amountInPercentage: reward.amountInPercentage ?? null,
+ maxDuration: reward.maxDuration ?? null,
+ description: reward.description ?? null,
+ tooltipDescription: reward.tooltipDescription ?? null,
+ modifiers: reward.modifiers ?? null,
+ config: reward.config ?? null,
+ spendLimitAmount: reward.spendLimitAmount ?? null,
+ spendLimitInterval: reward.spendLimitInterval ?? null,
+ };
+}
+
+export function toDiscountActivitySnapshot(
+ discount: Pick<
+ DiscountProps,
+ "id" | "amount" | "type" | "maxDuration" | "description"
+ >,
+) {
+ return {
+ id: discount.id,
+ amount: discount.amount,
+ type: discount.type,
+ maxDuration: discount.maxDuration ?? null,
+ description: discount.description ?? null,
+ };
+}
diff --git a/apps/web/lib/api/activity-log/track-reward-overrides.ts b/apps/web/lib/api/activity-log/track-reward-overrides.ts
new file mode 100644
index 0000000000..0ee474bb8f
--- /dev/null
+++ b/apps/web/lib/api/activity-log/track-reward-overrides.ts
@@ -0,0 +1,154 @@
+import {
+ toDiscountActivitySnapshot,
+ toRewardActivitySnapshot,
+} from "@/lib/api/activity-log/to-reward-activity-snapshot";
+import {
+ trackActivityLog,
+ type TrackActivityLogInput,
+} from "@/lib/api/activity-log/track-activity-log";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
+import type { EnrollmentRewardIds } from "@/lib/api/rewards/reward-overrides";
+import { prisma } from "@/lib/prisma";
+
+type RewardOverrideBaseInput = {
+ workspaceId: string;
+ programId: string;
+ partnerId: string;
+ userId: string;
+ previous: EnrollmentRewardIds;
+ next: EnrollmentRewardIds;
+ description?: string;
+};
+
+export async function trackPartnerRewardOverrideLog(
+ input: RewardOverrideBaseInput,
+) {
+ const {
+ workspaceId,
+ programId,
+ partnerId,
+ userId,
+ previous,
+ next,
+ description,
+ } = input;
+
+ const rewardFields = [
+ ["clickReward", previous.clickRewardId, next.clickRewardId],
+ ["leadReward", previous.leadRewardId, next.leadRewardId],
+ ["saleReward", previous.saleRewardId, next.saleRewardId],
+ ] as const;
+
+ const changedRewardFields = rewardFields.filter(
+ ([, oldId, newId]) => oldId !== newId,
+ );
+ const discountChanged = previous.discountId !== next.discountId;
+
+ if (changedRewardFields.length === 0 && !discountChanged) {
+ return;
+ }
+
+ const rewardIds = [
+ ...new Set(
+ changedRewardFields.flatMap(([, oldId, newId]) =>
+ [oldId, newId].filter((id): id is string => Boolean(id)),
+ ),
+ ),
+ ];
+ const discountIds = [
+ ...new Set(
+ [previous.discountId, next.discountId].filter((id): id is string =>
+ Boolean(id),
+ ),
+ ),
+ ];
+
+ const [rewards, discounts] = await Promise.all([
+ rewardIds.length > 0
+ ? prisma.reward.findMany({
+ where: { id: { in: rewardIds } },
+ })
+ : [],
+ discountChanged && discountIds.length > 0
+ ? prisma.discount.findMany({
+ where: { id: { in: discountIds } },
+ select: {
+ id: true,
+ amount: true,
+ type: true,
+ maxDuration: true,
+ description: true,
+ },
+ })
+ : [],
+ ]);
+
+ const rewardsById = new Map<
+ string,
+ ReturnType<typeof toRewardActivitySnapshot>
+ >();
+ const discountsById = new Map<
+ string,
+ ReturnType<typeof toDiscountActivitySnapshot>
+ >();
+
+ for (const reward of rewards) {
+ rewardsById.set(
+ reward.id,
+ toRewardActivitySnapshot(serializeReward(reward)),
+ );
+ }
+
+ for (const discount of discounts) {
+ discountsById.set(discount.id, toDiscountActivitySnapshot(discount));
+ }
+
+ const base = {
+ workspaceId,
+ programId,
+ resourceType: "partner" as const,
+ resourceId: partnerId,
+ userId,
+ };
+
+ const activityLogs: TrackActivityLogInput[] = [];
+
+ if (changedRewardFields.length > 0) {
+ activityLogs.push({
+ ...base,
+ action: "partner.rewardChanged",
+ description,
+ changeSet: Object.fromEntries(
+ changedRewardFields.map(([field, oldId, newId]) => [
+ field,
+ {
+ old: oldId ? rewardsById.get(oldId) ?? { id: oldId } : null,
+ new: newId ? rewardsById.get(newId) ?? { id: newId } : null,
+ },
+ ]),
+ ),
+ });
+ }
+
+ if (discountChanged) {
+ activityLogs.push({
+ ...base,
+ action: "partner.discountChanged",
+ description,
+ changeSet: {
+ discount: {
+ old: previous.discountId
+ ? discountsById.get(previous.discountId) ?? {
+ id: previous.discountId,
+ }
+ : null,
+ new: next.discountId
+ ? discountsById.get(next.discountId) ?? { id: next.discountId }
+ : null,
+ },
+ },
+ });
+ }
+
+ await trackActivityLog(activityLogs);
+}
diff --git a/apps/web/lib/api/partners/notify-partner-reward-change.ts b/apps/web/lib/api/partners/notify-partner-reward-change.ts
index 784646c401..fad2d16275 100644
--- a/apps/web/lib/api/partners/notify-partner-reward-change.ts
+++ b/apps/web/lib/api/partners/notify-partner-reward-change.ts
@@ -1,8 +1,13 @@
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import type { RewardJob } from "@/lib/api/rewards/queue-reward-processing";
+import type { EnrollmentRewardIds } from "@/lib/api/rewards/reward-overrides";
import { queueBatchEmail } from "@/lib/email/queue-batch-email";
+import { prisma } from "@/lib/prisma";
import { RewardProps } from "@/lib/types";
+import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import type PartnerRewardUpdated from "@dub/email/templates/partner-reward-updated";
import { Program, Reward, User } from "@prisma/client";
+import { getPartnerUsers } from "./get-partner-users";
const REWARD_ICONS: Record<RewardProps["event"], string> = {
click: "https://assets.dub.co/email-assets/icons/cursor-rays.png",
@@ -19,7 +24,7 @@ interface NotifyPartnerRewardChangeParams {
rewardSnapshot: { description: string; activityDescription?: string };
effectiveAt: Date | string;
users: Pick<User, "name" | "email">[];
- idempotencyKey: string;
+ idempotencyKey?: string;
}
export async function notifyPartnerRewardChange({
@@ -72,8 +77,84 @@ export async function notifyPartnerRewardChange({
action,
},
})),
- {
- idempotencyKey,
- },
+ idempotencyKey ? { idempotencyKey } : undefined,
);
}
+
+type OverrideRewardIds = Pick<
+ EnrollmentRewardIds,
+ "clickRewardId" | "leadRewardId" | "saleRewardId"
+>;
+
+export async function notifyPartnerRewardOverride({
+ programId,
+ partnerId,
+ previous,
+ next,
+ groupRewardIds,
+ activityDescription,
+}: {
+ programId: string;
+ partnerId: string;
+ previous: OverrideRewardIds;
+ next: OverrideRewardIds;
+ groupRewardIds?: OverrideRewardIds;
+ activityDescription?: string;
+}) {
+ const rewardId = (
+ ["clickRewardId", "leadRewardId", "saleRewardId"] as const
+ ).reduce<string | null>((found, field) => {
+ if (found || previous[field] === next[field]) {
+ return found;
+ }
+
+ return next[field] ?? groupRewardIds?.[field] ?? null;
+ }, null);
+
+ if (!rewardId) {
+ return;
+ }
+
+ const [program, reward, partnerUsers] = await Promise.all([
+ prisma.program.findUnique({
+ where: {
+ id: programId,
+ },
+ select: {
+ id: true,
+ name: true,
+ logo: true,
+ slug: true,
+ supportEmail: true,
+ },
+ }),
+
+ prisma.reward.findUnique({
+ where: {
+ id: rewardId,
+ },
+ }),
+
+ getPartnerUsers({
+ partnerIds: [partnerId],
+ }),
+ ]);
+
+ if (!program || !reward || partnerUsers.length === 0) {
+ return;
+ }
+
+ await notifyPartnerRewardChange({
+ action: "reward-updated",
+ program,
+ reward,
+ rewardSnapshot: {
+ description: formatRewardDescription(serializeReward(reward), {
+ includeEarnPrefix: false,
+ }),
+ activityDescription,
+ },
+ effectiveAt: new Date(),
+ users: partnerUsers.map(({ user }) => user),
+ });
+}
diff --git a/apps/web/lib/api/rewards/reward-overrides.ts b/apps/web/lib/api/rewards/reward-overrides.ts
new file mode 100644
index 0000000000..75ac7de54a
--- /dev/null
+++ b/apps/web/lib/api/rewards/reward-overrides.ts
@@ -0,0 +1,35 @@
+export type EnrollmentRewardIds = {
+ clickRewardId: string | null;
+ leadRewardId: string | null;
+ saleRewardId: string | null;
+ discountId: string | null;
+};
+
+export type EnrollmentRewardIdsInput = Partial<EnrollmentRewardIds>;
+
+// True when any reward/discount field was sent, including explicit null clears.
+export const hasRewardIdsInput = ({
+ clickRewardId,
+ leadRewardId,
+ saleRewardId,
+ discountId,
+}: EnrollmentRewardIdsInput) => {
+ return (
+ clickRewardId !== undefined ||
+ leadRewardId !== undefined ||
+ saleRewardId !== undefined ||
+ discountId !== undefined
+ );
+};
+
+// True when any field assigns a non-null reward/discount id (not a clear).
+export const hasRewardAssignment = ({
+ clickRewardId,
+ leadRewardId,
+ saleRewardId,
+ discountId,
+}: EnrollmentRewardIdsInput) => {
+ return [clickRewardId, leadRewardId, saleRewardId, discountId].some(
+ (id) => id !== undefined && id !== null,
+ );
+};
diff --git a/apps/web/lib/api/rewards/throw-if-invalid-rewards.ts b/apps/web/lib/api/rewards/throw-if-invalid-rewards.ts
new file mode 100644
index 0000000000..e71ad9c704
--- /dev/null
+++ b/apps/web/lib/api/rewards/throw-if-invalid-rewards.ts
@@ -0,0 +1,168 @@
+import { DubApiError } from "@/lib/api/errors";
+import type { EnrollmentRewardIdsInput } from "@/lib/api/rewards/reward-overrides";
+import { prisma } from "@/lib/prisma";
+import { EventType } from "@prisma/client";
+
+const belongsToGroup = ({
+ groupId,
+ entityGroupId,
+ defaultGroupId,
+}: {
+ groupId: string;
+ entityGroupId: string | null;
+ defaultGroupId?: string | null;
+}) => entityGroupId === groupId || defaultGroupId === groupId;
+
+export async function throwIfInvalidRewards({
+ programId,
+ groupId,
+ clickRewardId,
+ leadRewardId,
+ saleRewardId,
+ discountId,
+}: {
+ programId: string;
+ groupId: string | null | undefined;
+} & EnrollmentRewardIdsInput) {
+ const assignments: {
+ id: string;
+ event: EventType;
+ }[] = [];
+
+ if (clickRewardId) {
+ assignments.push({
+ id: clickRewardId,
+ event: EventType.click,
+ });
+ }
+
+ if (leadRewardId) {
+ assignments.push({
+ id: leadRewardId,
+ event: EventType.lead,
+ });
+ }
+
+ if (saleRewardId) {
+ assignments.push({
+ id: saleRewardId,
+ event: EventType.sale,
+ });
+ }
+
+ if (assignments.length === 0 && !discountId) {
+ return;
+ }
+
+ if (!groupId) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "This partner is not part of a partner group.",
+ });
+ }
+
+ if (assignments.length > 0) {
+ const rewards = await prisma.reward.findMany({
+ where: {
+ id: {
+ in: assignments.map(({ id }) => id),
+ },
+ programId,
+ },
+ select: {
+ id: true,
+ event: true,
+ groupId: true,
+ clickPartnerGroup: {
+ select: {
+ id: true,
+ },
+ },
+ leadPartnerGroup: {
+ select: {
+ id: true,
+ },
+ },
+ salePartnerGroup: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
+
+ const rewardsById = new Map(rewards.map((reward) => [reward.id, reward]));
+
+ for (const assignment of assignments) {
+ const reward = rewardsById.get(assignment.id);
+
+ if (!reward) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Reward ${assignment.id} not found.`,
+ });
+ }
+
+ if (reward.event !== assignment.event) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `Reward ${assignment.id} is a ${reward.event} reward and cannot be assigned as a ${assignment.event} reward.`,
+ });
+ }
+
+ if (
+ !belongsToGroup({
+ groupId,
+ entityGroupId: reward.groupId,
+ defaultGroupId:
+ reward.clickPartnerGroup?.id ??
+ reward.leadPartnerGroup?.id ??
+ reward.salePartnerGroup?.id,
+ })
+ ) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `Reward ${assignment.id} does not belong to this partner's group.`,
+ });
+ }
+ }
+ }
+
+ if (discountId) {
+ const discount = await prisma.discount.findFirst({
+ where: {
+ id: discountId,
+ programId,
+ },
+ select: {
+ id: true,
+ groupId: true,
+ partnerGroup: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
+
+ if (!discount) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Discount ${discountId} not found.`,
+ });
+ }
+
+ if (
+ !belongsToGroup({
+ groupId,
+ entityGroupId: discount.groupId,
+ defaultGroupId: discount.partnerGroup?.id,
+ })
+ ) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `Discount ${discountId} does not belong to this partner's group.`,
+ });
+ }
+ }
+}
diff --git a/apps/web/lib/discounts/generate-discount-code-for-partner.ts b/apps/web/lib/discounts/generate-discount-code-for-partner.ts
index 711e79f06c..a52873d122 100644
--- a/apps/web/lib/discounts/generate-discount-code-for-partner.ts
+++ b/apps/web/lib/discounts/generate-discount-code-for-partner.ts
@@ -24,14 +24,49 @@ export async function generateDiscountCodeForPartner({
where: {
id: partner.groupId,
},
- include: {
+ select: {
+ programId: true,
+ },
+ });
+
+ if (!group) {
+ console.log(
+ `Group ${partner.groupId} not found, skipping discount code creation...`,
+ );
+ return;
+ }
+
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId: partner.id,
+ programId: group.programId,
+ },
+ },
+ select: {
discount: true,
},
});
- if (!group?.discount?.autoProvisionEnabledAt) {
+ if (!programEnrollment) {
+ console.log(
+ `No program enrollment found for partner ${partner.id}, skipping discount code creation...`,
+ );
+ return;
+ }
+
+ const discount = programEnrollment?.discount;
+
+ if (!discount) {
+ console.log(
+ `No discount found for partner ${partner.id}, skipping discount code creation...`,
+ );
+ return;
+ }
+
+ if (!discount.autoProvisionEnabledAt) {
console.log(
- `Group ${partner.groupId} does not have auto provision enabled, skipping discount code creation...`,
+ `Discount ${discount.id} does not have auto provision enabled, skipping discount code creation...`,
);
return;
}
@@ -64,7 +99,7 @@ export async function generateDiscountCodeForPartner({
workspace,
partner,
link: partnerDefaultLink,
- discount: group.discount,
+ discount,
});
} catch (error) {
console.error(
diff --git a/apps/web/lib/discounts/remap-discount-codes.ts b/apps/web/lib/discounts/remap-discount-codes.ts
new file mode 100644
index 0000000000..9988a311c8
--- /dev/null
+++ b/apps/web/lib/discounts/remap-discount-codes.ts
@@ -0,0 +1,154 @@
+import { prisma } from "@/lib/prisma";
+import { ProgramEnrollment } from "@prisma/client";
+import { createDiscountCode } from "./create-discount-code";
+import { deleteDiscountCodes } from "./delete-discount-code";
+import { isDiscountProviderError } from "./discount-error";
+import { isDiscountEquivalent } from "./is-discount-equivalent";
+
+export async function remapDiscountCodes({
+ programId,
+ partnerId,
+}: Pick<ProgramEnrollment, "programId" | "partnerId">) {
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ select: {
+ id: true,
+ discount: true,
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!programEnrollment) {
+ console.log(
+ `Program enrollment not found for partner ${partnerId} and program ${programId}. Skipping...`,
+ );
+ return;
+ }
+
+ const discountCodes = await prisma.discountCode.findMany({
+ where: {
+ programId,
+ partnerId,
+ disabledAt: null,
+ },
+ include: {
+ discount: true,
+ },
+ });
+
+ const newDiscount = programEnrollment.discount;
+ const discountCodesToDelete: typeof discountCodes = [];
+
+ for (const discountCode of discountCodes) {
+ const existingDiscount = discountCode.discount;
+
+ // No discount exists for this discount code, delete it
+ if (!newDiscount) {
+ discountCodesToDelete.push(discountCode);
+ continue;
+ }
+
+ // The discount is already the correct one, skip
+ if (existingDiscount?.id === newDiscount.id) {
+ continue;
+ }
+
+ const isEquivalent = isDiscountEquivalent(newDiscount, existingDiscount);
+
+ // The discounts are equivalent, update the discount code to use the new discount
+ if (isEquivalent) {
+ await prisma.discountCode.updateMany({
+ where: {
+ id: discountCode.id,
+ },
+ data: {
+ discountId: newDiscount.id,
+ },
+ });
+ continue;
+ }
+
+ // The discounts are different, delete the discount code
+ discountCodesToDelete.push(discountCode);
+ }
+
+ if (discountCodesToDelete.length > 0) {
+ await deleteDiscountCodes(discountCodesToDelete);
+ }
+
+ if (!newDiscount?.autoProvisionEnabledAt) {
+ return;
+ }
+
+ const links = await prisma.link.findMany({
+ where: {
+ partnerId,
+ programId,
+ partnerGroupDefaultLinkId: {
+ not: null,
+ },
+ discountCode: {
+ is: null,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (links.length === 0) {
+ return;
+ }
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ defaultProgramId: programId,
+ },
+ select: {
+ id: true,
+ webhookEnabled: true,
+ stripeConnectId: true,
+ shopifyStoreId: true,
+ },
+ });
+
+ for (const link of links) {
+ try {
+ await createDiscountCode({
+ workspace,
+ partner: programEnrollment.partner,
+ link,
+ discount: newDiscount,
+ });
+ } catch (error) {
+ if (isDiscountProviderError(error)) {
+ if (
+ error.providerCode === "INTEGRATION_NOT_AVAILABLE" ||
+ error.providerCode === "AUTH_EXPIRED" ||
+ error.providerCode === "PERMISSIONS_REQUIRED" ||
+ error.providerCode === "COUPON_NOT_FOUND"
+ ) {
+ console.warn(
+ `${error.message} Skipping remaining discount code creation for remap.`,
+ );
+ break;
+ }
+ }
+
+ console.error(
+ `Failed to create discount code for link ${link.id}:`,
+ error,
+ );
+ }
+ }
+}
diff --git a/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.ts b/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.ts
new file mode 100644
index 0000000000..1d6809bc73
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.ts
@@ -0,0 +1,75 @@
+import { linkCache } from "@/lib/api/links/cache";
+import { prisma } from "@/lib/prisma";
+import { chunk } from "@dub/utils";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const inputSchema = z.discriminatedUnion("type", [
+ // Discount is still assigned to enrollments.
+ z.object({
+ type: z.literal("discount"),
+ discountId: z.string(),
+ }),
+
+ // Discount was unassigned or deleted; expire these partners' program links.
+ z.object({
+ type: z.literal("partners"),
+ programId: z.string(),
+ partnerIds: z.array(z.string()).min(1),
+ }),
+]);
+
+type InvalidateLinksForDiscountsInput = z.infer<typeof inputSchema>;
+
+// Invalidates the partner link cache when a discount is created/updated/deleted.
+export const invalidateLinksForDiscountsJob = defineJob({
+ name: "invalidate-links-for-discounts-job",
+ schema: inputSchema,
+ async handle(input) {
+ const links = await findLinksToInvalidate(input);
+
+ if (links.length === 0) {
+ console.info(`No links found to invalidate for discount. Skipping...`);
+ return;
+ }
+
+ const linkChunks = chunk(links, 100);
+
+ for (const linkChunk of linkChunks) {
+ await linkCache.expireMany(linkChunk);
+ }
+
+ console.info(`Expired cache for ${links.length} links.`);
+ },
+});
+
+async function findLinksToInvalidate(input: InvalidateLinksForDiscountsInput) {
+ if (input.type === "discount") {
+ return prisma.link.findMany({
+ where: {
+ programEnrollment: {
+ is: {
+ discountId: input.discountId,
+ },
+ },
+ },
+ select: {
+ domain: true,
+ key: true,
+ },
+ });
+ }
+
+ return prisma.link.findMany({
+ where: {
+ programId: input.programId,
+ partnerId: {
+ in: input.partnerIds,
+ },
+ },
+ select: {
+ domain: true,
+ key: true,
+ },
+ });
+}
diff --git a/apps/web/lib/jobs/handlers/remap-discount-codes-for-partner-job.ts b/apps/web/lib/jobs/handlers/remap-discount-codes-for-partner-job.ts
new file mode 100644
index 0000000000..824a0b023f
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/remap-discount-codes-for-partner-job.ts
@@ -0,0 +1,16 @@
+import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const inputSchema = z.object({
+ programId: z.string(),
+ partnerId: z.string(),
+});
+
+export const remapDiscountCodesForPartnerJob = defineJob({
+ name: "remap-discount-codes-for-partner-job",
+ schema: inputSchema,
+ async handle(input) {
+ await remapDiscountCodes(input);
+ },
+});
diff --git a/apps/web/lib/swr/use-discounts.ts b/apps/web/lib/swr/use-discounts.ts
index 055686017a..68670b22b5 100644
--- a/apps/web/lib/swr/use-discounts.ts
+++ b/apps/web/lib/swr/use-discounts.ts
@@ -9,7 +9,7 @@ export default function useDiscounts() {
const { data: discounts, error } = useSWR<DiscountProps[]>(
workspaceId &&
defaultProgramId &&
- `/api/programs/${defaultProgramId}/discounts?workspaceId=${workspaceId}`,
+ `/api/discounts?workspaceId=${workspaceId}`,
fetcher,
{
dedupingInterval: 60000,
diff --git a/apps/web/playwright/api/discounts/discounts.spec.ts b/apps/web/playwright/api/discounts/discounts.spec.ts
index 31104f5970..0e7bc4e4bd 100644
--- a/apps/web/playwright/api/discounts/discounts.spec.ts
+++ b/apps/web/playwright/api/discounts/discounts.spec.ts
@@ -185,13 +185,13 @@ async function deleteCustomer(api: ApiClient, id: string | undefined) {
await api.delete(`/api/customers/${id}`);
}
-test("GET /programs/{programId}/discounts – custom provider", async ({
+test("GET /api/discounts – lists discounts with partnersCount", async ({
api,
- program,
}) => {
- const { status, data } = await api.get<DiscountProps[]>(
- `/api/programs/${program.id}/discounts`,
- );
+ const { status, data } =
+ await api.get<
+ (DiscountProps & { groupId: string | null; partnersCount: number })[]
+ >("/api/discounts");
expect(status).toEqual(200);
@@ -199,11 +199,23 @@ test("GET /programs/{programId}/discounts – custom provider", async ({
expect(discount).toEqual({
id: customDiscountId,
+ groupId: null,
...expectedCustomDiscount,
partnersCount: expect.any(Number),
});
});
+test("GET /api/discounts?groupId= – includes group default without groupId column", async ({
+ api,
+}) => {
+ const { status, data } = await api.get<
+ (DiscountProps & { groupId: string | null; partnersCount: number })[]
+ >(`/api/discounts?groupId=${partnerGroupId}`);
+
+ expect(status).toEqual(200);
+ expect(data.some((item) => item.id === customDiscountId)).toBe(true);
+});
+
test("GET /groups/{id} – nested custom discount", async ({ api }) => {
const { status, data } = await api.get<GroupProps>(
`/api/groups/${partnerGroupId}`,
diff --git a/apps/web/tests/rewards/determine-partner-rewards.test.ts b/apps/web/tests/rewards/determine-partner-rewards.test.ts
index 2a9a72e6de..e20abefc2e 100644
--- a/apps/web/tests/rewards/determine-partner-rewards.test.ts
+++ b/apps/web/tests/rewards/determine-partner-rewards.test.ts
@@ -22,6 +22,7 @@ function saleReward(overrides: Partial<Reward> = {}): Reward {
config: null,
spendLimitAmount: null,
spendLimitInterval: null,
+ groupId: null,
createdAt: new Date("2026-01-01"),
updatedAt: new Date("2026-01-01"),
...overrides,