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.

Implement partner reward determination and migration for commissions

Kiran Kb8bf61644ef3
diff --git a/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
index f3ce65e19f..4811debd92 100644
--- a/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
+++ b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
@@ -1,7 +1,8 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";
-import { calculateSaleEarningsOld } from "@/lib/api/sales/calculate-earnings";
+import { calculateSaleEarnings } from "@/lib/api/sales/calculate-earnings";
import { createId } from "@/lib/api/utils";
+import { determinePartnerReward } from "@/lib/partners/rewards";
import {
getClickEvent,
getLeadEvent,
@@ -217,7 +218,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
}),
};
- const link = await prisma.link.findUnique({
+ const link = await prisma.link.findUniqueOrThrow({
where: {
id: linkId,
},
@@ -266,7 +267,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
]);
// for program links
- if (link?.programId) {
+ if (link.programId && link.partnerId) {
const { program, ...partner } =
await prisma.programEnrollment.findFirstOrThrow({
where: {
@@ -283,11 +284,22 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
},
});
- const saleEarnings = calculateSaleEarningsOld({
- program,
- partner,
- sales: 1,
- saleAmount: saleData.amount,
+ const reward = await determinePartnerReward({
+ event: "sale",
+ partnerId: partner.partnerId,
+ programId: program.id,
+ });
+
+ if (!reward || reward.amount === 0) {
+ return;
+ }
+
+ const earnings = calculateSaleEarnings({
+ reward,
+ sale: {
+ quantity: 1,
+ amount: saleData.amount,
+ },
});
await prisma.commission.create({
@@ -301,7 +313,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
quantity: 1,
type: EventType.sale,
amount: saleData.amount,
- earnings: saleEarnings,
+ earnings,
invoiceId,
},
});
@@ -315,7 +327,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
program,
sale: {
amount: saleData.amount,
- earnings: saleEarnings,
+ earnings,
},
}),
);
diff --git a/apps/web/app/api/stripe/integration/webhook/customer-created.ts b/apps/web/app/api/stripe/integration/webhook/customer-created.ts
index 901d3dbfa0..6f9e16ac21 100644
--- a/apps/web/app/api/stripe/integration/webhook/customer-created.ts
+++ b/apps/web/app/api/stripe/integration/webhook/customer-created.ts
@@ -1,5 +1,6 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { createId } from "@/lib/api/utils";
+import { determinePartnerReward } from "@/lib/partners/rewards";
import { getClickEvent, recordLead } from "@/lib/tinybird";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
@@ -125,20 +126,30 @@ export async function customerCreated(event: Stripe.Event) {
]);
if (link.programId && link.partnerId) {
- // TODO: check if there is a Lead Reward Rule for this partner and if yes, create a lead commission
- // await prisma.commission.create({
- // data: {
- // id: createId({ prefix: "cm_" }),
- // programId: link.programId,
- // linkId: link.id,
- // partnerId: link.partnerId,
- // eventId: leadData.event_id,
- // customerId: customer.id,
- // type: "lead",
- // amount: 0,
- // quantity: 1,
- // },
- // });
+ const reward = await determinePartnerReward({
+ event: "lead",
+ partnerId: link.partnerId,
+ programId: link.programId,
+ });
+
+ if (!reward || reward.amount === 0) {
+ return;
+ }
+
+ await prisma.commission.create({
+ data: {
+ id: createId({ prefix: "cm_" }),
+ programId: link.programId,
+ linkId: link.id,
+ partnerId: link.partnerId,
+ eventId: leadData.event_id,
+ customerId: customer.id,
+ type: "lead",
+ amount: 0,
+ quantity: 1,
+ earnings: reward.amount,
+ },
+ });
}
waitUntil(
diff --git a/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts
index 0f873a81df..22ed5e16fb 100644
--- a/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts
+++ b/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts
@@ -1,7 +1,8 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";
-import { calculateSaleEarningsOld } from "@/lib/api/sales/calculate-earnings";
+import { calculateSaleEarnings } from "@/lib/api/sales/calculate-earnings";
import { createId } from "@/lib/api/utils";
+import { determinePartnerReward } from "@/lib/partners/rewards";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
@@ -132,11 +133,22 @@ export async function invoicePaid(event: Stripe.Event) {
},
});
- const saleEarnings = calculateSaleEarningsOld({
- program,
- partner,
- sales: 1,
- saleAmount: saleData.amount,
+ const reward = await determinePartnerReward({
+ event: "sale",
+ partnerId: partner.partnerId,
+ programId: program.id,
+ });
+
+ if (!reward || reward.amount === 0) {
+ return;
+ }
+
+ const earnings = calculateSaleEarnings({
+ reward,
+ sale: {
+ quantity: 1,
+ amount: saleData.amount,
+ },
});
await prisma.commission.create({
@@ -150,7 +162,7 @@ export async function invoicePaid(event: Stripe.Event) {
quantity: 1,
type: "sale",
amount: saleData.amount,
- earnings: saleEarnings,
+ earnings,
invoiceId,
},
});
@@ -164,7 +176,7 @@ export async function invoicePaid(event: Stripe.Event) {
program,
sale: {
amount: saleData.amount,
- earnings: saleEarnings,
+ earnings,
},
}),
);
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index b9a1b8a913..b8199985cb 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -131,7 +131,7 @@ export const POST = withWorkspaceEdge(
programId: link.programId,
});
- if (!reward) {
+ if (!reward || reward.amount === 0) {
return;
}
@@ -144,8 +144,9 @@ export const POST = withWorkspaceEdge(
eventId,
customerId: customer.id,
type: "lead",
- amount: reward.amount,
+ amount: 0,
quantity: 1,
+ earnings: reward.amount,
},
});
}
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index facb44ad80..8905a86120 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -150,11 +150,11 @@ export const POST = withWorkspaceEdge(
programId: program.id,
});
- if (!reward) {
+ if (!reward || reward.amount === 0) {
return;
}
- const saleEarnings = calculateSaleEarnings({
+ const earnings = calculateSaleEarnings({
reward,
sale: {
quantity: 1,
@@ -174,7 +174,7 @@ export const POST = withWorkspaceEdge(
quantity: 1,
type: "sale",
amount: saleData.amount,
- earnings: saleEarnings,
+ earnings,
invoiceId,
},
}),
@@ -187,7 +187,7 @@ export const POST = withWorkspaceEdge(
program,
sale: {
amount: saleData.amount,
- earnings: saleEarnings,
+ earnings,
},
}),
]);
diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.ts
index 95bd200682..1a1c8329ad 100644
--- a/apps/web/lib/integrations/shopify/create-lead.ts
+++ b/apps/web/lib/integrations/shopify/create-lead.ts
@@ -1,6 +1,7 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { createId } from "@/lib/api/utils";
import { generateRandomName } from "@/lib/names";
+import { determinePartnerReward } from "@/lib/partners/rewards";
import { getClickEvent, recordLead } from "@/lib/tinybird";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
@@ -85,20 +86,30 @@ export async function createShopifyLead({
]);
if (link.programId && link.partnerId) {
- // TODO: check if there is a Lead Reward Rule for this partner and if yes, create a lead commission
- // await prisma.commission.create({
- // data: {
- // id: createId({ prefix: "cm_" }),
- // programId: link.programId,
- // linkId: link.id,
- // partnerId: link.partnerId,
- // eventId: leadData.event_id,
- // customerId: customer.id,
- // type: "lead",
- // amount: 0,
- // quantity: 1,
- // },
- // });
+ const reward = await determinePartnerReward({
+ event: "lead",
+ partnerId: link.partnerId,
+ programId: link.programId,
+ });
+
+ if (!reward || reward.amount === 0) {
+ return;
+ }
+
+ await prisma.commission.create({
+ data: {
+ id: createId({ prefix: "cm_" }),
+ programId: link.programId,
+ linkId: link.id,
+ partnerId: link.partnerId,
+ eventId: leadData.event_id,
+ customerId: customer.id,
+ type: "lead",
+ amount: 0,
+ quantity: 1,
+ earnings: reward.amount,
+ },
+ });
}
waitUntil(
diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.ts
index 0956b63e74..6bd562cf65 100644
--- a/apps/web/lib/integrations/shopify/create-sale.ts
+++ b/apps/web/lib/integrations/shopify/create-sale.ts
@@ -1,7 +1,8 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";
-import { calculateSaleEarningsOld } from "@/lib/api/sales/calculate-earnings";
+import { calculateSaleEarnings } from "@/lib/api/sales/calculate-earnings";
import { createId } from "@/lib/api/utils";
+import { determinePartnerReward } from "@/lib/partners/rewards";
import { recordSale } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
@@ -139,11 +140,22 @@ export async function createShopifySale({
},
});
- const saleEarnings = calculateSaleEarningsOld({
- program,
- partner,
- sales: 1,
- saleAmount: amount,
+ const reward = await determinePartnerReward({
+ event: "sale",
+ partnerId: partner.partnerId,
+ programId: program.id,
+ });
+
+ if (!reward || reward.amount === 0) {
+ return;
+ }
+
+ const earnings = calculateSaleEarnings({
+ reward,
+ sale: {
+ quantity: 1,
+ amount: saleData.amount,
+ },
});
await prisma.commission.create({
@@ -157,7 +169,7 @@ export async function createShopifySale({
quantity: 1,
type: "sale",
amount,
- earnings: saleEarnings,
+ earnings,
invoiceId,
currency,
},
@@ -172,7 +184,7 @@ export async function createShopifySale({
program,
sale: {
amount,
- earnings: saleEarnings,
+ earnings,
},
}),
);
diff --git a/apps/web/lib/partners/rewards.ts b/apps/web/lib/partners/rewards.ts
new file mode 100644
index 0000000000..22bbf8e385
--- /dev/null
+++ b/apps/web/lib/partners/rewards.ts
@@ -0,0 +1,61 @@
+import { prisma } from "@dub/prisma";
+import { EventType } from "@dub/prisma/client";
+
+export const determinePartnerReward = async ({
+ event,
+ partnerId,
+ programId,
+}: {
+ event: EventType;
+ partnerId: string;
+ programId: string;
+}) => {
+ const rewards = await prisma.reward.findMany({
+ where: {
+ event,
+ programId,
+ OR: [
+ // program-wide
+ {
+ partners: {
+ none: {},
+ },
+ },
+ // partner-specific
+ {
+ partners: {
+ some: {
+ programEnrollment: {
+ partnerId,
+ programId,
+ },
+ },
+ },
+ },
+ ],
+ },
+ select: {
+ amount: true,
+ type: true,
+ _count: {
+ select: {
+ partners: true,
+ },
+ },
+ },
+ });
+
+ if (rewards.length === 0) {
+ return;
+ }
+
+ const partnerSpecificReward = rewards.find(
+ (reward) => reward._count.partners === 1,
+ );
+
+ const programWideReward = rewards.find(
+ (reward) => reward._count.partners === 0,
+ );
+
+ return partnerSpecificReward || programWideReward || null;
+};
diff --git a/apps/web/scripts/migrate-commission-attributes.ts b/apps/web/scripts/migrate-commission-attributes.ts
new file mode 100644
index 0000000000..73a929904f
--- /dev/null
+++ b/apps/web/scripts/migrate-commission-attributes.ts
@@ -0,0 +1,37 @@
+import { createId } from "@/lib/api/utils";
+import { prisma } from "@dub/prisma";
+import { EventType } from "@prisma/client";
+import "dotenv-flow/config";
+
+async function main() {
+ const programs = await prisma.program.findMany();
+
+ for (const program of programs) {
+ const reward = await prisma.reward.create({
+ data: {
+ id: createId({ prefix: "rew_" }),
+ programId: program.id,
+ event: EventType.sale,
+ type: program.commissionType,
+ amount: program.commissionAmount,
+ duration: program.commissionDuration,
+ interval: program.commissionInterval,
+ createdAt: program.createdAt,
+ updatedAt: program.updatedAt,
+ },
+ });
+
+ await prisma.program.update({
+ where: {
+ id: reward.programId,
+ },
+ data: {
+ defaultRewardId: reward.id,
+ },
+ });
+
+ console.log(`Migrated commission attributes for program ${program.id}`);
+ }
+}
+
+main();
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 29a14eb643..6dac132c96 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -38,11 +38,13 @@ model Program {
cookieLength Int @default(90)
// Commission details
+ // TODO: Remove this after merging Rewards
commissionAmount Int @default(0)
commissionType CommissionType @default(percentage)
commissionDuration Int?
commissionInterval CommissionInterval?
- defaultRewardId String? // default reward for the program
+
+ defaultRewardId String? // default reward for the program
// Discounts (for dual-sided incentives)
discounts Discount[]