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 reward modifier evaluation logic

Kiran Kd82fc4a7af85
diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.ts
index 438daade72..4616fa5461 100644
--- a/apps/web/lib/partners/create-partner-commission.ts
+++ b/apps/web/lib/partners/create-partner-commission.ts
@@ -62,6 +62,10 @@ export const createPartnerCommission = async ({
event: event as EventType,
partnerId,
programId,
+ context: {
+ customer: { country: "US" },
+ // sale: { productId: "123" },
+ },
});
}
diff --git a/apps/web/lib/partners/determine-partner-reward.ts b/apps/web/lib/partners/determine-partner-reward.ts
index fae13ef601..6cbe8e9a50 100644
--- a/apps/web/lib/partners/determine-partner-reward.ts
+++ b/apps/web/lib/partners/determine-partner-reward.ts
@@ -1,6 +1,8 @@
import { prisma } from "@dub/prisma";
import { EventType, ProgramEnrollment, Reward } from "@dub/prisma/client";
-import { RewardSchema } from "../zod/schemas/rewards";
+import { z } from "zod";
+import { rewardContextSchema, RewardSchema } from "../zod/schemas/rewards";
+import { evaluateRewardModifier } from "./evaluate-reward-modifier";
const REWARD_EVENT_COLUMN_MAPPING = {
[EventType.click]: "clickReward",
@@ -12,10 +14,12 @@ export const determinePartnerReward = async ({
event,
partnerId,
programId,
+ context,
}: {
event: EventType;
partnerId: string;
programId: string;
+ context?: z.infer<typeof rewardContextSchema>;
}) => {
const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
@@ -37,7 +41,22 @@ export const determinePartnerReward = async ({
const partnerReward = partnerEnrollment[rewardIdColumn];
- if (!partnerReward || partnerReward.amount === 0) {
+ if (!partnerReward) {
+ return null;
+ }
+
+ if (partnerReward.modifiers && context) {
+ const rewardAmount = evaluateRewardModifier({
+ modifier: partnerReward.modifiers,
+ context,
+ });
+
+ if (rewardAmount) {
+ partnerReward.amount = rewardAmount;
+ }
+ }
+
+ if (partnerReward.amount === 0) {
return null;
}
diff --git a/apps/web/lib/partners/evaluate-reward-modifier.ts b/apps/web/lib/partners/evaluate-reward-modifier.ts
new file mode 100644
index 0000000000..d0082123f9
--- /dev/null
+++ b/apps/web/lib/partners/evaluate-reward-modifier.ts
@@ -0,0 +1,127 @@
+import { Prisma } from "@dub/prisma/client";
+import { z } from "zod";
+import {
+ rewardConditionSchema,
+ rewardContextSchema,
+ rewardModifierSchema,
+} from "../zod/schemas/rewards";
+
+type RewardModifier = z.infer<typeof rewardModifierSchema>;
+type RewardContext = z.infer<typeof rewardContextSchema>;
+type RewardCondition = z.infer<typeof rewardConditionSchema>;
+
+export const evaluateRewardModifier = ({
+ modifier,
+ context,
+}: {
+ modifier: Prisma.JsonValue;
+ context: RewardContext;
+}) => {
+ if (!modifier || !context) {
+ return null;
+ }
+
+ const parsedModifier = rewardModifierSchema.parse(modifier);
+
+ const conditionsMet = parsedModifier.conditions.every((condition) => {
+ let fieldValue = undefined;
+
+ if (condition.type === "customer") {
+ fieldValue = context.customer?.[condition.field];
+ } else if (condition.type === "sale") {
+ fieldValue = context.sale?.[condition.field];
+ }
+
+ if (fieldValue === undefined) {
+ return false;
+ }
+
+ return evaluateCondition({
+ condition,
+ fieldValue,
+ });
+ });
+
+ console.log("conditionsMet", conditionsMet);
+
+ return conditionsMet ? parsedModifier.amount : null;
+};
+
+const evaluateCondition = ({
+ condition,
+ fieldValue,
+}: {
+ condition: RewardCondition;
+ fieldValue: string | number | string[] | number[];
+}) => {
+ switch (condition.operator) {
+ case "equals_to":
+ return fieldValue === condition.value;
+ case "not_equals":
+ return fieldValue !== condition.value;
+ case "in":
+ if (Array.isArray(condition.value)) {
+ return (condition.value as (string | number)[]).includes(
+ fieldValue as string | number,
+ );
+ }
+ return false;
+ case "not_in":
+ if (Array.isArray(condition.value)) {
+ return !(condition.value as (string | number)[]).includes(
+ fieldValue as string | number,
+ );
+ }
+ return true;
+ case "starts_with":
+ if (
+ typeof fieldValue === "string" &&
+ typeof condition.value === "string"
+ ) {
+ return fieldValue.startsWith(condition.value);
+ }
+ return false;
+ case "ends_with":
+ if (
+ typeof fieldValue === "string" &&
+ typeof condition.value === "string"
+ ) {
+ return fieldValue.endsWith(condition.value);
+ }
+ return false;
+ case "greater_than":
+ if (
+ typeof fieldValue === "number" &&
+ typeof condition.value === "number"
+ ) {
+ return fieldValue > condition.value;
+ }
+ return false;
+ case "less_than":
+ if (
+ typeof fieldValue === "number" &&
+ typeof condition.value === "number"
+ ) {
+ return fieldValue < condition.value;
+ }
+ return false;
+ case "greater_than_or_equal":
+ if (
+ typeof fieldValue === "number" &&
+ typeof condition.value === "number"
+ ) {
+ return fieldValue >= condition.value;
+ }
+ return false;
+ case "less_than_or_equal":
+ if (
+ typeof fieldValue === "number" &&
+ typeof condition.value === "number"
+ ) {
+ return fieldValue <= condition.value;
+ }
+ return false;
+ default:
+ return false;
+ }
+};
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index fe709b28c1..09bb9d6321 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -79,3 +79,59 @@ export const REWARD_EVENT_COLUMN_MAPPING = Object.freeze({
lead: "leadRewardId",
sale: "saleRewardId",
});
+
+///// Reward modifier schema //////
+
+const operatorTypeSchema = z.enum([
+ "equals_to",
+ "not_equals",
+ "in",
+ "not_in",
+ "starts_with",
+ "ends_with",
+ "greater_than",
+ "less_than",
+ "greater_than_or_equal",
+ "less_than_or_equal",
+]);
+
+const logicOperatorSchema = z.enum(["AND", "OR"]);
+
+const fieldTypeSchema = z.enum(["customer", "sale"]);
+
+const fieldSchema = z.enum(["country", "productId"]);
+
+// A condition can be met if the field value matches the value
+export const rewardConditionSchema = z.object({
+ type: fieldTypeSchema,
+ field: fieldSchema,
+ operator: operatorTypeSchema,
+ value: z.union([
+ z.string(),
+ z.number(),
+ z.array(z.string()),
+ z.array(z.number()),
+ ]),
+});
+
+// A modifier can have multiple conditions that must be met for the modifier to be applied
+export const rewardModifierSchema = z.object({
+ operator: logicOperatorSchema,
+ amount: z.number().int().min(0),
+ conditions: z.array(rewardConditionSchema).min(1),
+});
+
+// The context in which a reward modifier is evaluated
+export const rewardContextSchema = z.object({
+ customer: z
+ .object({
+ country: z.string(),
+ })
+ .optional(),
+
+ sale: z
+ .object({
+ productId: z.string(),
+ })
+ .optional(),
+});
diff --git a/packages/prisma/schema/reward.prisma b/packages/prisma/schema/reward.prisma
index 76a29eb77c..40323c1598 100644
--- a/packages/prisma/schema/reward.prisma
+++ b/packages/prisma/schema/reward.prisma
@@ -20,6 +20,7 @@ model Reward {
maxDuration Int? // in months (0 -> not recurring, null -> infinite)
maxAmount Int? // how much a partner can receive payouts (in cents)
default Boolean @default(false)
+ modifiers Json? @db.Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt