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.

Add support for the `partner` attribute in reward conditions

Kiran K8627a3922d6d
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index daa1fac35f..af43643454 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -57,19 +57,13 @@ export const updateRewardAction = authActionClient
salePartnerGroup,
...rewardMetadata
} = updatedReward;
+
const isDefaultGroup = [
clickPartnerGroup,
leadPartnerGroup,
salePartnerGroup,
].some((group) => group?.slug === "default");
- console.log({
- isDefaultGroup,
- clickPartnerGroup,
- leadPartnerGroup,
- salePartnerGroup,
- });
-
waitUntil(
Promise.allSettled([
recordAuditLog({
@@ -86,6 +80,7 @@ export const updateRewardAction = authActionClient
},
],
}),
+
// we only cache default group pages for now so we need to invalidate them
...(isDefaultGroup
? [
diff --git a/apps/web/lib/partners/determine-partner-reward.ts b/apps/web/lib/partners/determine-partner-reward.ts
index 259a97ba1e..e3f5f230b4 100644
--- a/apps/web/lib/partners/determine-partner-reward.ts
+++ b/apps/web/lib/partners/determine-partner-reward.ts
@@ -1,5 +1,5 @@
import { prisma } from "@dub/prisma";
-import { EventType, ProgramEnrollment, Reward } from "@dub/prisma/client";
+import { EventType, Link, ProgramEnrollment, Reward } from "@dub/prisma/client";
import { RewardContext } from "../types";
import {
rewardConditionsArraySchema,
@@ -13,6 +13,15 @@ const REWARD_EVENT_COLUMN_MAPPING = {
[EventType.sale]: "saleReward",
};
+interface ProgramEnrollmentWithReward extends ProgramEnrollment {
+ clickReward?: Reward | null;
+ leadReward?: Reward | null;
+ saleReward?: Reward | null;
+ links?:
+ | Pick<Link, "clicks" | "leads" | "conversions" | "saleAmount">[]
+ | null;
+}
+
export const determinePartnerReward = async ({
event,
partnerId,
@@ -26,17 +35,26 @@ export const determinePartnerReward = async ({
}) => {
const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
- const partnerEnrollment = (await prisma.programEnrollment.findUnique({
- where: {
- partnerId_programId: {
- partnerId,
- programId,
+ const partnerEnrollment: ProgramEnrollmentWithReward | null =
+ await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
},
- },
- include: {
- [rewardIdColumn]: true,
- },
- })) as (ProgramEnrollment & { [key: string]: Reward | null }) | null;
+ include: {
+ [rewardIdColumn]: true,
+ links: {
+ select: {
+ clicks: true,
+ leads: true,
+ conversions: true,
+ saleAmount: true,
+ },
+ },
+ },
+ });
if (!partnerEnrollment) {
return null;
@@ -48,6 +66,32 @@ export const determinePartnerReward = async ({
return null;
}
+ // Aggregate the links metrics
+ const partnerLinksStats = partnerEnrollment.links?.reduce(
+ (acc, link) => {
+ acc.totalClicks += link.clicks;
+ acc.totalLeads += link.leads;
+ acc.totalConversions += link.conversions;
+ acc.totalSaleAmount += link.saleAmount;
+ return acc;
+ },
+ {
+ totalClicks: 0,
+ totalLeads: 0,
+ totalConversions: 0,
+ totalSaleAmount: 0,
+ },
+ );
+
+ // Add the links metrics to the context
+ context = {
+ ...context,
+ partner: {
+ ...partnerLinksStats,
+ totalCommissions: partnerEnrollment.totalCommissions,
+ },
+ };
+
if (partnerReward.modifiers && context) {
const modifiers = rewardConditionsArraySchema.safeParse(
partnerReward.modifiers,
@@ -63,6 +107,7 @@ export const determinePartnerReward = async ({
if (matchedCondition) {
partnerReward = {
...partnerReward,
+ // Override the reward amount, type and max duration with the matched condition
amount: matchedCondition.amount,
type: matchedCondition.type || partnerReward.type,
maxDuration:
diff --git a/apps/web/lib/partners/evaluate-reward-conditions.ts b/apps/web/lib/partners/evaluate-reward-conditions.ts
index 605fcc1af4..89c0877be2 100644
--- a/apps/web/lib/partners/evaluate-reward-conditions.ts
+++ b/apps/web/lib/partners/evaluate-reward-conditions.ts
@@ -1,5 +1,6 @@
import {
RewardCondition,
+ RewardConditions,
RewardConditionsArray,
RewardContext,
} from "../types";
@@ -15,6 +16,8 @@ export const evaluateRewardConditions = ({
return null;
}
+ const matchingConditions: RewardConditions[] = [];
+
for (const conditionGroup of conditions) {
// Evaluate each condition in the group
const conditionResults = conditionGroup.conditions.map((condition) => {
@@ -24,6 +27,8 @@ export const evaluateRewardConditions = ({
fieldValue = context.customer?.[condition.attribute];
} else if (condition.entity === "sale") {
fieldValue = context.sale?.[condition.attribute];
+ } else if (condition.entity === "partner") {
+ fieldValue = context.partner?.[condition.attribute];
}
if (fieldValue === undefined) {
@@ -44,13 +49,17 @@ export const evaluateRewardConditions = ({
conditionsMet = conditionResults.some((result) => result);
}
- // If this condition group matches, return it
if (conditionsMet) {
- return conditionGroup;
+ matchingConditions.push(conditionGroup);
}
}
- return null;
+ if (matchingConditions.length === 0) {
+ return null;
+ }
+
+ // Find the best matching condition (highest amount)
+ return matchingConditions.sort((a, b) => b.amount - a.amount)[0];
};
const evaluateCondition = ({
@@ -95,6 +104,14 @@ const evaluateCondition = ({
);
}
return true;
+ case "greater_than":
+ return Number(fieldValue) > Number(condition.value);
+ case "greater_than_or_equal":
+ return Number(fieldValue) >= Number(condition.value);
+ case "less_than":
+ return Number(fieldValue) < Number(condition.value);
+ case "less_than_or_equal":
+ return Number(fieldValue) <= Number(condition.value);
default:
return false;
}
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 3913f29628..ff28b46b10 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -15,13 +15,24 @@ export const COMMISSION_TYPES = [
},
] as const;
-export const CONDITION_ENTITIES = ["customer", "sale"] as const;
+export const CONDITION_ENTITIES = ["customer", "sale", "partner"] as const;
export const CONDITION_CUSTOMER_ATTRIBUTES = ["country"] as const;
+
export const CONDITION_SALE_ATTRIBUTES = ["productId"] as const;
+
+export const CONDITION_PARTNER_ATTRIBUTES = [
+ "totalClicks",
+ "totalLeads",
+ "totalConversions",
+ "totalSaleAmount",
+ "totalCommissions",
+] as const;
+
export const CONDITION_ATTRIBUTES = [
...CONDITION_CUSTOMER_ATTRIBUTES,
...CONDITION_SALE_ATTRIBUTES,
+ ...CONDITION_PARTNER_ATTRIBUTES,
] as const;
export const CONDITION_OPERATORS = [
@@ -31,11 +42,20 @@ export const CONDITION_OPERATORS = [
"ends_with",
"in",
"not_in",
+ "greater_than",
+ "greater_than_or_equal",
+ "less_than",
+ "less_than_or_equal",
] as const;
export const ATTRIBUTE_LABELS = {
- country: "country",
- productId: "product",
+ country: "Country",
+ productId: "Product ID",
+ totalClicks: "Total Clicks",
+ totalLeads: "Total Leads",
+ totalConversions: "Total Conversions",
+ totalSaleAmount: "Total Sale Amount",
+ totalCommissions: "Total Commissions",
} as const;
export const CONDITION_OPERATOR_LABELS = {
@@ -45,6 +65,10 @@ export const CONDITION_OPERATOR_LABELS = {
ends_with: "ends with",
in: "is one of",
not_in: "is not one of",
+ greater_than: "is greater than",
+ greater_than_or_equal: "is greater than or equal to",
+ less_than: "is less than",
+ less_than_or_equal: "is less than or equal to",
} as const;
export const rewardConditionSchema = z.object({
@@ -144,4 +168,14 @@ export const rewardContextSchema = z.object({
productId: z.string().nullish(),
})
.optional(),
+
+ partner: z
+ .object({
+ totalClicks: z.number().nullish(),
+ totalLeads: z.number().nullish(),
+ totalConversions: z.number().nullish(),
+ totalSaleAmount: z.number().nullish(),
+ totalCommissions: z.number().nullish(),
+ })
+ .optional(),
});
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index 8ec30edf06..ef5d317358 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -6,10 +6,12 @@ import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useWorkspace from "@/lib/swr/use-workspace";
import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
import {
+ ATTRIBUTE_LABELS,
CONDITION_ATTRIBUTES,
CONDITION_CUSTOMER_ATTRIBUTES,
CONDITION_OPERATOR_LABELS,
CONDITION_OPERATORS,
+ CONDITION_PARTNER_ATTRIBUTES,
CONDITION_SALE_ATTRIBUTES,
} from "@/lib/zod/schemas/rewards";
import { X } from "@/ui/shared/icons";
@@ -23,6 +25,7 @@ import {
MoneyBills2,
Popover,
User,
+ Users,
} from "@dub/ui";
import { capitalize, cn, COUNTRIES, pluralize, truncate } from "@dub/utils";
import { Command } from "cmdk";
@@ -115,6 +118,7 @@ export function RewardsLogic({
</div>
);
}
+
function ConditionalGroup({
index,
groupCount,
@@ -201,18 +205,17 @@ const ENTITIES = {
sale: {
attributes: CONDITION_SALE_ATTRIBUTES,
},
+ partner: {
+ attributes: CONDITION_PARTNER_ATTRIBUTES,
+ },
} as const;
const EVENT_ENTITIES: Record<EventType, (keyof typeof ENTITIES)[]> = {
- sale: ["sale", "customer"],
- lead: ["customer"],
+ sale: ["sale", "customer", "partner"],
+ lead: ["customer", "partner"],
click: [],
};
-const ATTRIBUTE_LABELS = {
- productId: "Product ID",
-};
-
const formatValue = (
value: string | number | string[] | number[] | undefined,
) => {
@@ -231,6 +234,11 @@ const formatValue = (
);
}
+ // For numeric values, show the number as is
+ if (typeof value === "number") {
+ return value.toString();
+ }
+
return truncate(value.toString(), 20);
};
@@ -253,7 +261,7 @@ function ConditionLogic({
});
const icon = condition.entity
- ? { customer: User, sale: InvoiceDollar }[condition.entity]
+ ? { customer: User, sale: InvoiceDollar, partner: Users }[condition.entity]
: ArrowTurnRight2;
const isArrayValue =
@@ -347,14 +355,23 @@ function ConditionLogic({
...condition,
operator:
value as (typeof CONDITION_OPERATORS)[number],
- // Update value to array / string if needed
+ // Update value to array / string / number if needed
...(["in", "not_in"].includes(value)
? !Array.isArray(condition.value)
? { value: [] }
: null
- : typeof condition.value !== "string"
- ? { value: "" }
- : null),
+ : [
+ "greater_than",
+ "greater_than_or_equal",
+ "less_than",
+ "less_than_or_equal",
+ ].includes(value)
+ ? typeof condition.value !== "number"
+ ? { value: undefined }
+ : null
+ : typeof condition.value !== "string"
+ ? { value: "" }
+ : null),
},
{
shouldDirty: true,
@@ -374,7 +391,9 @@ function ConditionLogic({
invalid={
Array.isArray(condition.value)
? condition.value.filter(Boolean).length === 0
- : !condition.value
+ : typeof condition.value === "number"
+ ? isNaN(condition.value)
+ : !condition.value
}
buttonClassName={cn(
condition.attribute === "productId" && "rounded-r-none",