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.

Persist commission descriptions from applied reward and conditions

Kiran K14dc3836363f
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
index 10509b2d71..3580d6731f 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/process/route.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/process/route.ts
@@ -2,13 +2,13 @@ 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 { buildCommissionDescription } from "@/lib/commissions/build-commission-description";
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,
@@ -194,7 +194,7 @@ export const POST = withCron(async ({ rawBody }) => {
return null;
}
- let description: string | null = null;
+ let cappedEarnings = earnings;
// Cap earnings to spend limit
if (clickReward.spendLimitAmount && clickReward.spendLimitInterval) {
@@ -205,10 +205,7 @@ export const POST = withCron(async ({ rawBody }) => {
const remainingSpendLimit =
clickReward.spendLimitAmount - historicalEarnings - usedThisBatch;
- const cappedEarnings = Math.max(
- 0,
- Math.min(earnings, remainingSpendLimit),
- );
+ cappedEarnings = Math.max(0, Math.min(earnings, remainingSpendLimit));
if (cappedEarnings === 0) {
console.log(`Reached spend limit for partner ${partnerId}.`);
@@ -216,16 +213,16 @@ export const POST = withCron(async ({ rawBody }) => {
}
usedSpendLimitByPartner.set(partnerId, usedThisBatch + cappedEarnings);
-
- description = buildCommissionDescription({
- earnings,
- cappedEarnings,
- reward: serializeReward(clickReward),
- });
-
- earnings = cappedEarnings;
}
+ // Persist the base click reward description (no per-country clause —
+ // one commission can mix countries/rates).
+ const description = buildCommissionDescription({
+ reward: serializeReward(clickReward),
+ earnings,
+ cappedEarnings,
+ });
+
return {
id: createId({ prefix: "cm_" }),
programId,
@@ -235,7 +232,7 @@ export const POST = withCron(async ({ rawBody }) => {
quantity: clicks,
type: CommissionType.click,
amount: 0,
- earnings,
+ earnings: cappedEarnings,
description,
createdAt: endDate,
invoiceId: `${linkId}-${aggregationDate}`, // used as a idempotency key
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 4f349b61d9..3a4ede5c66 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
@@ -10,6 +10,7 @@ import { getRewardSpendLimitWindow } from "@/lib/api/rewards/reward-spend-limit-
import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { logger } from "@/lib/axiom/server";
+import { buildCommissionDescription } from "@/lib/commissions/build-commission-description";
import { constructWebhookPartner } from "@/lib/partners/constuct-webhook-partner";
import {
determinePartnerRewards,
@@ -19,7 +20,7 @@ import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { prisma } from "@/lib/prisma";
-import { RewardProps } from "@/lib/types";
+import { RewardConditions, RewardProps } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
CommissionWebhookSchema,
@@ -27,7 +28,6 @@ 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,
@@ -219,6 +219,7 @@ async function stepCreateCommission(
let earnings = 0;
let reward: RewardProps | null = null;
+ let matchedCondition: RewardConditions | null = null;
let firstCommission: Pick<
Commission,
"rewardId" | "status" | "createdAt"
@@ -281,6 +282,7 @@ async function stepCreateCommission(
if (rewards.length > 0) {
reward = rewards[0].reward;
+ matchedCondition = rewards[0].matchedCondition;
}
// if there is no reward, skip commission creation
@@ -402,6 +404,8 @@ async function stepCreateCommission(
});
}
+ let cappedEarnings = earnings;
+
if (
customerId &&
event !== "custom" &&
@@ -409,7 +413,7 @@ async function stepCreateCommission(
reward.spendLimitAmount &&
reward.spendLimitInterval
) {
- const cappedEarnings = await clampEarningsToSpendLimit({
+ cappedEarnings = await clampEarningsToSpendLimit({
reward,
earnings,
programId,
@@ -425,16 +429,6 @@ async function stepCreateCommission(
outputLog: `Partner ${partnerId} has reached spend limit (${currencyFormatter(reward.spendLimitAmount)} ${reward.spendLimitInterval === "allTime" ? "" : `per ${reward.spendLimitInterval}`}) for ${event} event, skipping commission creation...`,
});
}
-
- if (!description) {
- description = buildCommissionDescription({
- earnings,
- cappedEarnings,
- reward,
- });
- }
-
- earnings = cappedEarnings;
}
// Custom reward jobs are queued from a snapshot of eligible enrollments.
@@ -455,6 +449,20 @@ async function stepCreateCommission(
});
}
+ // Snapshot the applied reward (and matched condition) so the activity log
+ // does not fall back to the live reward after later edits.
+ // Known limitation: when determinePartnerRewards splits Stripe products into
+ // multiple line rewards and we sum earnings, we only describe rewards[0]'s
+ // rate/condition — not every product line.
+ if (!description && reward && event !== "custom") {
+ description = buildCommissionDescription({
+ reward,
+ matchedCondition,
+ earnings,
+ cappedEarnings,
+ });
+ }
+
try {
const commission = await prisma.commission.create({
data: {
@@ -471,7 +479,7 @@ async function stepCreateCommission(
amount,
type: event,
currency,
- earnings,
+ earnings: cappedEarnings,
status,
description,
createdAt,
diff --git a/apps/web/lib/api/commissions/update-partner-commission.ts b/apps/web/lib/api/commissions/update-partner-commission.ts
index c9a6ffe241..5d8b4b8c12 100644
--- a/apps/web/lib/api/commissions/update-partner-commission.ts
+++ b/apps/web/lib/api/commissions/update-partner-commission.ts
@@ -150,7 +150,7 @@ export async function updatePartnerCommission({
const reward = determinePartnerReward({
event: "sale",
programEnrollment,
- });
+ })?.reward;
if (!reward) {
throw new DubApiError({
diff --git a/apps/web/lib/commissions/build-commission-description.ts b/apps/web/lib/commissions/build-commission-description.ts
new file mode 100644
index 0000000000..333af59f1e
--- /dev/null
+++ b/apps/web/lib/commissions/build-commission-description.ts
@@ -0,0 +1,93 @@
+import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { formatRewardConditionClause } from "@/lib/rewards/format-reward-condition";
+import { getSpendLimitDescriptionParts } from "@/lib/rewards/reward-spend-limit";
+import { RewardConditions, RewardProps } from "@/lib/types";
+import { currencyFormatter } from "@dub/utils";
+
+export function buildCommissionDescription({
+ reward,
+ matchedCondition,
+ earnings,
+ cappedEarnings,
+}: {
+ // Already resolved by determinePartnerReward (matched condition amounts applied)
+ reward: Pick<
+ RewardProps,
+ | "event"
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "maxDuration"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
+ >;
+ matchedCondition?: RewardConditions | null;
+ // Pre-spend-limit earnings (used to detect whether the limit was applied)
+ earnings?: number;
+ // Earnings after spend-limit clamping (same as earnings when not capped)
+ cappedEarnings?: number;
+}): string {
+ const rewardAmount = constructRewardAmount({
+ ...reward,
+ modifiers: undefined,
+ });
+
+ const parts: string[] = ["Earn", rewardAmount];
+
+ if (reward.event === "sale" && reward.maxDuration === 0) {
+ parts.push("for the first sale");
+ } else {
+ parts.push(`per ${reward.event}`);
+ }
+
+ // Duration only applies to sale rewards (click/lead are one-off)
+ if (reward.event === "sale") {
+ if (reward.maxDuration === null) {
+ parts.push("for the customer's lifetime");
+ } else if (reward.maxDuration && reward.maxDuration > 1) {
+ const durationText =
+ reward.maxDuration % 12 === 0
+ ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
+ : `${reward.maxDuration} months`;
+ parts.push(`for ${durationText}`);
+ }
+ }
+
+ let description = parts.join(" ");
+
+ if (matchedCondition?.conditions?.length) {
+ const clauses = matchedCondition.conditions.map((condition, idx) =>
+ formatRewardConditionClause({
+ condition,
+ event: reward.event,
+ operator: matchedCondition.operator,
+ isFirst: idx === 0,
+ }),
+ );
+
+ description += ` ${clauses.join(" ")}`;
+ }
+
+ if (earnings != null && cappedEarnings != null && earnings > cappedEarnings) {
+ const from = currencyFormatter(earnings, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+ const to = currencyFormatter(cappedEarnings, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ const limitParts = getSpendLimitDescriptionParts({
+ spendLimitAmount: reward.spendLimitAmount,
+ spendLimitInterval: reward.spendLimitInterval,
+ });
+ const limitLabel = limitParts
+ ? [limitParts.amount, limitParts.interval].filter(Boolean).join(" ")
+ : null;
+
+ description += limitLabel
+ ? `, capped from ${from} to ${to} due to ${limitLabel} spend limit`
+ : `, capped from ${from} to ${to} due to spend limit`;
+ }
+
+ return description;
+}
diff --git a/apps/web/lib/partner-referrals/create-network-referral-commission.ts b/apps/web/lib/partner-referrals/create-network-referral-commission.ts
index 94ef0d3d69..e99a64b843 100644
--- a/apps/web/lib/partner-referrals/create-network-referral-commission.ts
+++ b/apps/web/lib/partner-referrals/create-network-referral-commission.ts
@@ -1,8 +1,8 @@
import { prisma } from "@/lib/prisma";
import {
ACME_PROGRAM_ID,
- DEMO_PROGRAM_ID,
currencyFormatter,
+ DEMO_PROGRAM_ID,
log,
nanoid,
NETWORK_PROGRAM_ID,
@@ -170,7 +170,7 @@ export const createNetworkReferralCommission = async ({
const reward = determinePartnerReward({
event: "sale",
programEnrollment,
- });
+ })?.reward;
if (!reward) {
console.log(
diff --git a/apps/web/lib/partners/determine-partner-reward.ts b/apps/web/lib/partners/determine-partner-reward.ts
index 7d9de8e24d..efadb94115 100644
--- a/apps/web/lib/partners/determine-partner-reward.ts
+++ b/apps/web/lib/partners/determine-partner-reward.ts
@@ -1,7 +1,7 @@
import { prettyPrint, toCentsNumber } from "@dub/utils";
import { EventType, Link, Prisma, Reward } from "@prisma/client";
import { serializeReward } from "../api/partners/serialize-reward";
-import { RewardContext, RewardProps } from "../types";
+import { RewardConditions, RewardContext, RewardProps } from "../types";
import {
rewardConditionsArraySchema,
RewardSchema,
@@ -27,6 +27,7 @@ interface ProgramEnrollmentWithReward {
interface ProductReward {
reward: RewardProps;
+ matchedCondition: RewardConditions | null;
sale: {
amount: number;
quantity: number;
@@ -70,7 +71,10 @@ export const determinePartnerReward = ({
event: EventType;
programEnrollment: ProgramEnrollmentWithReward;
context?: RewardContext; // additional reward context (e.g. customer.country, sale.productId, etc.)
-}) => {
+}): {
+ reward: RewardProps;
+ matchedCondition: RewardConditions | null;
+} | null => {
let partnerReward: Reward =
programEnrollment[REWARD_EVENT_COLUMN_MAPPING[event]];
@@ -91,6 +95,8 @@ export const determinePartnerReward = ({
},
};
+ let matchedCondition: RewardConditions | null = null;
+
if (partnerReward.modifiers && context) {
const modifiers = rewardConditionsArraySchema.safeParse(
partnerReward.modifiers,
@@ -98,7 +104,7 @@ export const determinePartnerReward = ({
// Parse the conditions before evaluating them
if (modifiers.success) {
- const matchedCondition = evaluateRewardConditions({
+ matchedCondition = evaluateRewardConditions({
conditions: modifiers.data,
context,
});
@@ -131,7 +137,10 @@ export const determinePartnerReward = ({
return null;
}
- return RewardSchema.parse(partnerReward);
+ return {
+ reward: RewardSchema.parse(partnerReward),
+ matchedCondition,
+ };
};
export const determinePartnerRewards = ({
@@ -165,7 +174,7 @@ export const determinePartnerRewards = ({
// we need to calculate the reward for each product (for Stripe integration only)
if (products.length > 0 && hasProductIdModifier) {
for (const product of products) {
- const reward = determinePartnerReward({
+ const result = determinePartnerReward({
event,
programEnrollment,
context: {
@@ -178,11 +187,12 @@ export const determinePartnerRewards = ({
},
});
- if (reward) {
+ if (result) {
// product.amount is the Stripe line total (unit × quantity). Flat
// rewards are per sale/line, so do not multiply by line.quantity.
rewards.push({
- reward,
+ reward: result.reward,
+ matchedCondition: result.matchedCondition,
sale: {
amount: product.amount,
quantity: 1,
@@ -191,15 +201,16 @@ export const determinePartnerRewards = ({
}
}
} else {
- const reward = determinePartnerReward({
+ const result = determinePartnerReward({
event,
programEnrollment,
...(context ? { context } : {}),
});
- if (reward) {
+ if (result) {
rewards.push({
- reward,
+ reward: result.reward,
+ matchedCondition: result.matchedCondition,
sale: {
amount,
quantity,
diff --git a/apps/web/lib/rewards/format-reward-condition.ts b/apps/web/lib/rewards/format-reward-condition.ts
new file mode 100644
index 0000000000..a7bec934bb
--- /dev/null
+++ b/apps/web/lib/rewards/format-reward-condition.ts
@@ -0,0 +1,138 @@
+import { RewardCondition, RewardConditions, RewardProps } from "@/lib/types";
+import {
+ CONDITION_OPERATOR_LABELS,
+ REWARD_CONDITIONS,
+} from "@/lib/zod/schemas/rewards";
+import {
+ COUNTRIES,
+ capitalize,
+ currencyFormatter,
+ formatDateTime,
+} from "@dub/utils";
+import { formatDuration } from "date-fns";
+
+export function formatRewardConditionParts({
+ condition,
+ event,
+}: {
+ condition: RewardCondition;
+ event: RewardProps["event"];
+}) {
+ const entity = REWARD_CONDITIONS[event].entities.find(
+ (e) => e.id === condition.entity,
+ );
+ const attribute = entity?.attributes?.find(
+ (a) => a.id === condition.attribute,
+ );
+
+ const attributeLabel =
+ (condition.entity === "lead" || condition.entity === "sale") &&
+ condition.attribute === "metadata" &&
+ condition.metadataField?.trim()
+ ? `"${condition.metadataField.trim()}"`
+ : capitalize(attribute?.label);
+
+ const operatorLabel = condition.label
+ ? "is"
+ : CONDITION_OPERATOR_LABELS[condition.operator];
+
+ return {
+ entityLabel: capitalize(condition.entity),
+ attributeLabel: attributeLabel ?? "",
+ operatorLabel,
+ valueLabel: formatRewardConditionValue({ condition, attribute }),
+ };
+}
+
+export function formatRewardConditionClause({
+ condition,
+ event,
+ operator,
+ isFirst,
+}: {
+ condition: RewardCondition;
+ event: RewardProps["event"];
+ operator: RewardConditions["operator"];
+ isFirst: boolean;
+}): string {
+ const { entityLabel, attributeLabel, operatorLabel, valueLabel } =
+ formatRewardConditionParts({ condition, event });
+
+ return [
+ isFirst ? "if" : operator.toLowerCase(),
+ entityLabel,
+ attributeLabel,
+ operatorLabel,
+ valueLabel,
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+function formatRewardConditionValue({
+ condition,
+ attribute,
+}: {
+ condition: RewardCondition;
+ attribute:
+ | {
+ type: string;
+ options?: { id: string; label: string }[];
+ }
+ | undefined;
+}): string {
+ if (condition.value == null || condition.value === "") {
+ return "";
+ }
+
+ if (condition.attribute === "country") {
+ if (Array.isArray(condition.value)) {
+ return (condition.value as (string | number)[])
+ .map((v) => COUNTRIES[v?.toString()] ?? v)
+ .join(", ");
+ }
+
+ return COUNTRIES[condition.value?.toString()] ?? condition.value.toString();
+ }
+
+ if (condition.attribute === "subscriptionDurationMonths") {
+ return formatSubscriptionDuration(Number(condition.value));
+ }
+
+ if (condition.attribute === "productId" && condition.label?.trim()) {
+ return condition.label.trim();
+ }
+
+ if (Array.isArray(condition.value)) {
+ return (
+ attribute?.options
+ ? (condition.value as (string | number)[]).map(
+ (v) => attribute.options?.find((o) => o.id === v)?.label ?? v,
+ )
+ : condition.value
+ ).join(", ");
+ }
+
+ if (attribute?.type === "currency") {
+ return currencyFormatter(Number(condition.value));
+ }
+
+ if (attribute?.type === "date") {
+ return formatDateTime(new Date(Number(condition.value)));
+ }
+
+ if (attribute?.options) {
+ return (
+ attribute.options.find((o) => o.id === condition.value)?.label ??
+ condition.value.toString()
+ );
+ }
+
+ return condition.value.toString();
+}
+
+function formatSubscriptionDuration(v: number): string {
+ return formatDuration(
+ v >= 12 ? { years: Math.floor(v / 12), months: v % 12 } : { months: v },
+ );
+}
diff --git a/apps/web/lib/rewards/reward-spend-limit.ts b/apps/web/lib/rewards/reward-spend-limit.ts
new file mode 100644
index 0000000000..03eb77aa6f
--- /dev/null
+++ b/apps/web/lib/rewards/reward-spend-limit.ts
@@ -0,0 +1,19 @@
+import { RewardProps } from "@/lib/types";
+import { currencyFormatter } from "@dub/utils";
+
+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" ? "" : `per ${spendLimitInterval}`,
+ };
+}
diff --git a/apps/web/tests/commissions/build-commission-description.test.ts b/apps/web/tests/commissions/build-commission-description.test.ts
new file mode 100644
index 0000000000..b6e2875c0c
--- /dev/null
+++ b/apps/web/tests/commissions/build-commission-description.test.ts
@@ -0,0 +1,434 @@
+import { buildCommissionDescription } from "@/lib/commissions/build-commission-description";
+import { RewardConditions, RewardProps } from "@/lib/types";
+import { describe, expect, test } from "vitest";
+
+function saleReward(
+ overrides: Partial<
+ Pick<
+ RewardProps,
+ | "event"
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "maxDuration"
+ | "description"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
+ >
+ > = {},
+): Pick<
+ RewardProps,
+ | "event"
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "maxDuration"
+ | "description"
+ | "spendLimitAmount"
+ | "spendLimitInterval"
+> {
+ return {
+ event: "sale",
+ type: "percentage",
+ amountInCents: null,
+ amountInPercentage: 10,
+ maxDuration: 12,
+ description: null,
+ spendLimitAmount: null,
+ spendLimitInterval: null,
+ ...overrides,
+ };
+}
+
+describe("buildCommissionDescription", () => {
+ test("formats a base percentage sale reward", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward(),
+ }),
+ ).toBe("Earn 10% per sale for 1 year");
+ });
+
+ test("formats a base flat lead reward", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ event: "lead",
+ type: "flat",
+ amountInCents: 2500,
+ amountInPercentage: null,
+ maxDuration: null,
+ }),
+ }),
+ ).toBe("Earn $25 per lead");
+ });
+
+ test("formats a base click reward", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ event: "click",
+ type: "flat",
+ amountInCents: 50,
+ amountInPercentage: null,
+ maxDuration: null,
+ }),
+ }),
+ ).toBe("Earn $0.50 per click");
+ });
+
+ test("formats a first-sale reward", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ type: "flat",
+ amountInCents: 5000,
+ amountInPercentage: null,
+ maxDuration: 0,
+ }),
+ }),
+ ).toBe("Earn $50 for the first sale");
+ });
+
+ test("formats lifetime duration", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ maxDuration: null }),
+ }),
+ ).toBe("Earn 10% per sale for the customer's lifetime");
+ });
+
+ test("formats multi-month and multi-year durations", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ maxDuration: 6 }),
+ }),
+ ).toBe("Earn 10% per sale for 6 months");
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ maxDuration: 24 }),
+ }),
+ ).toBe("Earn 10% per sale for 2 years");
+ });
+
+ test("ignores editable reward.description", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ description: "Custom marketing copy",
+ }),
+ }),
+ ).toBe("Earn 10% per sale for 1 year");
+ });
+
+ test("never prints an Up to range even when reward had modifiers", () => {
+ const reward = saleReward({
+ amountInPercentage: 10,
+ });
+
+ expect(
+ buildCommissionDescription({
+ reward,
+ }),
+ ).not.toContain("Up to");
+ });
+
+ test("appends matched condition clauses to the applied reward rate", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "flat",
+ amountInCents: 5000,
+ maxDuration: 0,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "prod_premium",
+ label: "Premium Plan",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ // reward already resolved by determinePartnerReward
+ reward: saleReward({
+ type: "flat",
+ amountInCents: 5000,
+ amountInPercentage: null,
+ maxDuration: 0,
+ }),
+ matchedCondition,
+ }),
+ ).toBe("Earn $50 for the first sale if Sale Product ID is Premium Plan");
+ });
+
+ test("formats country names", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "percentage",
+ amountInPercentage: 20,
+ maxDuration: 12,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 20 }),
+ matchedCondition,
+ }),
+ ).toBe("Earn 20% per sale for 1 year if Customer Country is United States");
+ });
+
+ test("formats product label with is operator", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "percentage",
+ amountInPercentage: 20,
+ maxDuration: 12,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "in",
+ value: ["prod_a", "prod_b"],
+ label: "Premium Plan",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 20 }),
+ matchedCondition,
+ }),
+ ).toBe("Earn 20% per sale for 1 year if Sale Product ID is Premium Plan");
+ });
+
+ test("formats currency attribute values", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "flat",
+ amountInCents: 6000,
+ maxDuration: 0,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than_or_equal",
+ value: 20000,
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ type: "flat",
+ amountInCents: 6000,
+ amountInPercentage: null,
+ maxDuration: 0,
+ }),
+ matchedCondition,
+ }),
+ ).toBe(
+ "Earn $60 for the first sale if Sale Amount is greater than or equal to $200.00",
+ );
+ });
+
+ test("formats metadata attributes", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "percentage",
+ amountInPercentage: 15,
+ maxDuration: 12,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "metadata",
+ operator: "equals_to",
+ value: "enterprise",
+ metadataField: "plan",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 15 }),
+ matchedCondition,
+ }),
+ ).toBe('Earn 15% per sale for 1 year if Sale "plan" is enterprise');
+ });
+
+ test("joins AND conditions", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "flat",
+ amountInCents: 5000,
+ maxDuration: null,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "prod_premium",
+ label: "Premium Plan",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ type: "flat",
+ amountInCents: 5000,
+ amountInPercentage: null,
+ maxDuration: null,
+ }),
+ matchedCondition,
+ }),
+ ).toBe(
+ "Earn $50 per sale for the customer's lifetime if Customer Country is United States and Sale Product ID is Premium Plan",
+ );
+ });
+
+ test("joins OR conditions", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "OR",
+ type: "percentage",
+ amountInPercentage: 25,
+ maxDuration: 12,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "CA",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 25 }),
+ matchedCondition,
+ }),
+ ).toBe(
+ "Earn 25% per sale for 1 year if Customer Country is United States or Customer Country is Canada",
+ );
+ });
+
+ test("formats in arrays of country codes", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "percentage",
+ amountInPercentage: 20,
+ maxDuration: 12,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "in",
+ value: ["US", "CA", "GB"],
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 20 }),
+ matchedCondition,
+ }),
+ ).toBe(
+ "Earn 20% per sale for 1 year if Customer Country is one of United States, Canada, United Kingdom",
+ );
+ });
+
+ test("formats sale type option labels", () => {
+ const matchedCondition: RewardConditions = {
+ operator: "AND",
+ type: "percentage",
+ amountInPercentage: 5,
+ maxDuration: 12,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "type",
+ operator: "equals_to",
+ value: "recurring",
+ },
+ ],
+ };
+
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 5 }),
+ matchedCondition,
+ }),
+ ).toBe("Earn 5% per sale for 1 year if Sale Type is recurring");
+ });
+
+ test("appends capped-from/to suffix when earnings are capped", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ amountInPercentage: 20,
+ spendLimitAmount: 10000,
+ spendLimitInterval: "month",
+ }),
+ earnings: 15000,
+ cappedEarnings: 10000,
+ }),
+ ).toBe(
+ "Earn 20% per sale for 1 year, capped from $150 to $100 due to $100 per month spend limit",
+ );
+ });
+
+ test("appends capped-from/to without limit label when spend limit fields missing", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({ amountInPercentage: 20 }),
+ earnings: 5000,
+ cappedEarnings: 3000,
+ }),
+ ).toBe(
+ "Earn 20% per sale for 1 year, capped from $50 to $30 due to spend limit",
+ );
+ });
+
+ test("does not append spend limit suffix when earnings are not capped", () => {
+ expect(
+ buildCommissionDescription({
+ reward: saleReward({
+ amountInPercentage: 20,
+ spendLimitAmount: 10000,
+ spendLimitInterval: "month",
+ }),
+ earnings: 5000,
+ cappedEarnings: 5000,
+ }),
+ ).toBe("Earn 20% per sale for 1 year");
+ });
+});
diff --git a/apps/web/tests/rewards/determine-partner-rewards.test.ts b/apps/web/tests/rewards/determine-partner-rewards.test.ts
index caf0b13411..2a9a72e6de 100644
--- a/apps/web/tests/rewards/determine-partner-rewards.test.ts
+++ b/apps/web/tests/rewards/determine-partner-rewards.test.ts
@@ -97,6 +97,11 @@ describe("determinePartnerRewards", () => {
expect(rewards[0].sale).toEqual({ amount: 20000, quantity: 1 });
expect(rewards[0].reward.type).toBe("flat");
expect(rewards[0].reward.amountInCents).toBe(6000);
+ expect(rewards[0].matchedCondition).toMatchObject({
+ type: "flat",
+ amountInCents: 6000,
+ maxDuration: 0,
+ });
expect(
calculateSaleEarnings({
reward: rewards[0].reward,
@@ -179,5 +184,6 @@ describe("determinePartnerRewards", () => {
expect(rewards).toHaveLength(1);
expect(rewards[0].sale).toEqual({ amount: 20000, quantity: 1 });
+ expect(rewards[0].matchedCondition).toBeNull();
});
});
diff --git a/apps/web/tests/rewards/format-reward-condition.test.ts b/apps/web/tests/rewards/format-reward-condition.test.ts
new file mode 100644
index 0000000000..35de53c45a
--- /dev/null
+++ b/apps/web/tests/rewards/format-reward-condition.test.ts
@@ -0,0 +1,118 @@
+import {
+ formatRewardConditionClause,
+ formatRewardConditionParts,
+} from "@/lib/rewards/format-reward-condition";
+import { describe, expect, test } from "vitest";
+
+describe("formatRewardConditionParts", () => {
+ test("formats country names", () => {
+ expect(
+ formatRewardConditionParts({
+ event: "sale",
+ condition: {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ }),
+ ).toEqual({
+ entityLabel: "Customer",
+ attributeLabel: "Country",
+ operatorLabel: "is",
+ valueLabel: "United States",
+ });
+ });
+
+ test("uses product label with is operator", () => {
+ expect(
+ formatRewardConditionParts({
+ event: "sale",
+ condition: {
+ entity: "sale",
+ attribute: "productId",
+ operator: "in",
+ value: ["prod_a", "prod_b"],
+ label: "Premium Plan",
+ },
+ }),
+ ).toEqual({
+ entityLabel: "Sale",
+ attributeLabel: "Product ID",
+ operatorLabel: "is",
+ valueLabel: "Premium Plan",
+ });
+ });
+
+ test("formats metadata field names", () => {
+ expect(
+ formatRewardConditionParts({
+ event: "sale",
+ condition: {
+ entity: "sale",
+ attribute: "metadata",
+ operator: "equals_to",
+ value: "enterprise",
+ metadataField: "plan",
+ },
+ }),
+ ).toEqual({
+ entityLabel: "Sale",
+ attributeLabel: '"plan"',
+ operatorLabel: "is",
+ valueLabel: "enterprise",
+ });
+ });
+
+ test("formats currency values", () => {
+ expect(
+ formatRewardConditionParts({
+ event: "sale",
+ condition: {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than_or_equal",
+ value: 20000,
+ },
+ }),
+ ).toEqual({
+ entityLabel: "Sale",
+ attributeLabel: "Amount",
+ operatorLabel: "is greater than or equal to",
+ valueLabel: "$200.00",
+ });
+ });
+});
+
+describe("formatRewardConditionClause", () => {
+ test("joins parts with if/and conjunctions", () => {
+ expect(
+ formatRewardConditionClause({
+ event: "sale",
+ operator: "AND",
+ isFirst: true,
+ condition: {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ }),
+ ).toBe("if Customer Country is United States");
+
+ expect(
+ formatRewardConditionClause({
+ event: "sale",
+ operator: "AND",
+ isFirst: false,
+ condition: {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "prod_premium",
+ label: "Premium Plan",
+ },
+ }),
+ ).toBe("and Sale Product ID is Premium Plan");
+ });
+});
diff --git a/apps/web/ui/partners/format-reward-description.ts b/apps/web/ui/partners/format-reward-description.ts
index 6ea2b923d0..270b7921f6 100644
--- a/apps/web/ui/partners/format-reward-description.ts
+++ b/apps/web/ui/partners/format-reward-description.ts
@@ -4,12 +4,12 @@ import {
PARTNER_REFERRAL_PERCENTAGE_TRIGGERS,
PartnerReferralPercentageTrigger,
} from "@/lib/partner-referrals/constants";
+import { getSpendLimitDescriptionParts } from "@/lib/rewards/reward-spend-limit";
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: Pick<
diff --git a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
index 45e2c72b9c..416fb079d7 100644
--- a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
+++ b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
@@ -2,21 +2,10 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { getRewardAmount } from "@/lib/partners/get-reward-amount";
+import { formatRewardConditionParts } from "@/lib/rewards/format-reward-condition";
import { RewardCondition, RewardConditions, RewardProps } from "@/lib/types";
-import {
- CONDITION_OPERATOR_LABELS,
- REWARD_CONDITIONS,
-} from "@/lib/zod/schemas/rewards";
import { InfoTooltip, useScrollProgress } from "@dub/ui";
-import {
- COUNTRIES,
- capitalize,
- cn,
- currencyFormatter,
- formatDateTime,
- pluralize,
-} from "@dub/utils";
-import { formatDuration } from "date-fns";
+import { capitalize, cn, pluralize } from "@dub/utils";
import { useRef } from "react";
interface ProgramRewardModifiersTooltipProps {
@@ -159,67 +148,21 @@ const RewardItem = ({
{conditions && conditions.length > 0 && (
<ul className="ml-1 text-xs font-medium text-neutral-600">
{conditions.map((condition, idx) => {
- const entity = REWARD_CONDITIONS[reward.event].entities.find(
- (e) => e.id === condition.entity,
- );
- const attribute = entity?.attributes?.find(
- (a) => a.id === condition.attribute,
- );
+ const { entityLabel, attributeLabel, operatorLabel, valueLabel } =
+ formatRewardConditionParts({
+ condition,
+ event: reward.event,
+ });
return (
<li key={idx} className="flex items-start gap-1">
<span className="shrink-0 text-lg leading-none">&bull;</span>
<span className="min-w-0">
- {idx === 0 ? "If" : capitalize(operator)}{" "}
- {capitalize(condition.entity)}{" "}
- {(condition.entity === "lead" ||
- condition.entity === "sale") &&
- condition.attribute === "metadata" &&
- condition.metadataField?.trim()
- ? `"${condition.metadataField.trim()}"`
- : capitalize(attribute?.label)}{" "}
- {condition.label
- ? "is" // if custom label is set, use "is" instead of the actual operator to sound more natural
- : CONDITION_OPERATOR_LABELS[condition.operator]}{" "}
- {condition.value &&
- (condition.attribute === "country"
- ? // Country names
- Array.isArray(condition.value)
- ? (condition.value as any[])
- .map((v) => COUNTRIES[v?.toString()] ?? v)
- .join(", ")
- : COUNTRIES[condition.value?.toString()] ??
- condition.value
- : condition.attribute === "subscriptionDurationMonths"
- ? formatSubscriptionDuration(Number(condition.value))
- : condition.attribute === "productId" &&
- condition.label?.trim()
- ? condition.label.trim()
- : // Non-country value(s)
- Array.isArray(condition.value)
- ? // Basic array
- (attribute?.options
- ? (condition.value as string[] | number[]).map(
- (v) =>
- attribute.options?.find((o) => o.id === v)
- ?.label ?? v,
- )
- : condition.value
- ).join(", ")
- : attribute?.type === "currency"
- ? // Currency value
- currencyFormatter(Number(condition.value))
- : attribute?.type === "date"
- ? // Date+time value
- formatDateTime(
- new Date(Number(condition.value)),
- )
- : // Everything else
- attribute?.options
- ? attribute.options.find(
- (o) => o.id === condition.value,
- )?.label ?? condition.value.toString()
- : condition.value.toString())}
+ {idx === 0 ? "If" : capitalize(operator)} {entityLabel}{" "}
+ {attributeLabel} {operatorLabel}
+ {/* Match prior truthiness: hide value when condition.value is
+ falsy (e.g. 0), same as `condition.value && …` before. */}
+ {condition.value ? ` ${valueLabel}` : null}
</span>
</li>
);
@@ -229,9 +172,3 @@ const RewardItem = ({
</div>
);
};
-
-function formatSubscriptionDuration(v: number): string {
- return formatDuration(
- v >= 12 ? { years: Math.floor(v / 12), months: v % 12 } : { months: v },
- );
-}
diff --git a/apps/web/ui/partners/program-reward-spend-limit.tsx b/apps/web/ui/partners/program-reward-spend-limit.tsx
index ab63f9bf75..1f544abf36 100644
--- a/apps/web/ui/partners/program-reward-spend-limit.tsx
+++ b/apps/web/ui/partners/program-reward-spend-limit.tsx
@@ -1,24 +1,6 @@
-import { RewardProps } from "@/lib/types";
-import { currencyFormatter } from "@dub/utils";
+import { getSpendLimitDescriptionParts } from "@/lib/rewards/reward-spend-limit";
import { EventType, 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" ? "" : `per ${spendLimitInterval}`,
- };
-}
-
export function ProgramRewardSpendLimit({
event,
spendLimitAmount,
@@ -45,43 +27,3 @@ export function ProgramRewardSpendLimit({
.filter(Boolean)
.join(" ");
}
-
-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}`;
-}