-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathdetermine-partner-reward.ts
More file actions
183 lines (163 loc) · 4.76 KB
/
Copy pathdetermine-partner-reward.ts
File metadata and controls
183 lines (163 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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 {
rewardConditionsArraySchema,
RewardSchema,
} from "../zod/schemas/rewards";
import { aggregatePartnerLinksStats } from "./aggregate-partner-links-stats";
import { evaluateRewardConditions } from "./evaluate-reward-conditions";
import { getRewardAmount } from "./get-reward-amount";
const REWARD_EVENT_COLUMN_MAPPING = {
[EventType.click]: "clickReward",
[EventType.lead]: "leadReward",
[EventType.sale]: "saleReward",
};
interface ProgramEnrollmentWithReward {
partner: { country: string | null };
links: Link[] | null;
totalCommissions: number | bigint;
clickReward?: Reward | null;
leadReward?: Reward | null;
saleReward?: Reward | null;
}
interface ProductReward {
reward: RewardProps;
sale: {
amount: number;
quantity: number;
};
}
export const determinePartnerReward = ({
event,
programEnrollment,
context,
}: {
event: EventType;
programEnrollment: ProgramEnrollmentWithReward;
context?: RewardContext; // additional reward context (e.g. customer.country, sale.productId, etc.)
}) => {
let partnerReward: Reward =
programEnrollment[REWARD_EVENT_COLUMN_MAPPING[event]];
if (!partnerReward) {
return null;
}
// Add the links metrics to the context
const partnerLinksStats = aggregatePartnerLinksStats(programEnrollment.links);
context = {
...context,
partner: {
...context?.partner,
...partnerLinksStats,
totalCommissions: toCentsNumber(programEnrollment.totalCommissions),
country: programEnrollment.partner?.country,
},
};
if (partnerReward.modifiers && context) {
const modifiers = rewardConditionsArraySchema.safeParse(
partnerReward.modifiers,
);
// Parse the conditions before evaluating them
if (modifiers.success) {
const matchedCondition = evaluateRewardConditions({
conditions: modifiers.data,
context,
});
if (matchedCondition) {
partnerReward = {
...partnerReward,
// Override the reward amount, type and max duration with the matched condition
type: matchedCondition.type || partnerReward.type,
amountInCents:
matchedCondition.amountInCents != null
? matchedCondition.amountInCents
: null,
amountInPercentage:
matchedCondition.amountInPercentage != null
? new Prisma.Decimal(matchedCondition.amountInPercentage)
: null,
maxDuration:
matchedCondition.maxDuration !== undefined
? matchedCondition.maxDuration
: partnerReward.maxDuration,
};
}
}
}
const amount = getRewardAmount(serializeReward(partnerReward));
if (amount === 0) {
return null;
}
return RewardSchema.parse(partnerReward);
};
export const determinePartnerRewards = ({
event,
programEnrollment,
context,
amount,
quantity,
}: {
event: EventType;
programEnrollment: ProgramEnrollmentWithReward;
context?: RewardContext; // additional reward context (e.g. customer.country, sale.productId, etc.)
amount: number;
quantity: number;
}): ProductReward[] => {
const rewards: ProductReward[] = [];
const products = context?.sale?.products ?? [];
const modifiers = rewardConditionsArraySchema.safeParse(
programEnrollment.saleReward?.modifiers,
);
const hasProductIdModifier = modifiers.success
? modifiers.data.some((m) =>
m.conditions.some(
(c) => c.entity === "sale" && c.attribute === "productId",
),
)
: false;
// If there are products and a productId modifier,
// 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({
event,
programEnrollment,
context: {
...context,
sale: {
...context?.sale,
productId: product.id,
amount: product.amount,
},
},
});
if (reward) {
rewards.push({
reward,
sale: {
amount: product.amount,
quantity: product.quantity,
},
});
}
}
} else {
const reward = determinePartnerReward({
event,
programEnrollment,
...(context ? { context } : {}),
});
if (reward) {
rewards.push({
reward,
sale: {
amount,
quantity,
},
});
}
}
console.log("Reward context", prettyPrint(context));
return rewards;
};