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.

Cadence-based custom rewards (#4437)

Kiran K7dcd4e09e679
diff --git a/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts b/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts
index 744bce718b..f50e81cfa4 100644
--- a/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts
+++ b/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts
@@ -24,12 +24,14 @@ export const POST = withCron(async () => {
leadPartnerGroup: true,
salePartnerGroup: true,
referralPartnerGroup: true,
+ customPartnerGroup: true,
_count: {
select: {
clickEnrollments: true,
leadEnrollments: true,
saleEnrollments: true,
referralEnrollments: true,
+ customEnrollments: true,
},
},
},
@@ -49,10 +51,12 @@ export const POST = withCron(async () => {
reward.leadPartnerGroup === null &&
reward.salePartnerGroup === null &&
reward.referralPartnerGroup === null &&
+ reward.customPartnerGroup === null &&
reward._count.clickEnrollments === 0 &&
reward._count.leadEnrollments === 0 &&
reward._count.saleEnrollments === 0 &&
- reward._count.referralEnrollments === 0
+ reward._count.referralEnrollments === 0 &&
+ reward._count.customEnrollments === 0
);
});
diff --git a/apps/web/app/(ee)/api/cron/rewards/queue-custom-commissions/route.ts b/apps/web/app/(ee)/api/cron/rewards/queue-custom-commissions/route.ts
new file mode 100644
index 0000000000..27a69a3515
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/rewards/queue-custom-commissions/route.ts
@@ -0,0 +1,40 @@
+import { getUtcPeriodDate } from "@/lib/api/rewards/custom-reward-utils";
+import { findDueCustomRewards } from "@/lib/api/rewards/find-due-custom-rewards";
+import { withCron } from "@/lib/cron/with-cron";
+import { createCustomCommissionJob } from "@/lib/jobs/handlers/create-custom-commission-job";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+export const maxDuration = 600;
+
+// GET /api/cron/rewards/queue-custom-commissions
+// Fans out create-custom-commission-job for each due custom reward (daily UTC).
+export const GET = withCron(async () => {
+ const periodDate = getUtcPeriodDate();
+ const dueRewards = await findDueCustomRewards({ periodDate });
+
+ if (dueRewards.length === 0) {
+ return logAndRespond(
+ `No due custom rewards for period ${periodDate}. Skipping...`,
+ );
+ }
+
+ await createCustomCommissionJob.dispatchBatch(
+ dueRewards.map((reward) => ({
+ rewardId: reward.id,
+ periodDate,
+ })),
+ ({ rewardId }) => ({
+ label: rewardId,
+ deduplicationId: `custom-commission-${rewardId}-${periodDate}`,
+ flowControl: {
+ key: "create-custom-commission",
+ parallelism: 5,
+ },
+ }),
+ );
+
+ return logAndRespond(
+ `Queued create-custom-commission-job for ${dueRewards.length} custom rewards (period ${periodDate}).`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
index 0bce5a5c5a..094a7eecd0 100644
--- a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
+++ b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
@@ -160,6 +160,7 @@ export const PATCH = withWorkspace(
leadReward: true,
saleReward: true,
referralReward: true,
+ customReward: true,
discount: true,
},
}),
@@ -330,6 +331,7 @@ export const DELETE = withWorkspace(
group.leadRewardId,
group.saleRewardId,
group.referralRewardId,
+ group.customRewardId,
].filter(Boolean) as string[];
if (groupRewardIds.length > 0) {
diff --git a/apps/web/app/(ee)/api/groups/route.ts b/apps/web/app/(ee)/api/groups/route.ts
index 9bbb4547bc..dda6423b7f 100644
--- a/apps/web/app/(ee)/api/groups/route.ts
+++ b/apps/web/app/(ee)/api/groups/route.ts
@@ -151,6 +151,7 @@ export const POST = withWorkspace(
leadReward: true,
saleReward: true,
referralReward: true,
+ customReward: true,
discount: true,
},
});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
index 79a0b8fdbc..ad82102854 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
@@ -17,6 +17,7 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
leadReward: true,
saleReward: true,
referralReward: true,
+ customReward: true,
discount: true,
partnerGroup: true,
application: {
@@ -34,6 +35,7 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
programEnrollment.leadReward,
programEnrollment.saleReward,
programEnrollment.referralReward,
+ programEnrollment.customReward,
].filter((r): r is Reward => r !== null);
return NextResponse.json(
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
index 02d150cf93..fef349755d 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
@@ -49,6 +49,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
leadReward: true,
saleReward: true,
referralReward: true,
+ customReward: true,
discount: true,
}),
},
@@ -75,6 +76,8 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
enrollment.clickReward,
enrollment.leadReward,
enrollment.saleReward,
+ enrollment.referralReward,
+ enrollment.customReward,
].filter((r): r is Reward => r !== null)
: [],
application: enrollment.application
diff --git a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
index 234db2521c..1ebd527b18 100644
--- a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
+++ b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
@@ -178,6 +178,7 @@ async function stepCreateCommission(
customerId,
eventId,
invoiceId,
+ rewardId,
amount,
quantity,
currency,
@@ -425,13 +426,31 @@ async function stepCreateCommission(
earnings = cappedEarnings;
}
+ // Custom reward jobs are queued from a snapshot of eligible enrollments.
+ // Re-check at write time so we don't pay a partner who was banned, deactivated,
+ // or moved off this reward before the workflow ran.
+ // Only jobs that pass rewardId (create-custom-commission) should be gated —
+ // manual commissions and bounty payouts also use event "custom" but have no rewardId.
+ const isCustomRewardCommission = event === "custom" && Boolean(rewardId);
+ const stillOnCustomReward = programEnrollment.customRewardId === rewardId;
+
+ if (
+ isCustomRewardCommission &&
+ (programEnrollment.status !== "approved" || !stillOnCustomReward)
+ ) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} is no longer eligible for custom reward ${rewardId} (status: ${programEnrollment.status}), skipping commission creation...`,
+ });
+ }
+
try {
const commission = await prisma.commission.create({
data: {
id: createId({ prefix: "cm_" }),
programId,
partnerId,
- rewardId: reward?.id,
+ rewardId: reward?.id ?? rewardId,
customerId,
linkId,
eventId: eventId || null, // empty string should convert to null
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
index 1c07d048f0..d63d2f929d 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
@@ -58,6 +58,7 @@ export const getReferralsEmbedData = async (token: string) => {
leadReward: true,
saleReward: true,
referralReward: true,
+ customReward: true,
discount: true,
programPartnerTags: {
select: {
@@ -80,6 +81,7 @@ export const getReferralsEmbedData = async (token: string) => {
leadReward,
saleReward,
referralReward,
+ customReward,
partnerGroup: group,
} = programEnrollment;
@@ -120,7 +122,7 @@ export const getReferralsEmbedData = async (token: string) => {
},
partnerPlatforms: partner.platforms,
links: z.array(ReferralsEmbedLinkSchema).parse(links),
- rewards: [clickReward, leadReward, saleReward, referralReward]
+ rewards: [clickReward, leadReward, saleReward, referralReward, customReward]
.filter((r): r is Reward => r !== null)
.map((r) => serializeReward(r)),
discount,
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx
index 84c2a77779..f0850fbd5b 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx
@@ -652,7 +652,8 @@ function RewardList() {
(reward) =>
reward.event === "click" ||
reward.event === "lead" ||
- reward.event === "sale",
+ reward.event === "sale" ||
+ reward.event === "custom",
);
const referralRewards = eligibleRewards.filter(
@@ -660,7 +661,7 @@ function RewardList() {
);
const discount = programEnrollment.discount ?? null;
- const showReferralRewardCard = referralRewards.length > 0;
+ const hasPartnerReferralReward = referralRewards.length > 0;
const defaultProgramLink = programEnrollment.links?.[0];
const partnerLink = constructPartnerLink({
@@ -678,7 +679,9 @@ function RewardList() {
return (
<div className="flex flex-col gap-2 rounded-xl bg-neutral-100 p-2">
<RewardListItem
- title={showReferralRewardCard ? "Customer referral rewards" : "Rewards"}
+ title={
+ hasPartnerReferralReward ? "Customer referral rewards" : "Rewards"
+ }
titleRight={<RewardsTermsList />}
isDeactivated={isDeactivated}
rewards={[
@@ -724,7 +727,7 @@ function RewardList() {
}
/>
- {showReferralRewardCard && (
+ {hasPartnerReferralReward && (
<RewardListItem
title="Partner referral rewards"
isDeactivated={isDeactivated}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
index 3532be84db..5db6225a38 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
@@ -50,6 +50,7 @@ export function GroupRewards() {
group?.leadReward,
group?.saleReward,
group?.referralReward,
+ group?.customReward,
].filter(Boolean) ?? [];
const currentReward = rewardSheetState.rewardId
@@ -76,7 +77,7 @@ export function GroupRewards() {
<div className="flex flex-col gap-6">
{loading || !group ? (
<>
- {Array.from({ length: 4 }).map((_, index) => (
+ {Array.from({ length: 5 }).map((_, index) => (
<RewardSkeleton key={index} />
))}
</>
@@ -97,6 +98,12 @@ export function GroupRewards() {
event="referral"
group={group}
/>
+
+ <RewardItem
+ reward={group.customReward}
+ event="custom"
+ group={group}
+ />
</>
)}
</div>
diff --git a/apps/web/lib/actions/partners/ban-partner.ts b/apps/web/lib/actions/partners/ban-partner.ts
index 813c2f1cce..5d2a488a0d 100644
--- a/apps/web/lib/actions/partners/ban-partner.ts
+++ b/apps/web/lib/actions/partners/ban-partner.ts
@@ -104,6 +104,7 @@ export const banPartner = async ({
leadRewardId: null,
saleRewardId: null,
referralRewardId: null,
+ customRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/actions/partners/bulk-approve-partners.ts b/apps/web/lib/actions/partners/bulk-approve-partners.ts
index f1e3f5a67a..2b95340e04 100644
--- a/apps/web/lib/actions/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-approve-partners.ts
@@ -68,6 +68,7 @@ export const bulkApprovePartnersAction = authActionClient
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/lib/actions/partners/bulk-ban-partners.ts b/apps/web/lib/actions/partners/bulk-ban-partners.ts
index f7a566daad..9df518f1c1 100644
--- a/apps/web/lib/actions/partners/bulk-ban-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-ban-partners.ts
@@ -73,6 +73,7 @@ export const bulkBanPartnersAction = authActionClient
leadRewardId: null,
saleRewardId: null,
referralRewardId: null,
+ customRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/actions/partners/bulk-invite-partners.ts b/apps/web/lib/actions/partners/bulk-invite-partners.ts
index 21ae0bf85c..321e428bdb 100644
--- a/apps/web/lib/actions/partners/bulk-invite-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-invite-partners.ts
@@ -135,6 +135,7 @@ export const bulkInvitePartnersAction = authActionClient
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
})),
skipDuplicates: true,
diff --git a/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts b/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts
index d367080b6d..66d4506ef7 100644
--- a/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts
+++ b/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts
@@ -66,6 +66,7 @@ export const bulkRejectPartnerApplicationsAction = authActionClient
leadRewardId: null,
saleRewardId: null,
referralRewardId: null,
+ customRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.ts
index acb8e0b6c3..66b0cc17eb 100644
--- a/apps/web/lib/actions/partners/create-program-application.ts
+++ b/apps/web/lib/actions/partners/create-program-application.ts
@@ -317,6 +317,7 @@ async function createApplicationAndEnrollment({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
}),
diff --git a/apps/web/lib/actions/partners/reactivate-partner.ts b/apps/web/lib/actions/partners/reactivate-partner.ts
index 8b238ad8d3..9c22ddeec9 100644
--- a/apps/web/lib/actions/partners/reactivate-partner.ts
+++ b/apps/web/lib/actions/partners/reactivate-partner.ts
@@ -68,6 +68,8 @@ export const reactivatePartnerAction = authActionClient
clickRewardId: partnerGroup.clickRewardId,
leadRewardId: partnerGroup.leadRewardId,
saleRewardId: partnerGroup.saleRewardId,
+ referralRewardId: partnerGroup.referralRewardId,
+ customRewardId: partnerGroup.customRewardId,
discountId: partnerGroup.discountId,
},
}),
diff --git a/apps/web/lib/actions/partners/unban-partner.ts b/apps/web/lib/actions/partners/unban-partner.ts
index 664970d4c1..19b54c85c0 100644
--- a/apps/web/lib/actions/partners/unban-partner.ts
+++ b/apps/web/lib/actions/partners/unban-partner.ts
@@ -74,6 +74,8 @@ export const unbanPartnerAction = authActionClient
clickRewardId: partnerGroup.clickRewardId,
leadRewardId: partnerGroup.leadRewardId,
saleRewardId: partnerGroup.saleRewardId,
+ referralRewardId: partnerGroup.referralRewardId,
+ customRewardId: partnerGroup.customRewardId,
discountId: partnerGroup.discountId,
},
}),
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index 3fb38389bb..7aa0951db2 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -105,6 +105,7 @@ export const updateRewardAction = authActionClient
leadPartnerGroup: true,
salePartnerGroup: true,
referralPartnerGroup: true,
+ customPartnerGroup: true,
},
});
@@ -113,6 +114,7 @@ export const updateRewardAction = authActionClient
leadPartnerGroup,
salePartnerGroup,
referralPartnerGroup,
+ customPartnerGroup,
...rewardMetadata
} = updatedReward;
@@ -121,7 +123,8 @@ export const updateRewardAction = authActionClient
clickPartnerGroup ||
leadPartnerGroup ||
salePartnerGroup ||
- referralPartnerGroup;
+ referralPartnerGroup ||
+ customPartnerGroup;
if (!partnerGroup) {
throw new Error("Partner group not found.");
diff --git a/apps/web/lib/api/groups/get-group-or-throw.ts b/apps/web/lib/api/groups/get-group-or-throw.ts
index a8c6a80a23..fad403e21b 100644
--- a/apps/web/lib/api/groups/get-group-or-throw.ts
+++ b/apps/web/lib/api/groups/get-group-or-throw.ts
@@ -31,6 +31,7 @@ export const getGroupOrThrow = async ({
leadReward: includeExpandedFields,
saleReward: includeExpandedFields,
referralReward: includeExpandedFields,
+ customReward: includeExpandedFields,
discount: includeExpandedFields,
utmTemplate: includeExpandedFields,
partnerGroupDefaultLinks: includeExpandedFields,
diff --git a/apps/web/lib/api/groups/move-partners-to-group.ts b/apps/web/lib/api/groups/move-partners-to-group.ts
index b1285eaaee..8b9ba026ef 100644
--- a/apps/web/lib/api/groups/move-partners-to-group.ts
+++ b/apps/web/lib/api/groups/move-partners-to-group.ts
@@ -29,6 +29,7 @@ interface MovePartnersToGroupParams {
| "leadRewardId"
| "saleRewardId"
| "referralRewardId"
+ | "customRewardId"
| "discountId"
>;
isGroupDeleted?: boolean;
@@ -87,6 +88,7 @@ export async function movePartnersToGroup({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
...(groupMoveDisabledAt !== undefined && { groupMoveDisabledAt }),
},
diff --git a/apps/web/lib/api/partners/applications/approve-partner.ts b/apps/web/lib/api/partners/applications/approve-partner.ts
index 0bb6267549..164c058ba7 100644
--- a/apps/web/lib/api/partners/applications/approve-partner.ts
+++ b/apps/web/lib/api/partners/applications/approve-partner.ts
@@ -100,6 +100,7 @@ export async function approvePartner({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/lib/api/partners/applications/reject-partner.ts b/apps/web/lib/api/partners/applications/reject-partner.ts
index 56e5a5d60b..4380273f93 100644
--- a/apps/web/lib/api/partners/applications/reject-partner.ts
+++ b/apps/web/lib/api/partners/applications/reject-partner.ts
@@ -128,6 +128,7 @@ export async function rejectPartner({
leadRewardId: null,
saleRewardId: null,
referralRewardId: null,
+ customRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/api/partners/bulk-reactivate-partners.ts b/apps/web/lib/api/partners/bulk-reactivate-partners.ts
index c837635542..20a97e9cd0 100644
--- a/apps/web/lib/api/partners/bulk-reactivate-partners.ts
+++ b/apps/web/lib/api/partners/bulk-reactivate-partners.ts
@@ -51,6 +51,7 @@ export async function bulkReactivatePartners({
leadRewardId: true,
saleRewardId: true,
referralRewardId: true,
+ customRewardId: true,
discountId: true,
},
});
@@ -132,6 +133,7 @@ export async function bulkReactivatePartners({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/lib/api/partners/create-and-enroll-partner.ts b/apps/web/lib/api/partners/create-and-enroll-partner.ts
index c398e3263a..d98f4d5ea1 100644
--- a/apps/web/lib/api/partners/create-and-enroll-partner.ts
+++ b/apps/web/lib/api/partners/create-and-enroll-partner.ts
@@ -166,6 +166,7 @@ export const createAndEnrollPartner = async ({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
enrolledAt,
});
diff --git a/apps/web/lib/api/partners/create-or-get-program-enrollment.ts b/apps/web/lib/api/partners/create-or-get-program-enrollment.ts
index fceee37486..c2b2b2c295 100644
--- a/apps/web/lib/api/partners/create-or-get-program-enrollment.ts
+++ b/apps/web/lib/api/partners/create-or-get-program-enrollment.ts
@@ -15,6 +15,7 @@ export async function createOrGetProgramEnrollment({
leadRewardId,
saleRewardId,
referralRewardId,
+ customRewardId,
discountId,
enrolledAt,
}: Pick<
@@ -28,6 +29,7 @@ export async function createOrGetProgramEnrollment({
| "leadRewardId"
| "saleRewardId"
| "referralRewardId"
+ | "customRewardId"
| "discountId"
> & {
enrolledAt?: Date;
@@ -45,6 +47,7 @@ export async function createOrGetProgramEnrollment({
leadRewardId,
saleRewardId,
referralRewardId,
+ customRewardId,
discountId,
...(enrolledAt && {
createdAt: enrolledAt,
diff --git a/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts b/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts
index 402abbc67c..8f9b943553 100644
--- a/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts
+++ b/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts
@@ -9,6 +9,7 @@ const REWARD_ICONS: Record<EventType, string> = {
lead: "https://assets.dub.co/email-assets/icons/user-plus.png",
sale: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
referral: "https://assets.dub.co/email-assets/icons/nodes-4.png",
+ custom: "https://assets.dub.co/cms/icon-calendar-bounty.png",
};
const BOUNTY_ICONS: Record<BountyType, string> = {
@@ -37,6 +38,7 @@ export async function getGroupRewardsAndBounties({
group.leadReward,
group.saleReward,
group.referralReward,
+ group.customReward,
]
.filter((r): r is Reward => r !== null)
.map((reward) => ({
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 1b28b2dcbb..784646c401 100644
--- a/apps/web/lib/api/partners/notify-partner-reward-change.ts
+++ b/apps/web/lib/api/partners/notify-partner-reward-change.ts
@@ -9,6 +9,7 @@ const REWARD_ICONS: Record<RewardProps["event"], string> = {
lead: "https://assets.dub.co/email-assets/icons/user-plus.png",
sale: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
referral: "https://assets.dub.co/email-assets/icons/nodes-4.png",
+ custom: "https://assets.dub.co/cms/icon-calendar-bounty.png",
};
interface NotifyPartnerRewardChangeParams {
diff --git a/apps/web/lib/api/partners/process-partner-deactivation.ts b/apps/web/lib/api/partners/process-partner-deactivation.ts
index ccfb48dc41..71c5aee82c 100644
--- a/apps/web/lib/api/partners/process-partner-deactivation.ts
+++ b/apps/web/lib/api/partners/process-partner-deactivation.ts
@@ -62,6 +62,7 @@ export async function processPartnerDeactivation({
leadRewardId: null,
saleRewardId: null,
referralRewardId: null,
+ customRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/api/rewards/create-custom-reward-commissions.ts b/apps/web/lib/api/rewards/create-custom-reward-commissions.ts
new file mode 100644
index 0000000000..f4c76726db
--- /dev/null
+++ b/apps/web/lib/api/rewards/create-custom-reward-commissions.ts
@@ -0,0 +1,190 @@
+import { dispatchWorkflows } from "@/lib/jobs/publish-workflows";
+import { prisma } from "@/lib/prisma";
+import { customRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { pluck } from "@dub/utils";
+import {
+ CommissionType,
+ EventType,
+ ProgramEnrollmentStatus,
+} from "@prisma/client";
+import {
+ buildCommissionIdempotencyKey,
+ formatCommissionDescription,
+ hasRewardMaxDurationElapsed,
+ toUtcDateOnly,
+} from "./custom-reward-utils";
+
+const PAGE_SIZE = 100;
+
+export async function createCustomRewardCommissions({
+ rewardId,
+ periodDate,
+ startAfterPartnerId,
+}: {
+ rewardId: string;
+ periodDate: string;
+ startAfterPartnerId?: string;
+}) {
+ const reward = await prisma.reward.findUnique({
+ where: {
+ id: rewardId,
+ },
+ select: {
+ id: true,
+ programId: true,
+ event: true,
+ amountInCents: true,
+ maxDuration: true,
+ config: true,
+ },
+ });
+
+ if (!reward || reward.event !== EventType.custom || !reward.programId) {
+ console.info(
+ `[createCustomRewardCommissions] Reward ${rewardId} not found or not a custom reward. Skipping...`,
+ );
+ return {
+ nextCursor: null,
+ };
+ }
+
+ if (reward.amountInCents == null) {
+ console.info(
+ `[createCustomRewardCommissions] Reward ${rewardId} has no amountInCents. Skipping...`,
+ );
+ return {
+ nextCursor: null,
+ };
+ }
+
+ const parsedConfig = customRewardConfigSchema.safeParse(reward.config);
+
+ if (!parsedConfig.success) {
+ console.error(
+ `[createCustomRewardCommissions] Invalid config for reward ${rewardId}. Skipping...`,
+ );
+ return {
+ nextCursor: null,
+ };
+ }
+
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ customRewardId: rewardId,
+ status: ProgramEnrollmentStatus.approved,
+ ...(startAfterPartnerId && {
+ partnerId: {
+ gt: startAfterPartnerId,
+ },
+ }),
+ },
+ select: {
+ partnerId: true,
+ programId: true,
+ },
+ orderBy: {
+ partnerId: "asc",
+ },
+ take: PAGE_SIZE,
+ });
+
+ if (enrollments.length === 0) {
+ return {
+ nextCursor: null,
+ };
+ }
+
+ const partnerIds = pluck(enrollments, "partnerId");
+ const firstCommissionAtByPartnerId = new Map<string, Date | null>();
+
+ // Batch-fetch each partner's earliest custom commission so we can enforce maxDuration
+ // without N+1 queries. Skip when maxDuration is unlimited (null).
+ if (reward.maxDuration != null) {
+ const firstCommissions = await prisma.commission.groupBy({
+ by: ["partnerId"],
+ where: {
+ programId: reward.programId,
+ partnerId: {
+ in: partnerIds,
+ },
+ rewardId: reward.id,
+ type: CommissionType.custom,
+ },
+ _min: {
+ createdAt: true,
+ },
+ });
+
+ for (const commission of firstCommissions) {
+ firstCommissionAtByPartnerId.set(
+ commission.partnerId,
+ commission._min.createdAt,
+ );
+ }
+ }
+
+ const description = formatCommissionDescription({
+ amountInCents: reward.amountInCents,
+ frequency: parsedConfig.data.frequency,
+ interval: parsedConfig.data.interval,
+ periodDate,
+ });
+
+ const eligibleEnrollments = enrollments.filter((enrollment) => {
+ const firstCommissionAt = firstCommissionAtByPartnerId.get(
+ enrollment.partnerId,
+ );
+
+ // Skip partners whose first custom commission is already maxDuration months ago.
+ // No first commission means they haven't started earning yet, so they're still eligible.
+ return !(
+ firstCommissionAt &&
+ hasRewardMaxDurationElapsed({
+ firstCommissionAt,
+ maxDuration: reward.maxDuration,
+ periodDate,
+ })
+ );
+ });
+
+ const jobs = eligibleEnrollments.map((enrollment) => {
+ const invoiceId = buildCommissionIdempotencyKey({
+ rewardId: reward.id,
+ partnerId: enrollment.partnerId,
+ periodDate,
+ });
+
+ return {
+ name: "create-partner-commission-workflow" as const,
+ payload: {
+ event: CommissionType.custom,
+ partnerId: enrollment.partnerId,
+ programId: enrollment.programId,
+ amount: reward.amountInCents,
+ quantity: 1,
+ rewardId: reward.id,
+ invoiceId,
+ description,
+ createdAt: toUtcDateOnly(periodDate),
+ },
+ options: {
+ label: enrollment.partnerId,
+ flowControl: {
+ key: "create-custom-reward-commissions",
+ parallelism: 10,
+ },
+ },
+ };
+ });
+
+ await dispatchWorkflows(jobs);
+
+ const nextCursor =
+ enrollments.length === PAGE_SIZE
+ ? enrollments[enrollments.length - 1].partnerId
+ : null;
+
+ return {
+ nextCursor,
+ };
+}
diff --git a/apps/web/lib/api/rewards/custom-reward-utils.ts b/apps/web/lib/api/rewards/custom-reward-utils.ts
new file mode 100644
index 0000000000..4b151a4719
--- /dev/null
+++ b/apps/web/lib/api/rewards/custom-reward-utils.ts
@@ -0,0 +1,189 @@
+import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import type { CustomRewardConfig } from "@/lib/types";
+import { CUSTOM_REWARD_CADENCE_PRESETS } from "@/lib/zod/schemas/rewards";
+import { tz } from "@date-fns/tz";
+import { pluralize } from "@dub/utils";
+import { EventType } from "@prisma/client";
+import { createHash } from "crypto";
+import {
+ differenceInCalendarDays,
+ differenceInCalendarMonths,
+ differenceInCalendarYears,
+ differenceInMonths,
+ format,
+} from "date-fns";
+
+export function isEventBasedReward<T extends { event: EventType }>(
+ reward: T,
+): reward is T & { event: Exclude<EventType, "custom"> } {
+ return reward.event !== EventType.custom;
+}
+
+export function toUtcDateOnly(date: Date | string): Date {
+ if (typeof date === "string") {
+ const [year, month, day] = date.split("-").map(Number);
+ return new Date(Date.UTC(year, month - 1, day));
+ }
+
+ return new Date(
+ Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()),
+ );
+}
+
+function formatUtcDate(date: Date): string {
+ const year = date.getUTCFullYear();
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
+ const day = String(date.getUTCDate()).padStart(2, "0");
+ return `${year}-${month}-${day}`;
+}
+
+export function getUtcPeriodDate(date: Date | string = new Date()): string {
+ return formatUtcDate(toUtcDateOnly(date));
+}
+
+export function isCustomRewardStartDateInPast(anchorDate: string): boolean {
+ return anchorDate < getUtcPeriodDate();
+}
+
+function daysInUtcMonth(year: number, monthIndex: number) {
+ return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
+}
+
+function expectedUtcDayOfMonth(anchor: Date, candidate: Date) {
+ const anchorDay = anchor.getUTCDate();
+ const daysInCandidateMonth = daysInUtcMonth(
+ candidate.getUTCFullYear(),
+ candidate.getUTCMonth(),
+ );
+ return Math.min(anchorDay, daysInCandidateMonth);
+}
+
+export function isCadenceDue(
+ config: CustomRewardConfig,
+ dateUTC: Date | string,
+): boolean {
+ const today = toUtcDateOnly(dateUTC);
+ const anchor = toUtcDateOnly(config.anchorDate);
+
+ if (today.getTime() < anchor.getTime()) {
+ return false;
+ }
+
+ const { frequency, interval } = config;
+
+ if (frequency === "day") {
+ const daysDiff = differenceInCalendarDays(today, anchor, { in: tz("UTC") });
+ return daysDiff % interval === 0;
+ }
+
+ if (frequency === "week") {
+ const daysDiff = differenceInCalendarDays(today, anchor, { in: tz("UTC") });
+ return daysDiff % (interval * 7) === 0;
+ }
+
+ if (frequency === "month") {
+ if (today.getUTCDate() !== expectedUtcDayOfMonth(anchor, today)) {
+ return false;
+ }
+
+ const monthsDiff = differenceInCalendarMonths(today, anchor, {
+ in: tz("UTC"),
+ });
+ return monthsDiff % interval === 0;
+ }
+
+ // year
+ if (
+ today.getUTCMonth() !== anchor.getUTCMonth() ||
+ today.getUTCDate() !== expectedUtcDayOfMonth(anchor, today)
+ ) {
+ return false;
+ }
+
+ const yearsDiff = differenceInCalendarYears(today, anchor, { in: tz("UTC") });
+ return yearsDiff % interval === 0;
+}
+
+const CADENCE_LABELS: Record<CustomRewardConfig["frequency"], string> = {
+ day: "daily",
+ week: "weekly",
+ month: "monthly",
+ year: "yearly",
+};
+
+export function formatCadenceLabel({
+ frequency,
+ interval,
+}: Pick<CustomRewardConfig, "frequency" | "interval">) {
+ const preset = CUSTOM_REWARD_CADENCE_PRESETS.find(
+ (p) => p.frequency === frequency && p.interval === interval,
+ );
+
+ if (preset) {
+ return preset.label.toLowerCase();
+ }
+
+ if (interval === 1) {
+ return CADENCE_LABELS[frequency];
+ }
+
+ return `every ${interval} ${pluralize(frequency, interval)}`;
+}
+
+export function formatCommissionDescription({
+ amountInCents,
+ frequency,
+ interval,
+ periodDate,
+}: Pick<CustomRewardConfig, "frequency" | "interval"> & {
+ amountInCents: number;
+ periodDate: string;
+}) {
+ const cadenceLabel = formatCadenceLabel({ frequency, interval });
+ const periodFormat =
+ frequency === "day" || frequency === "week" ? "MMM d, yyyy" : "MMM yyyy";
+ const periodLabel = format(toUtcDateOnly(periodDate), periodFormat, {
+ in: tz("UTC"),
+ });
+ const amountLabel = constructRewardAmount({
+ type: "flat",
+ amountInCents,
+ amountInPercentage: null,
+ });
+
+ return `${amountLabel} ${cadenceLabel} · ${periodLabel}`;
+}
+
+export function buildCommissionIdempotencyKey({
+ rewardId,
+ partnerId,
+ periodDate,
+}: {
+ rewardId: string;
+ partnerId: string;
+ periodDate: string;
+}) {
+ return createHash("sha256")
+ .update(`custom_${rewardId}_${partnerId}_${periodDate}`)
+ .digest("hex");
+}
+
+export function hasRewardMaxDurationElapsed({
+ firstCommissionAt,
+ maxDuration,
+ periodDate,
+}: {
+ firstCommissionAt: Date;
+ maxDuration: number | null | undefined;
+ periodDate: Date | string;
+}): boolean {
+ // null / undefined = infinite
+ if (maxDuration == null) {
+ return false;
+ }
+
+ const period = toUtcDateOnly(periodDate);
+ const first = toUtcDateOnly(firstCommissionAt);
+
+ return differenceInMonths(period, first, { in: tz("UTC") }) >= maxDuration;
+}
diff --git a/apps/web/lib/api/rewards/find-due-custom-rewards.ts b/apps/web/lib/api/rewards/find-due-custom-rewards.ts
new file mode 100644
index 0000000000..7a032bf020
--- /dev/null
+++ b/apps/web/lib/api/rewards/find-due-custom-rewards.ts
@@ -0,0 +1,89 @@
+import { CRON_BATCH_SIZE } from "@/lib/cron";
+import { prisma } from "@/lib/prisma";
+import type { CustomRewardConfig } from "@/lib/types";
+import { customRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { EventType } from "@prisma/client";
+import { getUtcPeriodDate, isCadenceDue } from "./custom-reward-utils";
+
+export type DueCustomReward = {
+ id: string;
+ programId: string;
+ amountInCents: number;
+ maxDuration: number | null;
+ config: CustomRewardConfig;
+};
+
+export async function findDueCustomRewards({
+ periodDate = getUtcPeriodDate(),
+}: {
+ periodDate?: string;
+} = {}): Promise<DueCustomReward[]> {
+ const due: DueCustomReward[] = [];
+ let startAfterId: string | undefined;
+
+ while (true) {
+ const rewards = await prisma.reward.findMany({
+ where: {
+ event: EventType.custom,
+ programId: {
+ not: null,
+ },
+ ...(startAfterId && {
+ id: {
+ gt: startAfterId,
+ },
+ }),
+ },
+ select: {
+ id: true,
+ programId: true,
+ amountInCents: true,
+ maxDuration: true,
+ config: true,
+ },
+ orderBy: {
+ id: "asc",
+ },
+ take: CRON_BATCH_SIZE,
+ });
+
+ if (rewards.length === 0) {
+ break;
+ }
+
+ for (const reward of rewards) {
+ if (!reward.programId || reward.amountInCents == null) {
+ continue;
+ }
+
+ const parsedConfig = customRewardConfigSchema.safeParse(reward.config);
+
+ if (!parsedConfig.success) {
+ console.error(
+ `[findDueCustomRewards] Invalid config for reward ${reward.id}. Skipping...`,
+ );
+ continue;
+ }
+
+ if (!isCadenceDue(parsedConfig.data, periodDate)) {
+ continue;
+ }
+
+ due.push({
+ id: reward.id,
+ programId: reward.programId,
+ amountInCents: reward.amountInCents,
+ maxDuration: reward.maxDuration,
+ config: parsedConfig.data,
+ });
+ }
+
+ startAfterId = rewards[rewards.length - 1].id;
+
+ if (rewards.length < CRON_BATCH_SIZE) {
+ break;
+ }
+ }
+
+ return due;
+}
diff --git a/apps/web/lib/api/rewards/validate-reward.ts b/apps/web/lib/api/rewards/validate-reward.ts
index 3e062ad4b6..b541672b3f 100644
--- a/apps/web/lib/api/rewards/validate-reward.ts
+++ b/apps/web/lib/api/rewards/validate-reward.ts
@@ -4,11 +4,13 @@ import {
} from "@/lib/partner-referrals/constants";
import {
createOrUpdateRewardSchema,
+ customRewardConfigSchema,
referralRewardConfigSchema,
rewardConditionsArraySchema,
} from "@/lib/zod/schemas/rewards";
import * as z from "zod/v4";
import { DubApiError } from "../errors";
+import { isCustomRewardStartDateInPast } from "./custom-reward-utils";
export function validateReward(
reward: Partial<z.infer<typeof createOrUpdateRewardSchema>>,
@@ -37,6 +39,68 @@ export function validateReward(
}
}
+ if (reward.event === "custom") {
+ if (reward.type === "percentage") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Percentage rewards are not allowed for custom events.",
+ });
+ }
+
+ if (reward.amountInCents == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInCents must be provided for custom events.",
+ });
+ }
+
+ if (reward.amountInPercentage != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInPercentage is not allowed for custom events.",
+ });
+ }
+
+ if (reward.modifiers != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Reward modifiers are not allowed for custom rewards.",
+ });
+ }
+
+ if (reward.spendLimitAmount != null || reward.spendLimitInterval != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Spend limits are not allowed for custom rewards.",
+ });
+ }
+
+ if (reward.maxDuration === 0) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "maxDuration cannot be 0 for custom rewards. Use a manual commission for one-off payments.",
+ });
+ }
+
+ const parsedConfig = customRewardConfigSchema.safeParse(reward.config);
+
+ if (!parsedConfig.success) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "config must include frequency, interval, and anchorDate for custom rewards.",
+ });
+ }
+
+ if (isCustomRewardStartDateInPast(parsedConfig.data.anchorDate)) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Start date cannot be in the past.",
+ });
+ }
+ }
+
if (reward.event === "sale") {
if (reward.amountInCents != null && reward.amountInPercentage != null) {
throw new DubApiError({
diff --git a/apps/web/lib/api/workflows/move-group/execute.ts b/apps/web/lib/api/workflows/move-group/execute.ts
index 1174b41e5d..1460b7a40d 100644
--- a/apps/web/lib/api/workflows/move-group/execute.ts
+++ b/apps/web/lib/api/workflows/move-group/execute.ts
@@ -100,6 +100,7 @@ export const executeMoveGroupWorkflow = async ({
leadRewardId: true,
saleRewardId: true,
referralRewardId: true,
+ customRewardId: true,
discountId: true,
},
});
diff --git a/apps/web/lib/firstpromoter/import-partners.ts b/apps/web/lib/firstpromoter/import-partners.ts
index 2a137b0738..1cf3c4d959 100644
--- a/apps/web/lib/firstpromoter/import-partners.ts
+++ b/apps/web/lib/firstpromoter/import-partners.ts
@@ -196,6 +196,7 @@ async function createPartnerAndLinks({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
update: {
diff --git a/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts b/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts
index 2c9d26eaad..635990362c 100644
--- a/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts
+++ b/apps/web/lib/jobs/handlers/auto-reject-partner-job.ts
@@ -90,6 +90,7 @@ export const autoRejectPartnerJob = defineJob({
leadRewardId: null,
saleRewardId: null,
referralRewardId: null,
+ customRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/jobs/handlers/create-custom-commission-job.ts b/apps/web/lib/jobs/handlers/create-custom-commission-job.ts
new file mode 100644
index 0000000000..18e2009acd
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/create-custom-commission-job.ts
@@ -0,0 +1,34 @@
+import { createCustomRewardCommissions } from "@/lib/api/rewards/create-custom-reward-commissions";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+
+const inputSchema = z.object({
+ rewardId: z.string(),
+ periodDate: z.iso.date(),
+ startAfterPartnerId: z.string().optional(),
+});
+
+export const createCustomCommissionJob = defineJob({
+ name: "create-custom-commission-job",
+ schema: inputSchema,
+ defaults: {
+ retries: 3,
+ },
+ async handle(input) {
+ const { nextCursor } = await createCustomRewardCommissions(input);
+
+ if (nextCursor) {
+ await createCustomCommissionJob.dispatch(
+ {
+ rewardId: input.rewardId,
+ periodDate: input.periodDate,
+ startAfterPartnerId: nextCursor,
+ },
+ {
+ label: input.rewardId,
+ delay: 1,
+ },
+ );
+ }
+ },
+});
diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.ts
index 91313d0c46..4b4e06485d 100644
--- a/apps/web/lib/jobs/registry.ts
+++ b/apps/web/lib/jobs/registry.ts
@@ -65,6 +65,11 @@ const jobLoaders = {
import("./handlers/send-partner-program-summary-job").then(
(m) => m.sendPartnerProgramSummaryJob,
),
+
+ "create-custom-commission-job": () =>
+ import("./handlers/create-custom-commission-job").then(
+ (m) => m.createCustomCommissionJob,
+ ),
} as const satisfies Record<string, () => Promise<JobDefinition>>;
const jobCache = new Map<string, JobDefinition>();
diff --git a/apps/web/lib/lemonsqueezy/import-partners.ts b/apps/web/lib/lemonsqueezy/import-partners.ts
index dc2f818ab0..9c09242796 100644
--- a/apps/web/lib/lemonsqueezy/import-partners.ts
+++ b/apps/web/lib/lemonsqueezy/import-partners.ts
@@ -33,6 +33,7 @@ export async function importPartners(payload: LemonSqueezyImportPayload) {
leadRewardId: true,
saleRewardId: true,
referralRewardId: true,
+ customRewardId: true,
discountId: true,
},
},
@@ -192,6 +193,7 @@ async function createPartnerAndLinks({
| "leadRewardId"
| "saleRewardId"
| "referralRewardId"
+ | "customRewardId"
>;
userId: string;
importId: string;
@@ -239,6 +241,7 @@ async function createPartnerAndLinks({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
update: {
diff --git a/apps/web/lib/partners/complete-program-applications.ts b/apps/web/lib/partners/complete-program-applications.ts
index ad61cfa69e..5e91493af9 100644
--- a/apps/web/lib/partners/complete-program-applications.ts
+++ b/apps/web/lib/partners/complete-program-applications.ts
@@ -103,6 +103,8 @@ export async function completeProgramApplications(userEmail: string) {
clickRewardId: programApplication?.partnerGroup?.clickRewardId,
leadRewardId: programApplication?.partnerGroup?.leadRewardId,
saleRewardId: programApplication?.partnerGroup?.saleRewardId,
+ customRewardId: programApplication?.partnerGroup?.customRewardId,
+ referralRewardId: programApplication?.partnerGroup?.referralRewardId,
discountId: programApplication?.partnerGroup?.discountId,
}));
diff --git a/apps/web/lib/partners/get-group-rewards-and-discount.ts b/apps/web/lib/partners/get-group-rewards-and-discount.ts
index eb6fde431e..5a710e0a9c 100644
--- a/apps/web/lib/partners/get-group-rewards-and-discount.ts
+++ b/apps/web/lib/partners/get-group-rewards-and-discount.ts
@@ -1,3 +1,4 @@
+import { isEventBasedReward } from "@/lib/api/rewards/custom-reward-utils";
import { GroupProps, RewardProps } from "@/lib/types";
// Determines the rewards and discount for the partner group
@@ -7,9 +8,9 @@ export function getGroupRewardsAndDiscount({
leadReward,
discount,
}: Pick<GroupProps, "clickReward" | "saleReward" | "leadReward" | "discount">) {
- const rewards = [clickReward, saleReward, leadReward].filter(
- (r): r is RewardProps => r !== null,
- );
+ const rewards = [clickReward, saleReward, leadReward]
+ .filter((r): r is RewardProps => r !== null)
+ .filter(isEventBasedReward);
return {
rewards,
diff --git a/apps/web/lib/partnerstack/import-partners.ts b/apps/web/lib/partnerstack/import-partners.ts
index 6812bae8e0..d6e746a635 100644
--- a/apps/web/lib/partnerstack/import-partners.ts
+++ b/apps/web/lib/partnerstack/import-partners.ts
@@ -196,6 +196,7 @@ async function createPartner({
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
update: {
diff --git a/apps/web/lib/rewardful/import-partners.ts b/apps/web/lib/rewardful/import-partners.ts
index adaf6ccd3d..33b4cb0b98 100644
--- a/apps/web/lib/rewardful/import-partners.ts
+++ b/apps/web/lib/rewardful/import-partners.ts
@@ -97,6 +97,7 @@ export async function importPartners(payload: RewardfulImportPayload) {
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
partnerGroupDefaultLinkId:
@@ -176,6 +177,7 @@ async function createPartnerAndLinks({
leadRewardId: string | null;
clickRewardId: string | null;
referralRewardId: string | null;
+ customRewardId: string | null;
discountId: string | null;
};
partnerGroupDefaultLinkId?: string | null;
diff --git a/apps/web/lib/tapfiliate/import-partners.ts b/apps/web/lib/tapfiliate/import-partners.ts
index 5a149bca50..46d9aec45e 100644
--- a/apps/web/lib/tapfiliate/import-partners.ts
+++ b/apps/web/lib/tapfiliate/import-partners.ts
@@ -27,6 +27,8 @@ export async function importPartners(payload: TapfiliateImportPayload) {
clickRewardId: true,
leadRewardId: true,
saleRewardId: true,
+ referralRewardId: true,
+ customRewardId: true,
discountId: true,
},
},
@@ -182,7 +184,13 @@ async function createPartnerAndLinks({
affiliate: TapfiliatePartner;
group: Pick<
PartnerGroup,
- "id" | "discountId" | "clickRewardId" | "leadRewardId" | "saleRewardId"
+ | "id"
+ | "discountId"
+ | "clickRewardId"
+ | "leadRewardId"
+ | "saleRewardId"
+ | "referralRewardId"
+ | "customRewardId"
>;
userId: string;
importId: string;
@@ -234,6 +242,8 @@ async function createPartnerAndLinks({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
update: {
diff --git a/apps/web/lib/tolt/import-partners.ts b/apps/web/lib/tolt/import-partners.ts
index 32cdf4749a..91fa1278dc 100644
--- a/apps/web/lib/tolt/import-partners.ts
+++ b/apps/web/lib/tolt/import-partners.ts
@@ -74,6 +74,8 @@ export async function importPartners(payload: ToltImportPayload) {
saleRewardId: defaultGroup.saleRewardId,
leadRewardId: defaultGroup.leadRewardId,
clickRewardId: defaultGroup.clickRewardId,
+ customRewardId: defaultGroup.customRewardId,
+ referralRewardId: defaultGroup.referralRewardId,
discountId: defaultGroup.discountId,
},
}),
@@ -139,6 +141,8 @@ async function createPartner({
saleRewardId: string | null;
leadRewardId: string | null;
clickRewardId: string | null;
+ customRewardId: string | null;
+ referralRewardId: string | null;
discountId: string | null;
};
}) {
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 6caa1e933f..81182d61ea 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -179,6 +179,7 @@ import {
} from "./zod/schemas/programs";
import {
CUSTOMER_SOURCES,
+ customRewardConfigSchema,
rewardConditionsArraySchema,
rewardConditionSchema,
rewardConditionsSchema,
@@ -649,6 +650,8 @@ export type FolderSummary = Pick<
export type RewardProps = z.infer<typeof RewardSchema>;
+export type CustomRewardConfig = z.infer<typeof customRewardConfigSchema>;
+
export type CreatePartnerProps = z.infer<typeof createPartnerSchema>;
export type ProgramData = z.infer<typeof programDataSchema>;
diff --git a/apps/web/lib/zod/schemas/activity-log.ts b/apps/web/lib/zod/schemas/activity-log.ts
index ef80f6b66a..ac00b470ce 100644
--- a/apps/web/lib/zod/schemas/activity-log.ts
+++ b/apps/web/lib/zod/schemas/activity-log.ts
@@ -8,6 +8,7 @@ export const activityLogResourceTypeSchema = z.enum([
"saleReward",
"leadReward",
"referralReward",
+ "customReward",
"submittedLead",
]);
@@ -67,4 +68,5 @@ export const REWARD_EVENT_TO_RESOURCE_TYPE = {
sale: "saleReward",
lead: "leadReward",
referral: "referralReward",
+ custom: "customReward",
} as const;
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index 4ad4906a57..c25b26467b 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -486,6 +486,7 @@ export const createPartnerCommissionSchema = z.object({
customerId: z.string().optional(),
eventId: z.string().optional(),
invoiceId: z.string().nullish(),
+ rewardId: z.string().optional(),
amount: z.number().default(0).optional(),
quantity: z.number().default(1),
currency: z.string().optional(),
diff --git a/apps/web/lib/zod/schemas/groups.ts b/apps/web/lib/zod/schemas/groups.ts
index f512fa55a1..472a6a516f 100644
--- a/apps/web/lib/zod/schemas/groups.ts
+++ b/apps/web/lib/zod/schemas/groups.ts
@@ -68,6 +68,7 @@ export const GroupSchema = z.object({
leadReward: RewardSchema.nullish(),
saleReward: RewardSchema.nullish(),
referralReward: RewardSchema.nullish(),
+ customReward: RewardSchema.nullish(),
discount: DiscountSchema.nullish(),
utmTemplate: UTMTemplateSchema.nullish(),
additionalLinks: z.array(additionalPartnerLinkSchema).nullable(),
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index f9054c9a07..dc12588ff4 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -163,6 +163,7 @@ export const ProgramEnrollmentSchema = z.object({
leadRewardId: z.string().nullish(),
saleRewardId: z.string().nullish(),
referralRewardId: z.string().nullish(),
+ customRewardId: z.string().nullish(),
discount: DiscountSchema.nullish(),
discountId: z.string().nullish(),
applicationId: z
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 4fdaf662b9..9625db73a8 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -233,6 +233,11 @@ export const REWARD_CONDITIONS: Record<
referral: {
entities: [],
},
+
+ // Custom cadence reward (no modifiers)
+ custom: {
+ entities: [],
+ },
};
const REWARD_CONDITION_ENTITIES = [
@@ -469,6 +474,58 @@ export const referralRewardConfigSchema = z
}
});
+export const CUSTOM_REWARD_FREQUENCIES = [
+ "day",
+ "week",
+ "month",
+ "year",
+] as const;
+
+export const customRewardConfigSchema = z.object({
+ frequency: z.enum(CUSTOM_REWARD_FREQUENCIES),
+ interval: z.number().int().positive(),
+ anchorDate: z.iso.date(),
+});
+
+export const CUSTOM_REWARD_CADENCE_PRESETS = [
+ {
+ value: "daily",
+ label: "Daily",
+ frequency: "day" as const,
+ interval: 1,
+ },
+ {
+ value: "weekly",
+ label: "Weekly",
+ frequency: "week" as const,
+ interval: 1,
+ },
+ {
+ value: "biweekly",
+ label: "Biweekly",
+ frequency: "week" as const,
+ interval: 2,
+ },
+ {
+ value: "monthly",
+ label: "Monthly",
+ frequency: "month" as const,
+ interval: 1,
+ },
+ {
+ value: "quarterly",
+ label: "Quarterly",
+ frequency: "month" as const,
+ interval: 3,
+ },
+ {
+ value: "yearly",
+ label: "Yearly",
+ frequency: "year" as const,
+ interval: 1,
+ },
+] as const;
+
export const createOrUpdateRewardSchema = z.object({
workspaceId: z.string(),
event: z.enum(EventType),
@@ -477,7 +534,9 @@ export const createOrUpdateRewardSchema = z.object({
amountInPercentage: PERCENTAGE_REWARD_AMOUNT_SCHEMA.optional(),
maxDuration: maxDurationSchema,
modifiers: rewardConditionsArraySchema.nullish(),
- config: referralRewardConfigSchema.nullish(),
+ config: z
+ .union([referralRewardConfigSchema, customRewardConfigSchema])
+ .nullish(),
description: z.string().max(REWARD_DESCRIPTION_MAX_LENGTH).nullish(),
tooltipDescription: z
.string()
@@ -517,6 +576,7 @@ export const REWARD_EVENT_COLUMN_MAPPING = Object.freeze({
lead: "leadRewardId",
sale: "saleRewardId",
referral: "referralRewardId",
+ custom: "customRewardId",
});
export const CUSTOMER_SOURCES = ["tracked", "submitted", "trial"] as const;
diff --git a/apps/web/prisma/schema/group.prisma b/apps/web/prisma/schema/group.prisma
index 80b0606f22..b18000c877 100644
--- a/apps/web/prisma/schema/group.prisma
+++ b/apps/web/prisma/schema/group.prisma
@@ -14,6 +14,7 @@ model PartnerGroup {
leadRewardId String? @unique
saleRewardId String? @unique
referralRewardId String? @unique
+ customRewardId String? @unique
discountId String? @unique
linkStructure PartnerLinkStructure @default(short)
additionalLinks Json? @db.Json
@@ -37,6 +38,7 @@ model PartnerGroup {
leadReward Reward? @relation("LeadReward", fields: [leadRewardId], references: [id])
saleReward Reward? @relation("SaleReward", fields: [saleRewardId], references: [id])
referralReward Reward? @relation("ReferralReward", fields: [referralRewardId], references: [id])
+ customReward Reward? @relation("CustomReward", fields: [customRewardId], references: [id])
discount Discount? @relation(fields: [discountId], references: [id])
partners ProgramEnrollment[]
applications ProgramApplication[]
diff --git a/apps/web/prisma/schema/program.prisma b/apps/web/prisma/schema/program.prisma
index 3d86b34415..cf91a85609 100644
--- a/apps/web/prisma/schema/program.prisma
+++ b/apps/web/prisma/schema/program.prisma
@@ -115,6 +115,7 @@ model ProgramEnrollment {
leadRewardId String?
saleRewardId String?
referralRewardId String?
+ customRewardId String?
discountId String?
status ProgramEnrollmentStatus @default(pending)
@@ -157,6 +158,7 @@ model ProgramEnrollment {
leadReward Reward? @relation("LeadRewardEnrollments", fields: [leadRewardId], references: [id])
saleReward Reward? @relation("SaleRewardEnrollments", fields: [saleRewardId], references: [id])
referralReward Reward? @relation("ReferralRewardEnrollments", fields: [referralRewardId], references: [id])
+ customReward Reward? @relation("CustomRewardEnrollments", fields: [customRewardId], references: [id])
discount Discount? @relation(fields: [discountId], references: [id])
bountySubmissions BountySubmission[]
discountCodes DiscountCode[]
@@ -194,5 +196,6 @@ model ProgramEnrollment {
@@index(leadRewardId)
@@index(saleRewardId)
@@index(referralRewardId)
+ @@index(customRewardId)
@@index(discountId)
}
diff --git a/apps/web/prisma/schema/reward.prisma b/apps/web/prisma/schema/reward.prisma
index 71de7cf612..3ccc092443 100644
--- a/apps/web/prisma/schema/reward.prisma
+++ b/apps/web/prisma/schema/reward.prisma
@@ -3,6 +3,7 @@ enum EventType {
lead
sale
referral
+ custom
}
enum RewardStructure {
@@ -39,10 +40,12 @@ model Reward {
leadEnrollments ProgramEnrollment[] @relation("LeadRewardEnrollments")
saleEnrollments ProgramEnrollment[] @relation("SaleRewardEnrollments")
referralEnrollments ProgramEnrollment[] @relation("ReferralRewardEnrollments")
+ customEnrollments ProgramEnrollment[] @relation("CustomRewardEnrollments")
clickPartnerGroup PartnerGroup? @relation("ClickReward")
leadPartnerGroup PartnerGroup? @relation("LeadReward")
salePartnerGroup PartnerGroup? @relation("SaleReward")
referralPartnerGroup PartnerGroup? @relation("ReferralReward")
+ customPartnerGroup PartnerGroup? @relation("CustomReward")
commissions Commission[]
@@index([programId, event])
diff --git a/apps/web/scripts/partners/fix-partner-groups.ts b/apps/web/scripts/partners/fix-partner-groups.ts
index 00e59af185..c2f4fd4376 100644
--- a/apps/web/scripts/partners/fix-partner-groups.ts
+++ b/apps/web/scripts/partners/fix-partner-groups.ts
@@ -49,6 +49,7 @@ async function main() {
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
referralRewardId: group.referralRewardId,
+ customRewardId: group.customRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/tests/partner-groups/index.test.ts b/apps/web/tests/partner-groups/index.test.ts
index 994ece0428..452af3ae8a 100644
--- a/apps/web/tests/partner-groups/index.test.ts
+++ b/apps/web/tests/partner-groups/index.test.ts
@@ -29,6 +29,7 @@ const expectedGroup: Partial<GroupProps> = {
leadReward: null,
saleReward: null,
referralReward: null,
+ customReward: null,
discount: null,
maxPartnerLinks: DEFAULT_ADDITIONAL_PARTNER_LINKS,
linkStructure: "short",
diff --git a/apps/web/tests/rewards/custom-reward-cadence.test.ts b/apps/web/tests/rewards/custom-reward-cadence.test.ts
new file mode 100644
index 0000000000..86a84d297e
--- /dev/null
+++ b/apps/web/tests/rewards/custom-reward-cadence.test.ts
@@ -0,0 +1,285 @@
+import {
+ buildCommissionIdempotencyKey,
+ formatCommissionDescription,
+ getUtcPeriodDate,
+ hasRewardMaxDurationElapsed,
+ isCadenceDue,
+ isCustomRewardStartDateInPast,
+ isEventBasedReward,
+} from "@/lib/api/rewards/custom-reward-utils";
+import type { CustomRewardConfig } from "@/lib/types";
+import { customRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { createHash } from "crypto";
+import { describe, expect, test } from "vitest";
+
+const monthlyConfig: CustomRewardConfig = {
+ frequency: "month",
+ interval: 1,
+ anchorDate: "2026-01-31",
+};
+
+const weeklyConfig: CustomRewardConfig = {
+ frequency: "week",
+ interval: 1,
+ anchorDate: "2026-04-06", // Monday
+};
+
+const biweeklyConfig: CustomRewardConfig = {
+ frequency: "week",
+ interval: 2,
+ anchorDate: "2026-04-06",
+};
+
+const dailyConfig: CustomRewardConfig = {
+ frequency: "day",
+ interval: 1,
+ anchorDate: "2026-04-01",
+};
+
+const quarterlyConfig: CustomRewardConfig = {
+ frequency: "month",
+ interval: 3,
+ anchorDate: "2026-01-15",
+};
+
+const yearlyConfig: CustomRewardConfig = {
+ frequency: "year",
+ interval: 1,
+ anchorDate: "2026-01-01",
+};
+
+describe("isCadenceDue", () => {
+ test("daily is due every day on/after anchor", () => {
+ expect(isCadenceDue(dailyConfig, "2026-03-31")).toBe(false);
+ expect(isCadenceDue(dailyConfig, "2026-04-01")).toBe(true);
+ expect(isCadenceDue(dailyConfig, "2026-04-02")).toBe(true);
+ });
+
+ test("weekly is due every 7 days from anchor", () => {
+ expect(isCadenceDue(weeklyConfig, "2026-04-06")).toBe(true);
+ expect(isCadenceDue(weeklyConfig, "2026-04-07")).toBe(false);
+ expect(isCadenceDue(weeklyConfig, "2026-04-13")).toBe(true);
+ });
+
+ test("biweekly is due every 14 days from anchor", () => {
+ expect(isCadenceDue(biweeklyConfig, "2026-04-06")).toBe(true);
+ expect(isCadenceDue(biweeklyConfig, "2026-04-13")).toBe(false);
+ expect(isCadenceDue(biweeklyConfig, "2026-04-20")).toBe(true);
+ expect(isCadenceDue(biweeklyConfig, "2026-04-27")).toBe(false);
+ });
+
+ test("monthly clamps short months to last day", () => {
+ expect(isCadenceDue(monthlyConfig, "2026-01-31")).toBe(true);
+ expect(isCadenceDue(monthlyConfig, "2026-02-28")).toBe(true);
+ expect(isCadenceDue(monthlyConfig, "2026-02-27")).toBe(false);
+ expect(isCadenceDue(monthlyConfig, "2026-03-31")).toBe(true);
+ });
+
+ test("quarterly is due every 3 months on the same day", () => {
+ expect(isCadenceDue(quarterlyConfig, "2026-01-15")).toBe(true);
+ expect(isCadenceDue(quarterlyConfig, "2026-02-15")).toBe(false);
+ expect(isCadenceDue(quarterlyConfig, "2026-04-15")).toBe(true);
+ expect(isCadenceDue(quarterlyConfig, "2026-07-15")).toBe(true);
+ });
+
+ test("yearly is due on the same month and day", () => {
+ expect(isCadenceDue(yearlyConfig, "2026-01-01")).toBe(true);
+ expect(isCadenceDue(yearlyConfig, "2026-01-02")).toBe(false);
+ expect(isCadenceDue(yearlyConfig, "2027-01-01")).toBe(true);
+ });
+
+ test("before anchorDate is never due", () => {
+ expect(isCadenceDue(weeklyConfig, "2026-04-05")).toBe(false);
+ expect(isCadenceDue(monthlyConfig, "2025-12-31")).toBe(false);
+ });
+
+ test("no backfill: past cadence ticks are not due after the period", () => {
+ // Scanner only evaluates today's UTC date; a missed tick stays not due.
+ expect(isCadenceDue(monthlyConfig, "2026-01-30")).toBe(false);
+ expect(isCadenceDue(biweeklyConfig, "2026-04-14")).toBe(false);
+ });
+});
+
+describe("buildCommissionIdempotencyKey", () => {
+ test("is a deterministic sha256 of custom_reward_partner_period", () => {
+ const invoiceId = buildCommissionIdempotencyKey({
+ rewardId: "rw_123",
+ partnerId: "pn_456",
+ periodDate: "2026-04-15",
+ });
+
+ const expected = createHash("sha256")
+ .update("custom_rw_123_pn_456_2026-04-15")
+ .digest("hex");
+
+ expect(invoiceId).toBe(expected);
+ });
+
+ test("does not collide with Stripe invoice ids", () => {
+ const invoiceId = buildCommissionIdempotencyKey({
+ rewardId: "rw_1",
+ partnerId: "pn_1",
+ periodDate: "2026-01-01",
+ });
+
+ expect(invoiceId.startsWith("in_")).toBe(false);
+ });
+});
+
+describe("formatCommissionDescription", () => {
+ test("formats period label from UTC calendar month", () => {
+ // UTC midnight on the 1st is still the prior local month in US timezones.
+ expect(
+ formatCommissionDescription({
+ amountInCents: 1000,
+ frequency: "month",
+ interval: 1,
+ periodDate: "2026-09-01",
+ }),
+ ).toBe("$10 monthly · Sep 2026");
+ });
+
+ test("uses the full UTC date for daily and weekly periods", () => {
+ expect(
+ formatCommissionDescription({
+ amountInCents: 1000,
+ frequency: "day",
+ interval: 1,
+ periodDate: "2026-04-15",
+ }),
+ ).toBe("$10 daily · Apr 15, 2026");
+
+ expect(
+ formatCommissionDescription({
+ amountInCents: 1000,
+ frequency: "week",
+ interval: 1,
+ periodDate: "2026-04-06",
+ }),
+ ).toBe("$10 weekly · Apr 6, 2026");
+ });
+
+ test("uses preset labels for biweekly and quarterly", () => {
+ expect(
+ formatCommissionDescription({
+ amountInCents: 2500,
+ frequency: "week",
+ interval: 2,
+ periodDate: "2026-04-06",
+ }),
+ ).toBe("$25 biweekly · Apr 6, 2026");
+
+ expect(
+ formatCommissionDescription({
+ amountInCents: 5000,
+ frequency: "month",
+ interval: 3,
+ periodDate: "2026-01-15",
+ }),
+ ).toBe("$50 quarterly · Jan 2026");
+ });
+
+ test("falls back to every N units for non-preset intervals", () => {
+ expect(
+ formatCommissionDescription({
+ amountInCents: 1000,
+ frequency: "day",
+ interval: 5,
+ periodDate: "2026-04-15",
+ }),
+ ).toBe("$10 every 5 days · Apr 15, 2026");
+ });
+});
+
+describe("hasRewardMaxDurationElapsed", () => {
+ test("null maxDuration never elapses", () => {
+ expect(
+ hasRewardMaxDurationElapsed({
+ firstCommissionAt: new Date("2026-01-01T00:00:00.000Z"),
+ maxDuration: null,
+ periodDate: "2027-01-01",
+ }),
+ ).toBe(false);
+ });
+
+ test("elapses after N months from first commission", () => {
+ expect(
+ hasRewardMaxDurationElapsed({
+ firstCommissionAt: new Date("2026-01-15T00:00:00.000Z"),
+ maxDuration: 12,
+ periodDate: "2026-12-15",
+ }),
+ ).toBe(false);
+
+ expect(
+ hasRewardMaxDurationElapsed({
+ firstCommissionAt: new Date("2026-01-15T00:00:00.000Z"),
+ maxDuration: 12,
+ periodDate: "2027-01-15",
+ }),
+ ).toBe(true);
+ });
+
+ test("counts UTC calendar months when period is midnight on the 1st", () => {
+ // Jan 31 → Mar 1 is 1 full UTC month. Local US fields can read that as 0.
+ expect(
+ hasRewardMaxDurationElapsed({
+ firstCommissionAt: new Date("2026-01-31T00:00:00.000Z"),
+ maxDuration: 1,
+ periodDate: "2026-03-01",
+ }),
+ ).toBe(true);
+ });
+});
+
+describe("isEventBasedReward", () => {
+ test("excludes custom rewards", () => {
+ expect(isEventBasedReward({ event: "sale" })).toBe(true);
+ expect(isEventBasedReward({ event: "referral" })).toBe(true);
+ expect(isEventBasedReward({ event: "custom" })).toBe(false);
+ });
+});
+
+describe("isCustomRewardStartDateInPast", () => {
+ test("accepts today and future dates", () => {
+ expect(isCustomRewardStartDateInPast(getUtcPeriodDate())).toBe(false);
+ expect(isCustomRewardStartDateInPast("2099-01-01")).toBe(false);
+ });
+
+ test("rejects a past date", () => {
+ expect(isCustomRewardStartDateInPast("2020-01-01")).toBe(true);
+ });
+});
+
+describe("customRewardConfigSchema.anchorDate", () => {
+ const base = { frequency: "month" as const, interval: 1 };
+
+ test("accepts valid YYYY-MM-DD calendar dates", () => {
+ expect(
+ customRewardConfigSchema.parse({ ...base, anchorDate: "2026-01-31" })
+ .anchorDate,
+ ).toBe("2026-01-31");
+ expect(
+ customRewardConfigSchema.parse({ ...base, anchorDate: "2024-02-29" })
+ .anchorDate,
+ ).toBe("2024-02-29");
+ });
+
+ test("rejects impossible month-end dates", () => {
+ expect(
+ customRewardConfigSchema.safeParse({ ...base, anchorDate: "2026-02-31" })
+ .success,
+ ).toBe(false);
+ expect(
+ customRewardConfigSchema.safeParse({ ...base, anchorDate: "2026-04-31" })
+ .success,
+ ).toBe(false);
+ });
+
+ test("rejects leap-day dates in non-leap years", () => {
+ expect(
+ customRewardConfigSchema.safeParse({ ...base, anchorDate: "2025-02-29" })
+ .success,
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/ui/activity-logs/activity-feed.tsx b/apps/web/ui/activity-logs/activity-feed.tsx
index 4c59f099f6..5ad4b49dce 100644
--- a/apps/web/ui/activity-logs/activity-feed.tsx
+++ b/apps/web/ui/activity-logs/activity-feed.tsx
@@ -14,6 +14,7 @@ const ACTIVITY_ITEM_MAP: Record<
leadReward: RewardActivityItem,
saleReward: RewardActivityItem,
referralReward: RewardActivityItem,
+ customReward: RewardActivityItem,
};
interface ActivityFeedProps {
diff --git a/apps/web/ui/partners/custom-reward-description.tsx b/apps/web/ui/partners/custom-reward-description.tsx
new file mode 100644
index 0000000000..adaaf9a600
--- /dev/null
+++ b/apps/web/ui/partners/custom-reward-description.tsx
@@ -0,0 +1,89 @@
+import { formatCadenceLabel } from "@/lib/api/rewards/custom-reward-utils";
+import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { RewardProps } from "@/lib/types";
+import { customRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { cn } from "@dub/utils";
+
+type CustomRewardDescriptionInput = Pick<
+ RewardProps,
+ "type" | "amountInCents" | "amountInPercentage" | "maxDuration" | "config"
+>;
+
+export function getCustomRewardDescriptionParts(
+ reward: CustomRewardDescriptionInput,
+) {
+ const amount = constructRewardAmount(reward);
+ const parsed = customRewardConfigSchema.safeParse(reward.config);
+ const config = parsed.success ? parsed.data : undefined;
+
+ const cadenceLabel = config
+ ? formatCadenceLabel({
+ frequency: config.frequency,
+ interval: config.interval,
+ })
+ : "on a schedule";
+
+ const durationLabel =
+ reward.maxDuration == null
+ ? null
+ : reward.maxDuration % 12 === 0
+ ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
+ : `${reward.maxDuration} month${reward.maxDuration > 1 ? "s" : ""}`;
+
+ return {
+ amount,
+ cadenceLabel,
+ durationLabel,
+ };
+}
+
+export function formatCustomRewardDescription(
+ reward: CustomRewardDescriptionInput,
+ { includeEarnPrefix = true }: { includeEarnPrefix?: boolean } = {},
+) {
+ const { amount, cadenceLabel, durationLabel } =
+ getCustomRewardDescriptionParts(reward);
+
+ return [
+ includeEarnPrefix ? "Earn" : null,
+ amount,
+ cadenceLabel,
+ durationLabel ? `for ${durationLabel}` : null,
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+export function CustomRewardDescription({
+ reward,
+ amountClassName,
+ periodClassName,
+ includeEarnPrefix = true,
+}: {
+ reward: CustomRewardDescriptionInput;
+ amountClassName?: string;
+ periodClassName?: string;
+ includeEarnPrefix?: boolean;
+}) {
+ const { amount, cadenceLabel, durationLabel } =
+ getCustomRewardDescriptionParts(reward);
+
+ return (
+ <>
+ {includeEarnPrefix ? <>Earn </> : null}
+ <strong className={cn("font-semibold lowercase", amountClassName)}>
+ {amount}
+ </strong>{" "}
+ {cadenceLabel}
+ {durationLabel ? (
+ <>
+ {" "}
+ for{" "}
+ <strong className={cn("font-semibold", periodClassName)}>
+ {durationLabel}
+ </strong>
+ </>
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/web/ui/partners/format-reward-description.ts b/apps/web/ui/partners/format-reward-description.ts
index bc043108e9..6ea2b923d0 100644
--- a/apps/web/ui/partners/format-reward-description.ts
+++ b/apps/web/ui/partners/format-reward-description.ts
@@ -8,10 +8,22 @@ import { RewardProps } from "@/lib/types";
import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
import { currencyFormatter } from "@dub/utils";
import { RewardSpendLimitInterval } from "@prisma/client";
+import { formatCustomRewardDescription } from "./custom-reward-description";
import { getSpendLimitDescriptionParts } from "./program-reward-spend-limit";
export function formatRewardDescription(
- reward: RewardProps,
+ reward: Pick<
+ RewardProps,
+ | "description"
+ | "event"
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "maxDuration"
+ | "config"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
+ >,
{ includeEarnPrefix = true }: { includeEarnPrefix?: boolean } = {},
) {
if (reward.description) {
@@ -22,6 +34,10 @@ export function formatRewardDescription(
return formatReferralRewardDescription(reward, { includeEarnPrefix });
}
+ if (reward.event === "custom") {
+ return formatCustomRewardDescription(reward, { includeEarnPrefix });
+ }
+
const rewardAmount = constructRewardAmount(reward);
const parts: string[] = [];
@@ -62,7 +78,10 @@ export function formatRewardDescription(
}
function formatReferralRewardDescription(
- reward: RewardProps,
+ reward: Pick<
+ RewardProps,
+ "type" | "amountInCents" | "amountInPercentage" | "maxDuration" | "config"
+ >,
{ includeEarnPrefix }: { includeEarnPrefix: boolean },
) {
const rewardAmount = constructRewardAmount(reward);
diff --git a/apps/web/ui/partners/lander/lander-rewards.tsx b/apps/web/ui/partners/lander/lander-rewards.tsx
index 50a633d2c2..f2a28fb0c9 100644
--- a/apps/web/ui/partners/lander/lander-rewards.tsx
+++ b/apps/web/ui/partners/lander/lander-rewards.tsx
@@ -1,5 +1,6 @@
"use client";
+import { isEventBasedReward } from "@/lib/api/rewards/custom-reward-utils";
import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import {
DiscountProps,
@@ -27,6 +28,10 @@ export function LanderRewards({
className?: string;
}) {
const sortedFilteredRewards = rewards.filter((reward) => {
+ if (!isEventBasedReward(reward)) {
+ return false;
+ }
+
const rawAmount =
reward.type === "flat" ? reward.amountInCents : reward.amountInPercentage;
diff --git a/apps/web/ui/partners/partner-info-cards.tsx b/apps/web/ui/partners/partner-info-cards.tsx
index a7ac9cab84..f989433766 100644
--- a/apps/web/ui/partners/partner-info-cards.tsx
+++ b/apps/web/ui/partners/partner-info-cards.tsx
@@ -439,6 +439,8 @@ export function PartnerInfoCards({
group.clickReward ||
group.leadReward ||
group.saleReward ||
+ group.referralReward ||
+ group.customReward ||
group.discount ? (
<ProgramRewardList
rewards={[
@@ -446,6 +448,7 @@ export function PartnerInfoCards({
group.leadReward,
group.saleReward,
group.referralReward,
+ group.customReward,
].filter((r): r is RewardProps => r !== null)}
discount={group.discount}
variant="plain"
diff --git a/apps/web/ui/partners/program-reward-description.tsx b/apps/web/ui/partners/program-reward-description.tsx
index 4570e312d7..6e0ff7fd3e 100644
--- a/apps/web/ui/partners/program-reward-description.tsx
+++ b/apps/web/ui/partners/program-reward-description.tsx
@@ -8,6 +8,7 @@ import {
import { DiscountProps, RewardProps } from "@/lib/types";
import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
import { cn, currencyFormatter } from "@dub/utils";
+import { CustomRewardDescription } from "./custom-reward-description";
import { ProgramRewardModifiersTooltip } from "./program-reward-modifiers-tooltip";
import { ProgramRewardSpendLimit } from "./program-reward-spend-limit";
@@ -48,6 +49,12 @@ export function ProgramRewardDescription({
amountClassName={amountClassName}
periodClassName={periodClassName}
/>
+ ) : reward.event === "custom" ? (
+ <CustomRewardDescription
+ reward={reward}
+ amountClassName={amountClassName}
+ periodClassName={periodClassName}
+ />
) : (
<>
Earn{" "}
diff --git a/apps/web/ui/partners/program-rewards-panel.tsx b/apps/web/ui/partners/program-rewards-panel.tsx
index d83e7de319..8615474b80 100644
--- a/apps/web/ui/partners/program-rewards-panel.tsx
+++ b/apps/web/ui/partners/program-rewards-panel.tsx
@@ -6,6 +6,7 @@ import { DiscountProps, RewardProps } from "@/lib/types";
import { Gift, Tooltip } from "@dub/ui";
import { HelpCircle } from "lucide-react";
import { memo } from "react";
+import { CustomRewardDescription } from "./custom-reward-description";
import { formatDiscountDescription } from "./format-discount-description";
import { ProgramRewardModifiersTooltipContent } from "./program-reward-modifiers-tooltip";
import { REWARD_EVENT_ICON } from "./rewards/reward-event-icon";
@@ -37,41 +38,48 @@ export const ProgramRewardsPanel = memo(
const rewardItems = [
...sortedFilteredRewards.map((reward) => ({
icon: REWARD_EVENT_ICON[reward.event],
- label: reward.description || (
- <>
- {constructRewardAmount(reward)}{" "}
- {reward.event === "sale" && reward.maxDuration === 0 ? (
- <>for the first sale</>
- ) : (
- <>per {reward.event}</>
- )}
- {reward.maxDuration === null ? (
- <>
- {" "}
- for the{" "}
- <strong className="font-semibold">customer's lifetime</strong>
- </>
- ) : reward.maxDuration && reward.maxDuration > 1 ? (
- <>
- {" "}
- for{" "}
- <strong className="font-semibold">
- {reward.maxDuration % 12 === 0
- ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
- : `${reward.maxDuration} months`}
- </strong>
- </>
- ) : null}
- {!!reward.modifiers?.length && (
- // whitespace-nowrap keeps the tooltip icon attached to the last
- // word of the description so it never wraps on its own line
- <span className="whitespace-nowrap">
- {" "}
- <CustomRewardModifiersTooltip reward={reward} />
- </span>
- )}
- </>
- ),
+ label:
+ reward.description ||
+ (reward.event === "custom" ? (
+ <CustomRewardDescription
+ reward={reward}
+ includeEarnPrefix={false}
+ />
+ ) : (
+ <>
+ {constructRewardAmount(reward)}{" "}
+ {reward.event === "sale" && reward.maxDuration === 0 ? (
+ <>for the first sale</>
+ ) : (
+ <>per {reward.event}</>
+ )}
+ {reward.maxDuration === null ? (
+ <>
+ {" "}
+ for the{" "}
+ <strong className="font-semibold">customer's lifetime</strong>
+ </>
+ ) : reward.maxDuration && reward.maxDuration > 1 ? (
+ <>
+ {" "}
+ for{" "}
+ <strong className="font-semibold">
+ {reward.maxDuration % 12 === 0
+ ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
+ : `${reward.maxDuration} months`}
+ </strong>
+ </>
+ ) : null}
+ {!!reward.modifiers?.length && (
+ // whitespace-nowrap keeps the tooltip icon attached to the last
+ // word of the description so it never wraps on its own line
+ <span className="whitespace-nowrap">
+ {" "}
+ <CustomRewardModifiersTooltip reward={reward} />
+ </span>
+ )}
+ </>
+ )),
})),
...(discount
? [
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index 9dc0d980f6..9660b71216 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -16,6 +16,7 @@ import { RewardConditionsArray, RewardProps } from "@/lib/types";
import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
import {
createOrUpdateRewardSchema,
+ customRewardConfigSchema,
REWARD_CONDITION_ATTRIBUTES,
REWARD_DESCRIPTION_MAX_LENGTH,
REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH,
@@ -69,6 +70,7 @@ import {
AIRewardPreviewFrame,
useAIRewardBuilder,
} from "./ai-reward-builder";
+import { CustomRewardBuilder } from "./custom-reward-builder";
import { PartnerReferralRewardBuilder } from "./partner-referral-reward-builder";
import { RewardIconSquare } from "./reward-icon-square";
import { RewardPreviewCard } from "./reward-preview-card";
@@ -83,6 +85,7 @@ interface RewardSheetProps {
// Special form schema to allow for empty condition fields when adding a new condition
const formSchema = createOrUpdateRewardSchema.extend({
+ config: z.any().nullish(),
modifiers: z
.array(
rewardConditionsSchema.extend({
@@ -137,7 +140,11 @@ function referralConfigToApi(
export const getRewardPayload = ({ data }: { data: FormData }) => {
let modifiers: RewardConditionsArray | null = null;
const config =
- data.event === "referral" ? referralConfigToApi(data.config) : null;
+ data.event === "referral"
+ ? referralConfigToApi(data.config)
+ : data.event === "custom"
+ ? customRewardConfigSchema.parse(data.config)
+ : null;
if (data.modifiers?.length) {
modifiers = rewardConditionsArraySchema.parse(
@@ -245,13 +252,18 @@ function RewardSheetContent({
event,
type:
defaultValuesSource?.type ??
- (event === "click" || event === "lead" ? "flat" : "percentage"),
+ (event === "click" || event === "lead" || event === "custom"
+ ? "flat"
+ : "percentage"),
maxDuration: defaultValuesSource
? defaultValuesSource.maxDuration === null
? Infinity
: defaultValuesSource.maxDuration
: Infinity,
- config: referralConfigFromApi(defaultValuesSource?.config),
+ config:
+ event === "custom"
+ ? defaultValuesSource?.config
+ : referralConfigFromApi(defaultValuesSource?.config),
amountInCents:
defaultValuesSource?.amountInCents != null
? defaultValuesSource.amountInCents / 100
@@ -341,7 +353,9 @@ function RewardSheetContent({
canUseAdvancedRewardLogic,
} = getPlanCapabilities(plan);
- const aiEvent = selectedEvent === "referral" ? "sale" : selectedEvent;
+ const isAiRewardEvent =
+ selectedEvent !== "referral" && selectedEvent !== "custom";
+ const aiEvent = isAiRewardEvent ? selectedEvent : "sale";
const aiBuilder = useAIRewardBuilder({
event: aiEvent,
getValues: () => getValues() as Record<string, unknown>,
@@ -513,10 +527,10 @@ function RewardSheetContent({
</div>
<div className="flex flex-1 flex-col overflow-y-auto p-6">
- {selectedEvent !== "referral" && (
+ {isAiRewardEvent && (
<AIRewardInput event={selectedEvent} builder={aiBuilder} />
)}
- {selectedEvent !== "referral" ? (
+ {isAiRewardEvent ? (
<AIRewardPreviewFrame builder={aiBuilder}>
<RewardSheetCard
title={
@@ -809,7 +823,11 @@ function RewardSheetContent({
<div className="flex min-w-0 items-center justify-between">
<div className="flex min-w-0 items-center gap-2.5">
<RewardIconSquare icon={MoneyBills2} />
- <PartnerReferralRewardBuilder />
+ {selectedEvent === "custom" ? (
+ <CustomRewardBuilder />
+ ) : (
+ <PartnerReferralRewardBuilder />
+ )}
</div>
<Tooltip
content={"Add a custom reward description"}
@@ -958,7 +976,7 @@ function RewardSheetContent({
isDeleting ||
isCreating ||
isUpdating ||
- (selectedEvent !== "referral" && aiBuilder.isReviewing)
+ (isAiRewardEvent && aiBuilder.isReviewing)
}
disabledTooltip={
showReferralUpsell ? (
@@ -975,7 +993,7 @@ function RewardSheetContent({
href={`/${workspaceSlug}/upgrade?plan=advanced&showAdvancedUpsellModal=true`}
target="_blank"
/>
- ) : selectedEvent !== "referral" && aiBuilder.isReviewing ? (
+ ) : isAiRewardEvent && aiBuilder.isReviewing ? (
"Accept or discard the generated reward before saving."
) : undefined
}
diff --git a/apps/web/ui/partners/rewards/ai-reward-builder.tsx b/apps/web/ui/partners/rewards/ai-reward-builder.tsx
index 58b0f5ff4c..e72979b34b 100644
--- a/apps/web/ui/partners/rewards/ai-reward-builder.tsx
+++ b/apps/web/ui/partners/rewards/ai-reward-builder.tsx
@@ -54,7 +54,7 @@ function buildRewardFormValuesFromDraft({
draft: Omit<Partial<AIRewardDraft>, "modifiers"> & {
modifiers?: Array<DraftModifier | null | undefined>;
};
- event: Exclude<EventType, "referral">;
+ event: Exclude<EventType, "referral" | "custom">;
current: Record<string, unknown>;
finalize?: boolean;
}): Record<string, unknown> | null {
@@ -162,7 +162,7 @@ export function useAIRewardBuilder({
getValues,
reset,
}: {
- event: Exclude<EventType, "referral">;
+ event: Exclude<EventType, "referral" | "custom">;
getValues: () => Record<string, unknown>;
reset: (
values: Record<string, unknown>,
@@ -413,7 +413,7 @@ export function AIRewardInput({
event,
builder,
}: {
- event: Exclude<EventType, "referral">;
+ event: Exclude<EventType, "referral" | "custom">;
builder: AIRewardBuilderState;
}) {
const shouldReduceMotion = useReducedMotion();
@@ -956,7 +956,11 @@ function SkeletonPill({ className }: { className?: string }) {
);
}
-function ReviewSkeletons({ event }: { event: Exclude<EventType, "referral"> }) {
+function ReviewSkeletons({
+ event,
+}: {
+ event: Exclude<EventType, "referral" | "custom">;
+}) {
return (
<div className="border-border-subtle rounded-xl border bg-white text-sm shadow-sm">
<div className="flex items-start gap-2.5 p-2.5">
diff --git a/apps/web/ui/partners/rewards/custom-reward-builder.tsx b/apps/web/ui/partners/rewards/custom-reward-builder.tsx
new file mode 100644
index 0000000000..3b0960d81f
--- /dev/null
+++ b/apps/web/ui/partners/rewards/custom-reward-builder.tsx
@@ -0,0 +1,233 @@
+"use client";
+
+import { getUtcPeriodDate } from "@/lib/api/rewards/custom-reward-utils";
+import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
+import type { CustomRewardConfig } from "@/lib/types";
+import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
+import {
+ CUSTOM_REWARD_CADENCE_PRESETS,
+ customRewardConfigSchema,
+} from "@/lib/zod/schemas/rewards";
+import { DatePicker } from "@dub/ui";
+import { cn, pluralize } from "@dub/utils";
+import { useContext, useEffect, useMemo } from "react";
+import { DurationPopoverContent } from "../../shared/duration-popover-content";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverContext,
+ InlineBadgePopoverMenu,
+} from "../../shared/inline-badge-popover";
+import { useAddEditRewardForm } from "./add-edit-reward-sheet";
+
+function parseCustomConfig(config: unknown): CustomRewardConfig | null {
+ const parsed = customRewardConfigSchema.safeParse(config);
+ return parsed.success ? parsed.data : null;
+}
+
+function getCadencePresetValue(config: CustomRewardConfig | null) {
+ if (!config) {
+ return "monthly";
+ }
+
+ const preset = CUSTOM_REWARD_CADENCE_PRESETS.find(
+ (p) => p.frequency === config.frequency && p.interval === config.interval,
+ );
+
+ return preset?.value ?? "monthly";
+}
+
+export function CustomRewardBuilder() {
+ const { watch, setValue } = useAddEditRewardForm();
+
+ const [amountInCents, config, maxDuration] = watch([
+ "amountInCents",
+ "config",
+ "maxDuration",
+ ]);
+
+ const customConfig = useMemo(() => parseCustomConfig(config), [config]);
+ const cadenceValue = getCadencePresetValue(customConfig);
+
+ useEffect(() => {
+ setValue("type", "flat", { shouldDirty: false });
+
+ if (customConfig) {
+ return;
+ }
+
+ const monthly = CUSTOM_REWARD_CADENCE_PRESETS.find(
+ (p) => p.value === "monthly",
+ )!;
+
+ setValue(
+ "config",
+ {
+ frequency: monthly.frequency,
+ interval: monthly.interval,
+ anchorDate: getUtcPeriodDate(),
+ },
+ { shouldDirty: false },
+ );
+ }, [customConfig, setValue]);
+
+ const amountLabel =
+ amountInCents != null && !Number.isNaN(amountInCents)
+ ? constructRewardAmount({
+ type: "flat",
+ amountInCents: amountInCents * 100,
+ amountInPercentage: null,
+ maxDuration: null,
+ })
+ : "amount";
+
+ const cadenceLabel =
+ CUSTOM_REWARD_CADENCE_PRESETS.find(
+ (p) => p.value === cadenceValue,
+ )?.label.toLowerCase() ?? "monthly";
+
+ const durationLabel =
+ maxDuration === Infinity || maxDuration == null
+ ? "indefinitely"
+ : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`;
+
+ const minAnchorDate = useMemo(
+ () => new Date(`${getUtcPeriodDate()}T12:00:00`),
+ [],
+ );
+
+ const anchorDate = customConfig?.anchorDate
+ ? new Date(`${customConfig.anchorDate}T12:00:00`)
+ : undefined;
+
+ return (
+ <span className="leading-relaxed">
+ Pay{" "}
+ <InlineBadgePopover text={amountLabel} invalid={amountInCents == null}>
+ <AmountInput />
+ </InlineBadgePopover>{" "}
+ <InlineBadgePopover text={cadenceLabel}>
+ <InlineBadgePopoverMenu
+ selectedValue={cadenceValue}
+ onSelect={(value) => {
+ const preset = CUSTOM_REWARD_CADENCE_PRESETS.find(
+ (p) => p.value === value,
+ );
+ if (!preset) {
+ return;
+ }
+
+ setValue(
+ "config",
+ {
+ frequency: preset.frequency,
+ interval: preset.interval,
+ anchorDate: customConfig?.anchorDate ?? getUtcPeriodDate(),
+ },
+ { shouldDirty: true },
+ );
+ }}
+ items={CUSTOM_REWARD_CADENCE_PRESETS.map((preset) => ({
+ text: preset.label,
+ value: preset.value,
+ }))}
+ />
+ </InlineBadgePopover>
+ , starting{" "}
+ <DatePicker
+ value={anchorDate}
+ onChange={(date) => {
+ if (!date) {
+ return;
+ }
+
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ const nextAnchorDate = `${year}-${month}-${day}`;
+
+ if (nextAnchorDate < getUtcPeriodDate()) {
+ return;
+ }
+
+ setValue(
+ "config",
+ {
+ frequency: customConfig?.frequency ?? "month",
+ interval: customConfig?.interval ?? 1,
+ anchorDate: nextAnchorDate,
+ },
+ { shouldDirty: true },
+ );
+ }}
+ placeholder="Select date"
+ invalid={!customConfig?.anchorDate}
+ fromDate={minAnchorDate}
+ disabledDays={{ before: minAnchorDate }}
+ trigger={({ displayValue, placeholder, invalid }) => (
+ <button
+ type="button"
+ className={cn(
+ "inline-block rounded px-1.5 text-left text-sm font-semibold transition-colors",
+ invalid
+ ? "bg-orange-50 text-orange-500 hover:bg-orange-100 data-[state=open]:bg-orange-100"
+ : "bg-blue-50 text-blue-700 hover:bg-blue-100 data-[state=open]:bg-blue-100",
+ )}
+ >
+ {displayValue ?? placeholder}
+ </button>
+ )}
+ />{" "}
+ <InlineBadgePopover text={durationLabel}>
+ <DurationPopoverContent
+ value={
+ maxDuration === Infinity || maxDuration == null
+ ? Infinity
+ : Number(maxDuration)
+ }
+ onChange={(value) =>
+ setValue("maxDuration", value === Infinity ? null : value, {
+ shouldDirty: true,
+ })
+ }
+ presetDurations={RECURRING_MAX_DURATIONS.filter(
+ (v) => v !== 0 && v !== 1,
+ )}
+ minValue={1}
+ hideLifetime
+ />
+ </InlineBadgePopover>
+ </span>
+ );
+}
+
+function AmountInput() {
+ const { register } = useAddEditRewardForm();
+ const { setIsOpen } = useContext(InlineBadgePopoverContext);
+
+ return (
+ <div className="relative rounded-md shadow-sm">
+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-500">
+ $
+ </span>
+ <input
+ className="block w-full rounded-md border-neutral-300 pl-4 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ placeholder="0.00"
+ {...register("amountInCents", {
+ required: true,
+ setValueAs: (value: string) => (value === "" ? undefined : +value),
+ min: 0,
+ onChange: handleMoneyInputChange,
+ })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setIsOpen(false);
+ return;
+ }
+ handleMoneyKeyDown(e);
+ }}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/rewards/reward-event-descriptions.tsx b/apps/web/ui/partners/rewards/reward-event-descriptions.tsx
index 3b963fc0ed..278d7723a6 100644
--- a/apps/web/ui/partners/rewards/reward-event-descriptions.tsx
+++ b/apps/web/ui/partners/rewards/reward-event-descriptions.tsx
@@ -1,4 +1,11 @@
-import { CursorRays, Icon, InvoiceDollar, Nodes4, UserPlus } from "@dub/ui";
+import {
+ CalendarDays,
+ CursorRays,
+ Icon,
+ InvoiceDollar,
+ Nodes4,
+ UserPlus,
+} from "@dub/ui";
import { EventType } from "@prisma/client";
export const REWARD_EVENT_DESCRIPTIONS: Record<
@@ -42,4 +49,12 @@ export const REWARD_EVENT_DESCRIPTIONS: Record<
bestFor: "driving partner growth to your program",
learnMoreHref: "https://dub.co/help/article/partner-referrals",
},
+ custom: {
+ icon: CalendarDays,
+ title: "Custom reward",
+ description: "Pay a fixed amount on a regular cadence",
+ bestFor: "retainers and scheduled partner payments",
+ learnMoreHref:
+ "https://dub.co/help/article/partner-rewards#configuring-reward-types",
+ },
};
diff --git a/apps/web/ui/partners/rewards/reward-event-icon.tsx b/apps/web/ui/partners/rewards/reward-event-icon.tsx
index a1d7683bc8..66d0d12fa1 100644
--- a/apps/web/ui/partners/rewards/reward-event-icon.tsx
+++ b/apps/web/ui/partners/rewards/reward-event-icon.tsx
@@ -1,8 +1,15 @@
-import { CursorRays, InvoiceDollar, Nodes4, UserPlus } from "@dub/ui/icons";
+import {
+ CalendarDays,
+ CursorRays,
+ InvoiceDollar,
+ Nodes4,
+ UserPlus,
+} from "@dub/ui/icons";
export const REWARD_EVENT_ICON = {
click: CursorRays,
lead: UserPlus,
sale: InvoiceDollar,
referral: Nodes4,
+ custom: CalendarDays,
};
diff --git a/apps/web/ui/partners/rewards/reward-presets.ts b/apps/web/ui/partners/rewards/reward-presets.ts
index 70e9fa8779..ad5b17d1a2 100644
--- a/apps/web/ui/partners/rewards/reward-presets.ts
+++ b/apps/web/ui/partners/rewards/reward-presets.ts
@@ -8,7 +8,7 @@ export type RewardPreset = {
};
export const REWARD_PRESETS: Partial<
- Record<Exclude<EventType, "referral">, RewardPreset[]>
+ Record<Exclude<EventType, "referral" | "custom">, RewardPreset[]>
> = {
sale: [
{
diff --git a/apps/web/ui/partners/rewards/reward-preview-card.tsx b/apps/web/ui/partners/rewards/reward-preview-card.tsx
index 6cfa919a6e..06b97a3d33 100644
--- a/apps/web/ui/partners/rewards/reward-preview-card.tsx
+++ b/apps/web/ui/partners/rewards/reward-preview-card.tsx
@@ -1,3 +1,4 @@
+import { isEventBasedReward } from "@/lib/api/rewards/custom-reward-utils";
import { EnrolledPartnerProps } from "@/lib/types";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
import { Button, Table, useTable } from "@dub/ui";
@@ -52,18 +53,20 @@ export function RewardPreviewCard() {
<span className="text-content-emphasis flex items-center gap-2.5 text-sm font-semibold">
Reward preview
</span>
- <div className="flex items-center gap-2">
- <span className="text-xs font-semibold text-neutral-500">
- {hasConditions ? "Base reward quality" : "Reward quality"}
- </span>
- <RewardQualityIndicator
- event={reward.event}
- quality={quality}
- tooltipFooter={
- hasConditions ? "Based on default reward only" : undefined
- }
- />
- </div>
+ {isEventBasedReward(reward) && (
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-semibold text-neutral-500">
+ {hasConditions ? "Base reward quality" : "Reward quality"}
+ </span>
+ <RewardQualityIndicator
+ event={reward.event}
+ quality={quality}
+ tooltipFooter={
+ hasConditions ? "Based on default reward only" : undefined
+ }
+ />
+ </div>
+ )}
</div>
<div className="border-border-subtle bg-bg-default -mx-px rounded-xl border-x border-t p-4">
diff --git a/apps/web/ui/shared/duration-popover-content.tsx b/apps/web/ui/shared/duration-popover-content.tsx
index 8413b90eea..67567e47ca 100644
--- a/apps/web/ui/shared/duration-popover-content.tsx
+++ b/apps/web/ui/shared/duration-popover-content.tsx
@@ -14,6 +14,7 @@ type DurationPopoverContentProps = {
presetDurations: number[];
partnerReferralReward?: boolean;
presetsOnly?: boolean;
+ hideLifetime?: boolean;
unit?: "days" | "months";
minValue?: number;
};
@@ -24,6 +25,7 @@ export function DurationPopoverContent({
presetDurations,
partnerReferralReward,
presetsOnly = false,
+ hideLifetime = false,
unit = "months",
minValue = 0,
}: DurationPopoverContentProps) {
@@ -142,7 +144,11 @@ export function DurationPopoverContent({
}
if (e.key === "Enter") {
e.preventDefault();
- if (!presetsOnly && customDurationInput === "0") {
+ if (
+ !presetsOnly &&
+ minValue === 0 &&
+ customDurationInput === "0"
+ ) {
onChange(0);
setCustomDurationInput("");
setShowCustomInput(false);
@@ -187,14 +193,16 @@ export function DurationPopoverContent({
setCustomDurationInput("");
}}
items={[
- ...(!presetsOnly && !partnerReferralReward
+ ...(!presetsOnly && !partnerReferralReward && minValue === 0
? [{ text: "one time", value: "0" }]
: []),
...presetItems,
...(!presetsOnly
? [
{
- text: `for the ${partnerReferralReward ? "referred partner's" : "customer's"} lifetime`,
+ text: hideLifetime
+ ? "Indefinitely"
+ : `for the ${partnerReferralReward ? "referred partner's" : "customer's"} lifetime`,
value: "Infinity",
},
]
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index e59dfb5eda..e6296f6f7b 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -95,6 +95,10 @@
{
"path": "/api/cron/campaigns/queue-scheduled",
"schedule": "* * * * *"
+ },
+ {
+ "path": "/api/cron/rewards/queue-custom-commissions",
+ "schedule": "0 0 * * *"
}
],
"functions": {
diff --git a/packages/ui/src/date-picker/date-picker.tsx b/packages/ui/src/date-picker/date-picker.tsx
index 78135495a5..2d96a35161 100644
--- a/packages/ui/src/date-picker/date-picker.tsx
+++ b/packages/ui/src/date-picker/date-picker.tsx
@@ -36,6 +36,7 @@ export function DatePicker({
trigger: customTrigger,
renderContent,
disabled,
+ disabledDays,
locale = enUS,
placeholder = "Select date",
hasError,
@@ -69,6 +70,7 @@ export function DatePicker({
selected={selected}
onSelect={onSelect}
locale={locale}
+ disabled={disabledDays}
{...props}
defaultMonth={selected}
/>