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.

Reward spend limit (#4040)

Kiran K41950ed6e835
diff --git a/apps/web/app/(ee)/api/cron/aggregate-clicks/process/route.ts b/apps/web/app/(ee)/api/cron/aggregate-clicks/process/route.ts
new file mode 100644
index 0000000000..10509b2d71
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/process/route.ts
@@ -0,0 +1,356 @@
+import { createId } from "@/lib/api/create-id";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
+import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
+import { getRewardSpendLimitWindow } from "@/lib/api/rewards/reward-spend-limit-window";
+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
+import { withCron } from "@/lib/cron/with-cron";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
+import { prisma } from "@/lib/prisma";
+import { getTopLinksByCountries } from "@/lib/tinybird/get-top-links-by-countries";
+import { COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { buildCommissionDescription } from "@/ui/partners/program-reward-spend-limit";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ currencyFormatter,
+ getPrettyUrl,
+} from "@dub/utils";
+import { CommissionType, EventType, Prisma, Reward } from "@prisma/client";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
+import { resolveClickReward } from "../resolve-click-reward-amount";
+
+export const dynamic = "force-dynamic";
+
+const inputSchema = z.object({
+ clickRewardId: z.string(),
+ startDate: z.coerce.date(),
+ endDate: z.coerce.date(),
+ startingAfter: z.string().optional(),
+});
+
+const BATCH_SIZE = 200;
+
+type LinkEarnings = {
+ clicks: number;
+ earnings: number;
+ partnerId: string;
+};
+
+// POST /api/cron/aggregate-clicks/process
+// Process a batch of links for a given click reward
+export const POST = withCron(async ({ rawBody }) => {
+ const { clickRewardId, startDate, endDate, startingAfter } =
+ inputSchema.parse(JSON.parse(rawBody));
+
+ const clickReward = await prisma.reward.findUnique({
+ where: {
+ id: clickRewardId,
+ },
+ });
+
+ if (!clickReward) {
+ return logAndRespond(`Reward not found for ${clickRewardId}. Skipping...`);
+ }
+
+ // When soft deleted
+ if (!clickReward.programId) {
+ return logAndRespond(
+ `Reward ${clickRewardId} is not associated with a program. Skipping...`,
+ );
+ }
+
+ if (clickReward.event !== EventType.click) {
+ return logAndRespond(
+ `Reward ${clickRewardId} is not a click reward. Skipping...`,
+ );
+ }
+
+ const links = await prisma.link.findMany({
+ where: {
+ programEnrollment: {
+ status: {
+ in: COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES,
+ },
+ clickRewardId,
+ },
+ clicks: {
+ gt: 0,
+ },
+ lastClicked: {
+ gte: startDate, // links that were clicked on after the start date
+ },
+ },
+ select: {
+ id: true,
+ shortLink: true,
+ programId: true,
+ partnerId: true,
+ },
+ ...(startingAfter && {
+ skip: 1,
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ orderBy: {
+ id: "asc",
+ },
+ take: BATCH_SIZE,
+ });
+
+ if (links.length === 0) {
+ return logAndRespond(
+ `No more links found for ${clickRewardId}. Skipping...`,
+ );
+ }
+
+ const clicksByCountries = await getTopLinksByCountries({
+ linkIds: links.map(({ id }) => id),
+ start: startDate,
+ end: endDate,
+ });
+
+ // Group clicks by link
+ const clicksByLinkId = new Map<string, typeof clicksByCountries>();
+
+ for (const click of clicksByCountries) {
+ const existing = clicksByLinkId.get(click.link_id) || [];
+ existing.push(click);
+ clicksByLinkId.set(click.link_id, existing);
+ }
+
+ // Calculate earnings per link considering geo CPC
+ const linkEarningsMap = new Map<string, LinkEarnings>();
+
+ for (const { id: linkId, shortLink, programId, partnerId } of links) {
+ if (!programId || !partnerId) {
+ console.log(`No click reward for link ${linkId}.`);
+ continue;
+ }
+
+ const linkClicksByCountry = clicksByLinkId.get(linkId) || [];
+
+ // Calculate earnings per country for each link
+ for (const { country, clicks } of linkClicksByCountry) {
+ const finalReward = resolveClickReward({
+ reward: clickReward,
+ country,
+ });
+
+ const existing = linkEarningsMap.get(linkId) || {
+ clicks: 0,
+ earnings: 0,
+ };
+
+ const amountInCents = getRewardAmount(serializeReward(finalReward));
+
+ linkEarningsMap.set(linkId, {
+ clicks: existing.clicks + clicks,
+ earnings: existing.earnings + amountInCents * clicks,
+ partnerId,
+ });
+
+ if (clickReward.modifiers) {
+ console.log(
+ `Earnings for link ${getPrettyUrl(shortLink)} for ${country}: ${currencyFormatter(amountInCents)} * ${clicks} = ${currencyFormatter(
+ amountInCents * clicks,
+ )}`,
+ );
+ }
+ }
+ }
+
+ // Apply reward spend limit
+ const uniquePartners = new Set(
+ Array.from(linkEarningsMap.values(), ({ partnerId }) => partnerId),
+ );
+
+ const historicalEarningsByPartner = await getHistoricalEarnings({
+ clickReward,
+ partnerIds: Array.from(uniquePartners),
+ aggregationStartDate: startDate,
+ });
+
+ const aggregationDate = startDate.toISOString().split("T")[0];
+ const usedSpendLimitByPartner = new Map<string, number>();
+ let commissionsToCreate: Prisma.CommissionCreateManyInput[] = [];
+
+ // Create commissions for each link
+ commissionsToCreate = links
+ .map(({ id: linkId, programId, partnerId }) => {
+ if (!programId || !partnerId) {
+ return null;
+ }
+
+ const linkEarnings = linkEarningsMap.get(linkId);
+
+ if (!linkEarnings) {
+ return null;
+ }
+
+ let { clicks, earnings } = linkEarnings;
+
+ if (clicks === 0 || earnings === 0) {
+ return null;
+ }
+
+ let description: string | null = null;
+
+ // Cap earnings to spend limit
+ if (clickReward.spendLimitAmount && clickReward.spendLimitInterval) {
+ const usedThisBatch = usedSpendLimitByPartner.get(partnerId) ?? 0;
+ const historicalEarnings =
+ historicalEarningsByPartner.get(partnerId) ?? 0;
+
+ const remainingSpendLimit =
+ clickReward.spendLimitAmount - historicalEarnings - usedThisBatch;
+
+ const cappedEarnings = Math.max(
+ 0,
+ Math.min(earnings, remainingSpendLimit),
+ );
+
+ if (cappedEarnings === 0) {
+ console.log(`Reached spend limit for partner ${partnerId}.`);
+ return null;
+ }
+
+ usedSpendLimitByPartner.set(partnerId, usedThisBatch + cappedEarnings);
+
+ description = buildCommissionDescription({
+ earnings,
+ cappedEarnings,
+ reward: serializeReward(clickReward),
+ });
+
+ earnings = cappedEarnings;
+ }
+
+ return {
+ id: createId({ prefix: "cm_" }),
+ programId,
+ partnerId,
+ rewardId: clickReward.id,
+ linkId,
+ quantity: clicks,
+ type: CommissionType.click,
+ amount: 0,
+ earnings,
+ description,
+ createdAt: endDate,
+ invoiceId: `${linkId}-${aggregationDate}`, // used as a idempotency key
+ };
+ })
+ .filter((c): c is NonNullable<typeof c> => c !== null);
+
+ const { count } = await prisma.commission.createMany({
+ data: commissionsToCreate,
+ skipDuplicates: true,
+ });
+
+ console.log(
+ `Created ${count} commissions for click reward ${clickRewardId}.`,
+ );
+
+ if (count > 0) {
+ console.table(commissionsToCreate);
+
+ // Sync total commissions for each partner that we created commissions for
+ for (const { partnerId, programId } of commissionsToCreate) {
+ await syncTotalCommissions({
+ partnerId,
+ programId,
+ });
+ }
+
+ console.log(
+ `Synced total commissions count for ${commissionsToCreate.length} partners`,
+ );
+ }
+
+ // Schedule next batch if we have more links to process
+ if (links.length === BATCH_SIZE) {
+ const nextStartingAfter = links[links.length - 1].id;
+
+ await enqueueBatchJobs([
+ {
+ queueName: "aggregate-clicks",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/aggregate-clicks/process`,
+ body: {
+ clickRewardId: clickReward.id,
+ startDate,
+ endDate,
+ startingAfter: nextStartingAfter,
+ },
+ },
+ ]);
+
+ return logAndRespond(
+ `Enqueued next batch for aggregate clicks cron (startingAfter: ${nextStartingAfter}).`,
+ );
+ }
+
+ return logAndRespond("Aggregate clicks job processed successfully.");
+});
+
+async function getHistoricalEarnings({
+ clickReward,
+ partnerIds,
+ aggregationStartDate,
+}: {
+ clickReward: Pick<
+ Reward,
+ "spendLimitAmount" | "spendLimitInterval" | "programId"
+ >;
+ partnerIds: string[];
+ aggregationStartDate: Date;
+}) {
+ if (
+ !clickReward.spendLimitAmount ||
+ !clickReward.spendLimitInterval ||
+ !clickReward.programId
+ ) {
+ return new Map<string, number>();
+ }
+
+ const { startDate, endDate } = getRewardSpendLimitWindow({
+ spendLimitInterval: clickReward.spendLimitInterval,
+ referenceDate: aggregationStartDate,
+ });
+
+ const commissions = await prisma.commission.groupBy({
+ by: ["programId", "partnerId"],
+ where: {
+ programId: clickReward.programId,
+ partnerId: {
+ in: partnerIds,
+ },
+ type: CommissionType.click,
+ status: {
+ in: ["pending", "processed", "paid"],
+ },
+ ...(startDate && endDate
+ ? {
+ createdAt: {
+ gte: startDate,
+ lte: endDate,
+ },
+ }
+ : {}),
+ },
+ _sum: {
+ earnings: true,
+ },
+ });
+
+ const historicalEarningsByPartner = new Map<string, number>();
+
+ for (const commission of commissions) {
+ historicalEarningsByPartner.set(
+ commission.partnerId,
+ commission._sum.earnings ?? 0,
+ );
+ }
+
+ return historicalEarningsByPartner;
+}
diff --git a/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts b/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts
index 8ac10adf56..11576081c1 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount.ts
@@ -1,17 +1,15 @@
-import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { evaluateRewardConditions } from "@/lib/partners/evaluate-reward-conditions";
-import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { rewardConditionsArraySchema } from "@/lib/zod/schemas/rewards";
import { Reward } from "@prisma/client";
// Resolve the click reward amount for a given reward and country
-export function resolveClickRewardAmount({
+export function resolveClickReward({
reward,
country,
}: {
reward: Reward;
country: string;
-}): number {
+}) {
let partnerReward = reward;
if (reward.modifiers) {
@@ -40,5 +38,5 @@ export function resolveClickRewardAmount({
}
}
- return getRewardAmount(serializeReward(partnerReward));
+ return partnerReward;
}
diff --git a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
index 1c862a9afd..a7ea03bc66 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
@@ -1,251 +1,63 @@
-import { createId } from "@/lib/api/create-id";
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
-import { qstash } from "@/lib/cron";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
+import { withCron } from "@/lib/cron/with-cron";
import { prisma } from "@/lib/prisma";
-import { getTopLinksByCountries } from "@/lib/tinybird/get-top-links-by-countries";
-import { COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
-import {
- APP_DOMAIN_WITH_NGROK,
- currencyFormatter,
- getPrettyUrl,
- nFormatter,
-} from "@dub/utils";
-import { CommissionType, Prisma } from "@prisma/client";
-import * as z from "zod/v4";
+import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";
+import { EventType } from "@prisma/client";
import { logAndRespond } from "../utils";
-import { resolveClickRewardAmount } from "./resolve-click-reward-amount";
export const dynamic = "force-dynamic";
-const BATCH_SIZE = 200;
-
-const schema = z.object({
- startingAfter: z.string().optional(),
- batchNumber: z.number().optional().default(1),
-});
-
// This route is used aggregate clicks events on daily basis for Program links and add to the Commission table
// Runs every day at 00:00 (0 0 * * *)
-// GET /api/cron/aggregate-clicks
-async function handler(req: Request) {
- try {
- let { startingAfter, batchNumber } = schema.parse({
- startingAfter: undefined,
- batchNumber: 1,
- });
-
- if (req.method === "GET") {
- await verifyVercelSignature(req);
- } else if (req.method === "POST") {
- const rawBody = await req.text();
- await verifyQstashSignature({
- req,
- rawBody,
- });
-
- ({ startingAfter, batchNumber } = schema.parse(JSON.parse(rawBody)));
- }
-
- const now = new Date();
-
- // set 'start' to the beginning of the previous day (00:00:00)
- const start = new Date(now);
- start.setDate(start.getDate() - 1);
- start.setHours(0, 0, 0, 0);
-
- // set 'end' to the end of the previous day (23:59:59)
- const end = new Date(now);
- end.setDate(end.getDate() - 1);
- end.setHours(23, 59, 59, 999);
-
- const linksWithClickRewards = await prisma.link.findMany({
- where: {
- programEnrollment: {
- status: {
- in: COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES,
- },
- clickRewardId: {
- not: null,
- },
- },
- clicks: {
- gt: 0,
- },
- lastClicked: {
- gte: start, // links that were clicked on after the start date
- },
+// POST /api/cron/aggregate-clicks
+export const POST = withCron(async () => {
+ const clickRewards = await prisma.reward.findMany({
+ where: {
+ event: EventType.click,
+ clickEnrollments: {
+ some: {},
},
- select: {
- id: true,
- shortLink: true,
- programId: true,
- partnerId: true,
- programEnrollment: {
- select: {
- clickReward: true,
- },
- },
- },
- take: BATCH_SIZE,
- skip: startingAfter ? 1 : 0,
- ...(startingAfter && {
- cursor: {
- id: startingAfter,
- },
- }),
- orderBy: {
- id: "asc",
+ programId: {
+ not: null,
},
- });
-
- const endMessage = `Finished aggregating clicks for ${batchNumber} batches (total ${nFormatter(batchNumber * (BATCH_SIZE - 1) + linksWithClickRewards.length, { full: true })} links)`;
-
- if (linksWithClickRewards.length === 0) {
- return logAndRespond(endMessage);
- }
-
- const clicksByCountries = await getTopLinksByCountries({
- linkIds: linksWithClickRewards.map(({ id }) => id),
- start,
- end,
- });
-
- // This should never happen, but just in case
- if (clicksByCountries.length === 0) {
- return logAndRespond(endMessage);
- }
-
- // Group clicks by link_id for easier iteration
- const clicksByLinkId = new Map<string, typeof clicksByCountries>();
- for (const click of clicksByCountries) {
- const existing = clicksByLinkId.get(click.link_id) || [];
- existing.push(click);
- clicksByLinkId.set(click.link_id, existing);
- }
-
- const linkEarningsMap = new Map<
- string,
- { linkClicks: number; earnings: number }
- >();
-
- // Calculate earnings per link considering geo CPC
- for (const {
- id: linkId,
- shortLink,
- programEnrollment,
- } of linksWithClickRewards) {
- if (!programEnrollment?.clickReward) {
- console.log(`No click reward for link ${linkId}.`);
- continue;
- }
-
- const linkClicksByCountry = clicksByLinkId.get(linkId) || [];
-
- // Calculate earnings per country for each link
- for (const { country, clicks } of linkClicksByCountry) {
- const rewardAmount = resolveClickRewardAmount({
- reward: programEnrollment.clickReward,
- country,
- });
-
- const existing = linkEarningsMap.get(linkId) || {
- linkClicks: 0,
- earnings: 0,
- };
-
- linkEarningsMap.set(linkId, {
- linkClicks: existing.linkClicks + clicks,
- earnings: existing.earnings + rewardAmount * clicks,
- });
-
- // only console.log if there are modifiers
- if (programEnrollment.clickReward.modifiers) {
- console.log(
- `Earnings for link ${getPrettyUrl(shortLink)} for ${country}: ${currencyFormatter(rewardAmount)} * ${clicks} = ${currencyFormatter(
- rewardAmount * clicks,
- )}`,
- );
- }
- }
- }
-
- // Create commissions for each link
- const commissionsToCreate = linksWithClickRewards
- .map(({ id, programId, partnerId, programEnrollment }) => {
- if (!programId || !partnerId || !programEnrollment?.clickReward) {
- return null;
- }
-
- const { linkClicks, earnings } = linkEarningsMap.get(id) || {
- linkClicks: 0,
- earnings: 0,
- };
-
- if (linkClicks === 0 || earnings === 0) {
- return null;
- }
-
- return {
- id: createId({ prefix: "cm_" }),
- programId,
- partnerId,
- rewardId: programEnrollment.clickReward.id,
- linkId: id,
- quantity: linkClicks,
- type: CommissionType.click,
- amount: 0,
- earnings,
- };
- })
- .filter(
- (c): c is NonNullable<typeof c> => c !== null,
- ) satisfies Prisma.CommissionCreateManyInput[];
-
- console.table(commissionsToCreate);
-
- // Create commissions
- await prisma.commission.createMany({
- data: commissionsToCreate,
- });
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (clickRewards.length === 0) {
+ return logAndRespond("No click rewards found. Skipping...");
+ }
- // Sync total commissions for each partner that we created commissions for
- for (const { partnerId, programId } of commissionsToCreate) {
- await syncTotalCommissions({
- partnerId,
- programId,
- });
- }
+ const now = new Date();
- console.log(
- `Synced total commissions count for ${commissionsToCreate.length} partners`,
- );
+ // set 'start' to the beginning of the previous day (00:00:00)
+ const startDate = new Date(now);
+ startDate.setDate(startDate.getDate() - 1);
+ startDate.setHours(0, 0, 0, 0);
- // Schedule next batch if we have more links to process
- if (linksWithClickRewards.length === BATCH_SIZE) {
- const nextStartingAfter =
- linksWithClickRewards[linksWithClickRewards.length - 1].id;
+ // set 'end' to the end of the previous day (23:59:59)
+ const endDate = new Date(now);
+ endDate.setDate(endDate.getDate() - 1);
+ endDate.setHours(23, 59, 59, 999);
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/aggregate-clicks`,
- method: "POST",
+ for (const clickRewardsChunk of chunk(clickRewards, 50)) {
+ await enqueueBatchJobs(
+ clickRewardsChunk.map((clickReward) => ({
+ queueName: "aggregate-clicks",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/aggregate-clicks/process`,
+ deduplicationId: `aggregate-clicks-${clickReward.id}`,
body: {
- startingAfter: nextStartingAfter,
- batchNumber: batchNumber + 1,
+ clickRewardId: clickReward.id,
+ startDate,
+ endDate,
},
- });
-
- return logAndRespond(
- `Enqueued next batch (batch #${batchNumber + 1} for aggregate clicks cron (startingAfter: ${nextStartingAfter}).`,
- );
- }
-
- return logAndRespond(endMessage);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
+ })),
+ );
}
-}
-export { handler as GET, handler as POST };
+ return logAndRespond(
+ `Enqueued aggregate clicks jobs for ${clickRewards.length} click rewards.`,
+ );
+});
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 5175dbf390..534fb85336 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
@@ -4,6 +4,7 @@ import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-e
import { notifyPartnerCommission } from "@/lib/api/partners/notify-partner-commission";
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { getRewardSpendLimitWindow } from "@/lib/api/rewards/reward-spend-limit-window";
import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { logger } from "@/lib/axiom/server";
@@ -21,6 +22,7 @@ import {
} from "@/lib/zod/schemas/commissions";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import { COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { buildCommissionDescription } from "@/ui/partners/program-reward-spend-limit";
import { currencyFormatter, log, pick, toCentsNumber } from "@dub/utils";
import {
Commission,
@@ -71,7 +73,6 @@ export const { POST } = serve<Input>(
links: true,
partner: true,
partnerGroup: true,
- ...(event === "click" && { clickReward: true }),
...(event === "lead" && { leadReward: true }),
...(event === "sale" && { saleReward: true }),
},
@@ -181,8 +182,17 @@ async function stepCreateCommission(
amount = 0;
}
+ // Skip invalid reward events (should never happen, but just in case)
+ if (event === "click" || event === "referral") {
+ return logAndReturn({
+ commission: null,
+ outputLog: `"${event}" commissions are not created via this workflow. Skipping commission creation...`,
+ });
+ }
+
+ // for lead / sale rewards, we need to check if the partner is eligible for commissions
if (
- ["click", "lead", "sale"].includes(event) &&
+ ["lead", "sale"].includes(event) &&
!COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES.includes(programEnrollment.status)
) {
return logAndReturn({
@@ -202,7 +212,7 @@ async function stepCreateCommission(
earnings = amount;
amount = 0;
} else {
- if (["lead", "sale"].includes(event) && customerId) {
+ if (customerId) {
firstCommission = await prisma.commission.findFirst({
where: {
partnerId,
@@ -265,105 +275,98 @@ async function stepCreateCommission(
});
}
- // Click commissions are created by /api/cron/aggregate-clicks, not this workflow.
- // TODO: Confirm whether any caller still queues event === "click" here; if not, remove this branch.
- if (event === "click") {
- earnings = getRewardAmount(reward) * quantity;
+ // for lead and sale events, we need to check if this partner-customer combination was recorded already (for deduplication)
+ // for sale rewards specifically, we also need to check:
+ // 1. if the partner has reached the max duration for the reward (if applicable)
+ // 2. if the previous commission were marked as fraud or canceled
+ if (firstCommission) {
+ // if first commission is fraud or canceled, skip commission creation
+ if (["fraud", "canceled"].includes(firstCommission.status)) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has a first commission that is ${firstCommission.status}, skipping commission creation...`,
+ });
+ }
- // for lead and sale events, we need to check if this partner-customer combination was recorded already (for deduplication)
- // for sale rewards specifically, we also need to check:
- // 1. if the partner has reached the max duration for the reward (if applicable)
- // 2. if the previous commission were marked as fraud or canceled
- } else {
- if (firstCommission) {
- // if first commission is fraud or canceled, skip commission creation
- if (["fraud", "canceled"].includes(firstCommission.status)) {
- return logAndReturn({
- commission: null,
- outputLog: `Partner ${partnerId} has a first commission that is ${firstCommission.status}, skipping commission creation...`,
- });
- }
+ // for lead events, we need to check if the partner has already been issued a lead reward for this customer
+ if (event === "lead") {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has already been issued a lead reward for this customer ${customerId}, skipping commission creation...`,
+ });
- // for lead events, we need to check if the partner has already been issued a lead reward for this customer
- if (event === "lead") {
- return logAndReturn({
- commission: null,
- outputLog: `Partner ${partnerId} has already been issued a lead reward for this customer ${customerId}, skipping commission creation...`,
+ // for sale rewards, we need to check if partner's reward was updated and different from the first commission's reward
+ // we need to make sure it wasn't changed from one-time to recurring so we don't create a new commission
+ } else {
+ if (
+ firstCommission.rewardId &&
+ firstCommission.rewardId !== reward.id
+ ) {
+ const originalReward = await prisma.reward.findUnique({
+ where: {
+ id: firstCommission.rewardId,
+ },
+ select: {
+ id: true,
+ maxDuration: true,
+ },
});
- // for sale rewards, we need to check if partner's reward was updated and different from the first commission's reward
- // we need to make sure it wasn't changed from one-time to recurring so we don't create a new commission
- } else {
if (
- firstCommission.rewardId &&
- firstCommission.rewardId !== reward.id
+ typeof originalReward?.maxDuration === "number" &&
+ originalReward.maxDuration === 0
) {
- const originalReward = await prisma.reward.findUnique({
- where: {
- id: firstCommission.rewardId,
- },
- select: {
- id: true,
- maxDuration: true,
- },
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} is only eligible for first-sale commissions based on the original reward ${originalReward.id}, skipping commission creation...`,
});
+ }
+ }
- if (
- typeof originalReward?.maxDuration === "number" &&
- originalReward.maxDuration === 0
- ) {
- return logAndReturn({
- commission: null,
- outputLog: `Partner ${partnerId} is only eligible for first-sale commissions based on the original reward ${originalReward.id}, skipping commission creation...`,
- });
- }
+ // for sale rewards with a max duration, we need to check if the first commission is within the max duration
+ // if it's beyond the max duration, we should not create a new commission
+ if (typeof reward?.maxDuration === "number") {
+ // One-time sale reward (maxDuration === 0)
+ if (reward.maxDuration === 0) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} is only eligible for first-sale commissions, skipping commission creation...`,
+ });
}
- // for sale rewards with a max duration, we need to check if the first commission is within the max duration
- // if it's beyond the max duration, we should not create a new commission
- if (typeof reward?.maxDuration === "number") {
- // One-time sale reward (maxDuration === 0)
- if (reward.maxDuration === 0) {
+ // Recurring sale reward (maxDuration > 0)
+ else {
+ const subscriptionDurationMonths = differenceInMonths(
+ createdAt ?? new Date(), // account for custom commission creation date
+ firstCommission.createdAt,
+ );
+
+ if (subscriptionDurationMonths >= reward.maxDuration) {
return logAndReturn({
commission: null,
- outputLog: `Partner ${partnerId} is only eligible for first-sale commissions, skipping commission creation...`,
+ outputLog: `Partner ${partnerId} has reached max duration for ${event} event (subscription duration: ${subscriptionDurationMonths} months, max duration: ${reward.maxDuration} months), skipping commission creation...`,
});
}
-
- // Recurring sale reward (maxDuration > 0)
- else {
- const subscriptionDurationMonths = differenceInMonths(
- createdAt ?? new Date(), // account for custom commission creation date
- firstCommission.createdAt,
- );
-
- if (subscriptionDurationMonths >= reward.maxDuration) {
- return logAndReturn({
- commission: null,
- outputLog: `Partner ${partnerId} has reached max duration for ${event} event (subscription duration: ${subscriptionDurationMonths} months, max duration: ${reward.maxDuration} months), skipping commission creation...`,
- });
- }
- }
}
}
}
+ }
- // for lead events, we just multiply the reward amount by the quantity
- if (event === "lead") {
- earnings = getRewardAmount(reward) * quantity;
- }
- // for sale events, we need to calculate the earnings based on the sale amount
- else {
- earnings = rewards.reduce(
- (acc, { reward, sale }) =>
- acc +
- calculateSaleEarnings({
- reward,
- sale,
- }),
- 0,
- );
- }
+ // for lead events, we just multiply the reward amount by the quantity
+ if (event === "lead") {
+ earnings = getRewardAmount(reward) * quantity;
+ }
+ // for sale events, we need to calculate the earnings based on the sale amount
+ else {
+ earnings = rewards.reduce(
+ (acc, { reward, sale }) =>
+ acc +
+ calculateSaleEarnings({
+ reward,
+ sale,
+ }),
+ 0,
+ );
}
}
@@ -375,6 +378,41 @@ async function stepCreateCommission(
});
}
+ if (
+ customerId &&
+ event !== "custom" &&
+ reward &&
+ reward.spendLimitAmount &&
+ reward.spendLimitInterval
+ ) {
+ const cappedEarnings = await clampEarningsToSpendLimit({
+ reward,
+ earnings,
+ programId,
+ partnerId,
+ customerId,
+ referenceDate: createdAt ?? new Date(),
+ });
+
+ // If spend limit clamped earnings to 0, skip commission creation
+ if (cappedEarnings === 0) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has reached spend limit (${currencyFormatter(reward.spendLimitAmount)} ${reward.spendLimitInterval === "allTime" ? "in total" : `per ${reward.spendLimitInterval}`}) for ${event} event, skipping commission creation...`,
+ });
+ }
+
+ if (!description) {
+ description = buildCommissionDescription({
+ earnings,
+ cappedEarnings,
+ reward,
+ });
+ }
+
+ earnings = cappedEarnings;
+ }
+
try {
const commission = await prisma.commission.create({
data: {
@@ -597,3 +635,70 @@ async function stepRunSideEffects(
result: results[index],
}));
}
+
+// Reward cap scope:
+// - Sales: partner and customer level
+// - Clicks & Leads: partner level only
+async function clampEarningsToSpendLimit({
+ reward,
+ earnings,
+ programId,
+ partnerId,
+ customerId,
+ referenceDate,
+}: {
+ reward: Pick<
+ RewardProps,
+ "event" | "spendLimitAmount" | "spendLimitInterval"
+ >;
+ earnings: number;
+ programId: string;
+ partnerId: string;
+ customerId: string;
+ referenceDate: Date; // When creating a manual commission, the reference date is the createdAt date
+}) {
+ if (
+ earnings === 0 ||
+ !reward.spendLimitAmount ||
+ !reward.spendLimitInterval
+ ) {
+ return earnings;
+ }
+
+ const { startDate, endDate } = getRewardSpendLimitWindow({
+ spendLimitInterval: reward.spendLimitInterval,
+ referenceDate,
+ });
+
+ // Find the commission earnings for the partner and customer (if applicable) for the spend limit window
+ const {
+ _sum: { earnings: totalEarnings },
+ } = await prisma.commission.aggregate({
+ where: {
+ programId,
+ partnerId,
+ ...(reward.event === "sale" ? { customerId } : {}),
+ type: reward.event,
+ status: {
+ in: ["pending", "processed", "paid"],
+ },
+ // only need to filter if not all-time spend limit (no startDate or endDate)
+ ...(startDate && endDate
+ ? {
+ createdAt: {
+ gte: startDate,
+ lte: endDate,
+ },
+ }
+ : {}),
+ },
+ _sum: {
+ earnings: true,
+ },
+ });
+
+ return Math.max(
+ 0,
+ Math.min(earnings, reward.spendLimitAmount - (totalEarnings ?? 0)),
+ );
+}
diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.ts
index 1a6dfd4ed4..2a3fb31173 100644
--- a/apps/web/lib/actions/partners/create-reward.ts
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -35,6 +35,8 @@ export const createRewardAction = authActionClient
modifiers,
config,
groupId,
+ spendLimitAmount,
+ spendLimitInterval,
} = parsedInput;
throwIfNoPermission({
@@ -43,8 +45,11 @@ export const createRewardAction = authActionClient
});
const programId = getDefaultProgramIdOrThrow(workspace);
- const { canUseAdvancedRewardLogic, canCreateReferralReward } =
- getPlanCapabilities(workspace.plan);
+ const {
+ canUseAdvancedRewardLogic,
+ canSetRewardSpendLimit,
+ canCreateReferralReward,
+ } = getPlanCapabilities(workspace.plan);
if (event === "referral" && !canCreateReferralReward) {
throw new Error(
@@ -58,6 +63,12 @@ export const createRewardAction = authActionClient
);
}
+ if ((spendLimitAmount || spendLimitInterval) && !canSetRewardSpendLimit) {
+ throw new Error(
+ "Spend limits are only available on the Enterprise plan.",
+ );
+ }
+
const group = await getGroupOrThrow({
groupId,
programId,
@@ -85,6 +96,8 @@ export const createRewardAction = authActionClient
tooltipDescription: tooltipDescription || null,
modifiers: modifiers || Prisma.DbNull,
config: config ?? Prisma.DbNull,
+ spendLimitAmount,
+ spendLimitInterval,
...(type === "flat"
? {
amountInCents,
diff --git a/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts b/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
index 222ffd5855..6d8dabae3a 100644
--- a/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
+++ b/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
@@ -4,6 +4,10 @@ import { APP_DOMAIN_WITH_NGROK, prettyPrint } from "@dub/utils";
export async function triggerAggregateDueCommissionsCronJob(programId: string) {
const qstashResponse = await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/aggregate-due-commissions`,
+ flowControl: {
+ key: programId,
+ rate: 1,
+ },
body: {
programId,
},
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index f41cf8f8a0..fcb63d9f70 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -31,6 +31,8 @@ export const updateRewardAction = authActionClient
modifiers,
config,
rewardId,
+ spendLimitAmount,
+ spendLimitInterval,
} = parsedInput;
throwIfNoPermission({
@@ -45,8 +47,11 @@ export const updateRewardAction = authActionClient
programId,
});
- const { canUseAdvancedRewardLogic, canCreateReferralReward } =
- getPlanCapabilities(workspace.plan);
+ const {
+ canUseAdvancedRewardLogic,
+ canSetRewardSpendLimit,
+ canCreateReferralReward,
+ } = getPlanCapabilities(workspace.plan);
if (reward.event === "referral" && !canCreateReferralReward) {
throw new Error(
@@ -60,6 +65,12 @@ export const updateRewardAction = authActionClient
);
}
+ if ((spendLimitAmount || spendLimitInterval) && !canSetRewardSpendLimit) {
+ throw new Error(
+ "Spend limits are only available on the Enterprise plan.",
+ );
+ }
+
validateReward({
...parsedInput,
event: reward.event,
@@ -76,6 +87,8 @@ export const updateRewardAction = authActionClient
tooltipDescription: tooltipDescription || null,
modifiers: modifiers === null ? Prisma.DbNull : modifiers,
config: config === null ? Prisma.DbNull : config,
+ spendLimitAmount,
+ spendLimitInterval,
...(type === "flat"
? {
amountInCents,
diff --git a/apps/web/lib/api/activity-log/track-reward-activity-log.ts b/apps/web/lib/api/activity-log/track-reward-activity-log.ts
index 00aed2c203..4945dca914 100644
--- a/apps/web/lib/api/activity-log/track-reward-activity-log.ts
+++ b/apps/web/lib/api/activity-log/track-reward-activity-log.ts
@@ -26,6 +26,8 @@ function toRewardActivitySnapshot(reward: RewardProps) {
tooltipDescription: reward.tooltipDescription ?? null,
modifiers: reward.modifiers ?? null,
config: reward.config ?? null,
+ spendLimitAmount: reward.spendLimitAmount ?? null,
+ spendLimitInterval: reward.spendLimitInterval ?? null,
};
}
@@ -177,6 +179,8 @@ export function trackRewardActivityLog({
"description",
"tooltipDescription",
"config",
+ "spendLimitAmount",
+ "spendLimitInterval",
],
});
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.ts
index 39ef060d0c..a75327bd6f 100644
--- a/apps/web/lib/api/commissions/create-manual-commissions.ts
+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts
@@ -221,8 +221,8 @@ export async function createManualCommissions(args: CreateCommissionsArgs) {
amount: saleEvent.amount,
currency: saleEvent.currency,
invoiceId: saleEvent.invoiceId,
- // if the invoice payment was refunded on Stripe, set the commission status to refunded as well
createdAt: new Date(saleEvent.timestamp),
+ // if the invoice payment was refunded on Stripe, set the commission status to refunded as well
...(saleEvent.status === "refunded" && {
status: "refunded" as const,
}),
diff --git a/apps/web/lib/api/rewards/reward-spend-limit-window.ts b/apps/web/lib/api/rewards/reward-spend-limit-window.ts
new file mode 100644
index 0000000000..9ba648c9f6
--- /dev/null
+++ b/apps/web/lib/api/rewards/reward-spend-limit-window.ts
@@ -0,0 +1,45 @@
+import { RewardSpendLimitInterval } from "@prisma/client";
+import {
+ endOfDay,
+ endOfMonth,
+ endOfWeek,
+ startOfDay,
+ startOfMonth,
+ startOfWeek,
+} from "date-fns";
+
+export function getRewardSpendLimitWindow({
+ spendLimitInterval,
+ referenceDate,
+}: {
+ spendLimitInterval: RewardSpendLimitInterval;
+ referenceDate: Date; // when calculating historical earnings, this is the start date of the aggregation
+}) {
+ const date = referenceDate;
+
+ if (spendLimitInterval === "day") {
+ return {
+ startDate: startOfDay(date),
+ endDate: endOfDay(date),
+ };
+ }
+
+ if (spendLimitInterval === "week") {
+ return {
+ startDate: startOfWeek(date),
+ endDate: endOfWeek(date),
+ };
+ }
+
+ if (spendLimitInterval === "month") {
+ return {
+ startDate: startOfMonth(date),
+ endDate: endOfMonth(date),
+ };
+ }
+
+ return {
+ startDate: null,
+ endDate: null,
+ };
+}
diff --git a/apps/web/lib/api/rewards/validate-reward.ts b/apps/web/lib/api/rewards/validate-reward.ts
index e700283519..3e062ad4b6 100644
--- a/apps/web/lib/api/rewards/validate-reward.ts
+++ b/apps/web/lib/api/rewards/validate-reward.ts
@@ -200,4 +200,14 @@ export function validateReward(
});
}
}
+
+ const hasSpendLimitAmount = reward.spendLimitAmount != null;
+ const hasSpendLimitInterval = reward.spendLimitInterval != null;
+
+ if (hasSpendLimitAmount !== hasSpendLimitInterval) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Both "spendLimitAmount" and "spendLimitInterval" are required together. Provide both fields or omit both.`,
+ });
+ }
}
diff --git a/apps/web/lib/cron/enqueue-batch-jobs.ts b/apps/web/lib/cron/enqueue-batch-jobs.ts
index 9737c749db..00c69a6555 100644
--- a/apps/web/lib/cron/enqueue-batch-jobs.ts
+++ b/apps/web/lib/cron/enqueue-batch-jobs.ts
@@ -11,7 +11,8 @@ type EnqueueBatchJobsProps = PublishBatchRequest<unknown> & {
| "process-hubspot-webhook"
| "process-intercom-webhook"
| "delete-discount-code"
- | "create-referral-commissions";
+ | "create-referral-commissions"
+ | "aggregate-clicks";
};
// Generic helper to enqueue a batch of QStash jobs.
diff --git a/apps/web/lib/partners/queue-partner-commission-creation.ts b/apps/web/lib/partners/queue-partner-commission-creation.ts
index b504c46e34..bc0bf49f12 100644
--- a/apps/web/lib/partners/queue-partner-commission-creation.ts
+++ b/apps/web/lib/partners/queue-partner-commission-creation.ts
@@ -24,7 +24,7 @@ export const queuePartnerCommissionCreation = async (
workflowLabel: bountySubmissionId ?? customerId ?? partnerId,
body: params,
flowControl: {
- key: customerId ?? partnerId,
+ key: partnerId,
parallelism: 1,
},
});
diff --git a/apps/web/lib/plan-capabilities.ts b/apps/web/lib/plan-capabilities.ts
index 0250ff649a..5c42863a60 100644
--- a/apps/web/lib/plan-capabilities.ts
+++ b/apps/web/lib/plan-capabilities.ts
@@ -14,6 +14,7 @@ export const getPlanCapabilities = (
canExportAuditLogs: !!plan && ["enterprise"].includes(plan),
canUseAdvancedRewardLogic:
!!plan && ["enterprise", "advanced"].includes(plan),
+ canSetRewardSpendLimit: !!plan && ["enterprise"].includes(plan),
canMessagePartners: !!plan && ["enterprise", "advanced"].includes(plan),
canSendEmailCampaigns: !!plan && ["enterprise", "advanced"].includes(plan),
canDiscoverPartners: !!plan && ["enterprise", "advanced"].includes(plan),
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 591569bfdd..8411af998a 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -1,5 +1,9 @@
import { PARTNER_REFERRAL_TRIGGER } from "@/lib/partner-referrals/constants";
-import { EventType, RewardStructure } from "@prisma/client";
+import {
+ EventType,
+ RewardSpendLimitInterval,
+ RewardStructure,
+} from "@prisma/client";
import * as z from "zod/v4";
import { getPaginationQuerySchema, maxDurationSchema } from "./misc";
import { centsSchema } from "./utils";
@@ -301,6 +305,18 @@ export const FLAT_REWARD_AMOUNT_SCHEMA = z
message: "Reward amount cannot be greater than $999,999.99",
});
+const rewardSpendLimitSchema = z.object({
+ spendLimitAmount: z
+ .number()
+ .int()
+ .min(1, { message: "Spend limit amount must be greater than $0" })
+ .max(999_999_99, {
+ message: "Spend limit amount cannot be greater than $999,999.99",
+ })
+ .nullish(),
+ spendLimitInterval: z.enum(RewardSpendLimitInterval).nullish(),
+});
+
export const rewardConditionsSchema = z.object({
id: z.string().optional(),
operator: z.enum(["AND", "OR"]).default("AND"),
@@ -333,6 +349,7 @@ export const RewardSchema = z.object({
modifiers: z.any().nullish(), // TODO: Fix this
config: z.any().nullish(),
updatedAt: z.coerce.date(),
+ ...rewardSpendLimitSchema.shape,
});
export const REWARD_DESCRIPTION_MAX_LENGTH = 100;
@@ -371,6 +388,7 @@ export const createOrUpdateRewardSchema = z.object({
.max(REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH)
.nullish(),
groupId: z.string(),
+ ...rewardSpendLimitSchema.shape,
});
export const createRewardSchema = createOrUpdateRewardSchema.superRefine(
diff --git a/apps/web/prisma/schema/reward.prisma b/apps/web/prisma/schema/reward.prisma
index d9cb25b53c..71de7cf612 100644
--- a/apps/web/prisma/schema/reward.prisma
+++ b/apps/web/prisma/schema/reward.prisma
@@ -10,20 +10,29 @@ enum RewardStructure {
flat
}
+enum RewardSpendLimitInterval {
+ allTime
+ day
+ week
+ month
+}
+
model Reward {
- id String @id
+ id String @id
programId String?
description String?
- tooltipDescription String? @db.Text
+ tooltipDescription String? @db.Text
event EventType
- type RewardStructure @default(percentage)
+ type RewardStructure @default(percentage)
amountInCents Int?
- amountInPercentage Decimal? @db.Decimal(5, 2)
+ amountInPercentage Decimal? @db.Decimal(5, 2)
maxDuration Int? // in months (0 -> not recurring, null -> infinite)
- modifiers Json? @db.Json
- config Json? @db.Json
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ modifiers Json? @db.Json
+ config Json? @db.Json
+ spendLimitAmount Int?
+ spendLimitInterval RewardSpendLimitInterval?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
program Program? @relation(fields: [programId], references: [id])
clickEnrollments ProgramEnrollment[] @relation("ClickRewardEnrollments")
diff --git a/apps/web/tests/commissions/create-commission.test.ts b/apps/web/tests/commissions/create-commission.test.ts
index eb5632b63a..04aae324f0 100644
--- a/apps/web/tests/commissions/create-commission.test.ts
+++ b/apps/web/tests/commissions/create-commission.test.ts
@@ -77,25 +77,18 @@ describe.concurrent("POST /commissions", async () => {
expect(status).toEqual(202);
expect(data).toStrictEqual(expectedQueuedResponse);
- await new Promise((resolve) => setTimeout(resolve, 2000));
-
- const { data: commissions } = await http.get<CommissionResponse[]>({
- path: "/commissions",
+ await verifyCommission({
+ http,
+ description,
+ expectedEarnings: 500,
+ expectedType: "custom",
query: {
partnerId: E2E_PARTNER.id,
type: "custom",
sortBy: "createdAt",
sortOrder: "desc",
- pageSize: "1",
},
});
-
- const commissionFound = commissions.find(
- (c) => c.description === description,
- );
- expect(commissionFound).toBeDefined();
- expect(commissionFound!.earnings).toEqual(500);
- expect(commissionFound!.type).toEqual("custom");
});
test("create lead commission", async () => {
diff --git a/apps/web/tests/rewards/click-reward.test.ts b/apps/web/tests/rewards/click-reward.test.ts
index 50a9746a08..9ce0035c94 100644
--- a/apps/web/tests/rewards/click-reward.test.ts
+++ b/apps/web/tests/rewards/click-reward.test.ts
@@ -1,6 +1,8 @@
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { Reward } from "@prisma/client";
import { describe, expect, test, vi } from "vitest";
-import { resolveClickRewardAmount } from "../../app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount";
+import { resolveClickReward } from "../../app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount";
import { IntegrationHarness } from "../utils/integration";
// Mock server-only module
@@ -26,11 +28,13 @@ describe.sequential("Click reward resolution", async () => {
const modifierCountries = ["US", "GB", "AU"];
modifierCountries.forEach((country) => {
- const amount = resolveClickRewardAmount({
+ const clickReward = resolveClickReward({
reward,
country,
});
+ const amount = getRewardAmount(serializeReward(clickReward));
+
expect(amount).toBe(100);
});
});
@@ -41,11 +45,13 @@ describe.sequential("Click reward resolution", async () => {
const otherCountries = ["CA", "FR", "DE", "JP"];
otherCountries.forEach((country) => {
- const amount = resolveClickRewardAmount({
+ const clickReward = resolveClickReward({
reward,
country,
});
+ const amount = getRewardAmount(serializeReward(clickReward));
+
expect(amount).toBe(20);
});
});
@@ -63,11 +69,13 @@ describe.sequential("Click reward resolution", async () => {
];
testCases.forEach(({ country, expected }) => {
- const amount = resolveClickRewardAmount({
+ const clickReward = resolveClickReward({
reward,
country,
});
+ const amount = getRewardAmount(serializeReward(clickReward));
+
expect(amount).toBe(expected);
});
});
diff --git a/apps/web/tests/utils/verify-commission.ts b/apps/web/tests/utils/verify-commission.ts
index b5984797e3..5251d95c04 100644
--- a/apps/web/tests/utils/verify-commission.ts
+++ b/apps/web/tests/utils/verify-commission.ts
@@ -9,17 +9,23 @@ import { HttpClient } from "./http";
interface VerifyCommissionProps {
http: HttpClient;
customerExternalId?: string;
- invoiceId?: string;
+ invoiceId?: string; // fetch commission by invoiceId
+ description?: string; // fetch commissions + filter by description
expectedSaleAmount?: number;
expectedEarnings: number;
+ expectedType?: string;
+ query?: Record<string, string>; // to pass additional query params to GET /commissions
}
export const verifyCommission = async ({
http,
customerExternalId,
invoiceId,
+ description,
expectedSaleAmount,
expectedEarnings,
+ expectedType,
+ query: queryOverrides,
}: VerifyCommissionProps) => {
let customerId: string | undefined;
@@ -34,7 +40,9 @@ export const verifyCommission = async ({
customerId = customers[0].id;
}
- const query: Record<string, string> = {};
+ const query: Record<string, string> = {
+ ...queryOverrides,
+ };
if (invoiceId) {
query.invoiceId = invoiceId;
@@ -43,6 +51,19 @@ export const verifyCommission = async ({
if (customerId) {
query.customerId = customerId;
}
+ const findMatchingCommission = (
+ commissions: CommissionResponse[],
+ ): CommissionResponse | undefined => {
+ if (description) {
+ return commissions.find((c) => c.description === description);
+ }
+
+ if (commissions.length === 1) {
+ return commissions[0];
+ }
+
+ return undefined;
+ };
// Poll for commission every 5 seconds, timeout after 60 seconds
const startTime = Date.now();
@@ -53,10 +74,9 @@ export const verifyCommission = async ({
query,
});
- if (status === 200 && commissions.length === 1) {
- const commission = commissions[0];
+ const commission = findMatchingCommission(commissions);
- // Verify all expectations
+ if (status === 200 && commission) {
if (invoiceId) {
expect(commission.invoiceId).toEqual(invoiceId);
}
@@ -71,6 +91,10 @@ export const verifyCommission = async ({
expect(commission.earnings).toEqual(expectedEarnings);
+ if (expectedType) {
+ expect(commission.type).toEqual(expectedType);
+ }
+
return;
}
@@ -83,6 +107,7 @@ export const verifyCommission = async ({
// Timeout reached - fail the test
throw new Error(
`Commission not found within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +
- `Query: ${JSON.stringify(query)}`,
+ `Query: ${JSON.stringify(query)}` +
+ (description ? `, description: ${description}` : ""),
);
};
diff --git a/apps/web/ui/partners/format-reward-description.ts b/apps/web/ui/partners/format-reward-description.ts
index 63dfd0c7c8..eb7938066c 100644
--- a/apps/web/ui/partners/format-reward-description.ts
+++ b/apps/web/ui/partners/format-reward-description.ts
@@ -7,6 +7,8 @@ import {
import { RewardProps } from "@/lib/types";
import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
import { currencyFormatter } from "@dub/utils";
+import { RewardSpendLimitInterval } from "@prisma/client";
+import { getSpendLimitDescriptionParts } from "./program-reward-spend-limit";
export function formatRewardDescription(
reward: RewardProps,
@@ -45,7 +47,18 @@ export function formatRewardDescription(
parts.push(`for ${durationText}`);
}
- return parts.join(" ");
+ const spendLimitParts = getSpendLimitDescriptionParts({
+ spendLimitAmount: reward.spendLimitAmount,
+ spendLimitInterval: reward.spendLimitInterval,
+ });
+
+ let description = parts.join(" ");
+
+ if (spendLimitParts && reward.spendLimitInterval) {
+ description += `, with a ${spendLimitParts.amount} ${formatSpendLimitIntervalLabel(reward.spendLimitInterval)} limit`;
+ }
+
+ return description;
}
function formatReferralRewardDescription(
@@ -139,3 +152,16 @@ function formatReferralDuration(maxDuration: number | null | undefined) {
return "";
}
+
+function formatSpendLimitIntervalLabel(interval: RewardSpendLimitInterval) {
+ switch (interval) {
+ case "day":
+ return "daily";
+ case "week":
+ return "weekly";
+ case "month":
+ return "monthly";
+ case "allTime":
+ return "in total";
+ }
+}
diff --git a/apps/web/ui/partners/program-reward-description.tsx b/apps/web/ui/partners/program-reward-description.tsx
index bef47e1d1e..9b1a36d630 100644
--- a/apps/web/ui/partners/program-reward-description.tsx
+++ b/apps/web/ui/partners/program-reward-description.tsx
@@ -9,6 +9,7 @@ import { DiscountProps, RewardProps } from "@/lib/types";
import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
import { cn, currencyFormatter } from "@dub/utils";
import { ProgramRewardModifiersTooltip } from "./program-reward-modifiers-tooltip";
+import { ProgramRewardSpendLimit } from "./program-reward-spend-limit";
export function ProgramRewardDescription({
reward,
@@ -28,6 +29,8 @@ export function ProgramRewardDescription({
| "amountInCents"
| "amountInPercentage"
| "config"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
> | null;
discount?: DiscountProps | null;
amountClassName?: string;
@@ -80,6 +83,11 @@ export function ProgramRewardDescription({
</>
))}
+ <ProgramRewardSpendLimit
+ spendLimitAmount={reward.spendLimitAmount}
+ spendLimitInterval={reward.spendLimitInterval}
+ />
+
{/* Modifiers */}
{showModifiersTooltip &&
(!!reward.modifiers?.length ||
diff --git a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
index 5ff9afdcaa..6464c8ea98 100644
--- a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
+++ b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
@@ -99,6 +99,8 @@ export function ProgramRewardModifiersTooltipContent({
modifier.maxDuration === undefined
? reward.maxDuration
: modifier.maxDuration, // fallback to primary
+ spendLimitAmount: reward.spendLimitAmount,
+ spendLimitInterval: reward.spendLimitInterval,
}}
conditions={modifier.conditions}
operator={modifier.operator}
diff --git a/apps/web/ui/partners/program-reward-spend-limit.tsx b/apps/web/ui/partners/program-reward-spend-limit.tsx
new file mode 100644
index 0000000000..cafd349d30
--- /dev/null
+++ b/apps/web/ui/partners/program-reward-spend-limit.tsx
@@ -0,0 +1,81 @@
+import { RewardProps } from "@/lib/types";
+import { currencyFormatter } from "@dub/utils";
+import { RewardSpendLimitInterval } from "@prisma/client";
+
+export function getSpendLimitDescriptionParts({
+ spendLimitAmount,
+ spendLimitInterval,
+}: Pick<RewardProps, "spendLimitAmount" | "spendLimitInterval">) {
+ if (spendLimitAmount == null || spendLimitInterval == null) {
+ return null;
+ }
+
+ return {
+ amount: currencyFormatter(spendLimitAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ }),
+ interval:
+ spendLimitInterval === "allTime"
+ ? "in total"
+ : `per ${spendLimitInterval}`,
+ };
+}
+
+export function ProgramRewardSpendLimit({
+ spendLimitAmount,
+ spendLimitInterval,
+}: {
+ spendLimitAmount?: number | null;
+ spendLimitInterval?: RewardSpendLimitInterval | null;
+}) {
+ const parts = getSpendLimitDescriptionParts({
+ spendLimitAmount,
+ spendLimitInterval,
+ });
+
+ if (!parts) {
+ return null;
+ }
+
+ return ` up to ${parts.amount} ${parts.interval}`;
+}
+
+export function buildCommissionDescription({
+ earnings,
+ cappedEarnings,
+ reward,
+}: {
+ earnings: number;
+ cappedEarnings: number;
+ reward: Pick<
+ RewardProps,
+ | "event"
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
+ >;
+}) {
+ if (earnings <= cappedEarnings) {
+ return null;
+ }
+
+ const limitParts = getSpendLimitDescriptionParts({
+ spendLimitAmount: reward.spendLimitAmount,
+ spendLimitInterval: reward.spendLimitInterval,
+ });
+
+ if (!limitParts) {
+ return null;
+ }
+
+ const amount =
+ reward.type === "percentage"
+ ? `${reward.amountInPercentage ?? 0}%`
+ : currencyFormatter(reward.amountInCents ?? 0, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ return `Earn ${amount} per ${reward.event} up to ${limitParts.amount} ${limitParts.interval}`;
+}
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 e5b4aba35b..c7d99b85e0 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -187,6 +187,10 @@ export const getRewardPayload = ({ data }: { data: FormData }) => {
...amount,
maxDuration:
Infinity === Number(data.maxDuration) ? null : data.maxDuration,
+ spendLimitAmount:
+ data.spendLimitAmount == null || data.spendLimitInterval == null
+ ? null
+ : Math.round(Number(data.spendLimitAmount) * 100),
modifiers,
config,
};
@@ -231,6 +235,11 @@ function RewardSheetContent({
defaultValuesSource?.amountInPercentage != null
? defaultValuesSource.amountInPercentage
: undefined,
+ spendLimitAmount:
+ defaultValuesSource?.spendLimitAmount != null
+ ? defaultValuesSource.spendLimitAmount / 100
+ : null,
+ spendLimitInterval: defaultValuesSource?.spendLimitInterval ?? null,
description: defaultValuesSource?.description ?? null,
tooltipDescription: defaultValuesSource?.tooltipDescription ?? null,
modifiers: Array.isArray(defaultValuesSource?.modifiers)
@@ -273,6 +282,8 @@ function RewardSheetContent({
amountInPercentage,
type,
maxDuration,
+ spendLimitAmount,
+ spendLimitInterval,
description,
tooltipDescription,
modifiers,
@@ -282,6 +293,8 @@ function RewardSheetContent({
"amountInPercentage",
"type",
"maxDuration",
+ "spendLimitAmount",
+ "spendLimitInterval",
"description",
"tooltipDescription",
"modifiers",
@@ -289,6 +302,17 @@ function RewardSheetContent({
// Compute amount based on type
const amount = type === "flat" ? amountInCents : amountInPercentage;
+ const {
+ canCreateReferralReward,
+ canSetRewardSpendLimit,
+ canUseAdvancedRewardLogic,
+ } = getPlanCapabilities(plan);
+ const spendLimitEnabled =
+ canSetRewardSpendLimit && spendLimitInterval != null;
+ const hasIncompleteMainSpendLimit =
+ canSetRewardSpendLimit &&
+ spendLimitInterval != null &&
+ (spendLimitAmount == null || isNaN(spendLimitAmount));
const { executeAsync: createReward, isPending: isCreating } = useAction(
createRewardAction,
@@ -336,19 +360,15 @@ function RewardSheetContent({
);
const [showAdvancedUpsell, setShowAdvancedUpsell] = useState(false);
- const showReferralUpsell =
- event === "referral" && !getPlanCapabilities(plan).canCreateReferralReward;
+ const showReferralUpsell = event === "referral" && !canCreateReferralReward;
useEffect(() => {
- if (
- modifiers?.length &&
- !getPlanCapabilities(plan).canUseAdvancedRewardLogic
- ) {
+ if (modifiers?.length && !canUseAdvancedRewardLogic) {
setShowAdvancedUpsell(true);
} else {
setShowAdvancedUpsell(false);
}
- }, [modifiers, plan]);
+ }, [modifiers, canUseAdvancedRewardLogic]);
const onSubmit = async (data: FormData) => {
if (
@@ -505,6 +525,95 @@ function RewardSheetContent({
{modifiers?.length ? (
<> for all other {selectedEvent}s</>
) : null}
+ {canSetRewardSpendLimit ? (
+ <>
+ {", "}with{" "}
+ <InlineBadgePopover
+ text={
+ spendLimitEnabled
+ ? "a spend limit of"
+ : "no spend limit"
+ }
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={
+ spendLimitEnabled ? "limit" : "none"
+ }
+ onSelect={(value) => {
+ if (value === "none") {
+ setValue("spendLimitAmount", null, {
+ shouldDirty: true,
+ });
+ setValue("spendLimitInterval", null, {
+ shouldDirty: true,
+ });
+ } else {
+ setValue(
+ "spendLimitInterval",
+ spendLimitInterval ?? "allTime",
+ {
+ shouldDirty: true,
+ },
+ );
+ }
+ }}
+ items={[
+ { text: "no spend limit", value: "none" },
+ {
+ text: "a spend limit of",
+ value: "limit",
+ },
+ ]}
+ />
+ </InlineBadgePopover>{" "}
+ {spendLimitEnabled ? (
+ <>
+ <InlineBadgePopover
+ text={
+ spendLimitAmount != null &&
+ !isNaN(spendLimitAmount)
+ ? `$${spendLimitAmount}`
+ : "amount"
+ }
+ invalid={
+ spendLimitAmount == null ||
+ isNaN(spendLimitAmount)
+ }
+ >
+ <SpendLimitAmountInput />
+ </InlineBadgePopover>{" "}
+ <InlineBadgePopover
+ text={
+ spendLimitInterval === "allTime"
+ ? "all-time"
+ : `per ${spendLimitInterval}`
+ }
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={
+ spendLimitInterval ?? "allTime"
+ }
+ onSelect={(value) =>
+ setValue(
+ "spendLimitInterval",
+ value as any,
+ {
+ shouldDirty: true,
+ },
+ )
+ }
+ items={[
+ { text: "all-time", value: "allTime" },
+ { text: "per day", value: "day" },
+ { text: "per week", value: "week" },
+ { text: "per month", value: "month" },
+ ]}
+ />
+ </InlineBadgePopover>
+ </>
+ ) : null}
+ </>
+ ) : null}
</span>
)}
</div>
@@ -649,7 +758,11 @@ function RewardSheetContent({
className="h-9 w-fit"
loading={isCreating || isUpdating}
disabled={
- amount == null || isDeleting || isCreating || isUpdating
+ amount == null ||
+ hasIncompleteMainSpendLimit ||
+ isDeleting ||
+ isCreating ||
+ isUpdating
}
disabledTooltip={
showReferralUpsell ? (
@@ -810,6 +923,40 @@ function AmountInput() {
);
}
+function SpendLimitAmountInput() {
+ 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-400">
+ $
+ </span>
+ <input
+ className="block w-full rounded-md border-neutral-300 px-1.5 py-1 pl-4 pr-12 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm"
+ {...register("spendLimitAmount", {
+ required: true,
+ setValueAs: (value: string) => (value === "" ? null : +value),
+ min: 1,
+ onChange: handleMoneyInputChange,
+ })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setIsOpen(false);
+ return;
+ }
+
+ handleMoneyKeyDown(e);
+ }}
+ />
+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">
+ USD
+ </span>
+ </div>
+ );
+}
+
export function RewardSheet({
isOpen,
nested,