The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
consolidate in createPartnerCommission, maxRewardAmount → maxAmount
Steven Tey33fb9870a468
diff --git a/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/api/stripe/integration/webhook/invoice-paid.tsindex 3805391233..a179441e4c 100644--- a/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts@@ -2,7 +2,6 @@ import { convertCurrency } from "@/lib/analytics/convert-currency";import { includeTags } from "@/lib/api/links/include-tags";import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";-import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";@@ -10,7 +9,6 @@ import { transformSaleEventData } from "@/lib/webhook/transform";import { prisma } from "@dub/prisma";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";-import { differenceInMonths } from "date-fns";import type Stripe from "stripe";// Handle event "invoice.paid"@@ -130,68 +128,26 @@ export async function invoicePaid(event: Stripe.Event) {// for program linksif (link.programId && link.partnerId) {- const reward = await determinePartnerReward({+ const commission = await createPartnerCommission({+ event: "sale",programId: link.programId,partnerId: link.partnerId,- event: "sale",+ linkId: link.id,+ eventId,+ customerId: customer.id,+ amount: saleData.amount,+ quantity: 1,+ invoiceId,+ currency: saleData.currency,});- if (reward) {- let eligibleForCommission = true;-- if (typeof reward.maxDuration === "number") {- // Get the first commission (earliest sale) for this customer-partner pair- const firstCommission = await prisma.commission.findFirst({- where: {- partnerId: link.partnerId,- customerId: customer.id,- type: "sale",- },- orderBy: {- createdAt: "asc",- },- });-- if (firstCommission) {- if (reward.maxDuration === 0) {- eligibleForCommission = false;- } else {- // Calculate months difference between first commission and now- const monthsDifference = differenceInMonths(- new Date(),- firstCommission.createdAt,- );-- if (monthsDifference >= reward.maxDuration) {- eligibleForCommission = false;- }- }- }- }-- if (eligibleForCommission) {- const commission = await createPartnerCommission({- event: "sale",- programId: link.programId,- partnerId: link.partnerId,- linkId: link.id,- eventId,- customerId: customer.id,- amount: saleData.amount,- quantity: 1,- invoiceId,- currency: saleData.currency,- });-- if (commission) {- waitUntil(- notifyPartnerSale({- link,- commission,- }),- );- }- }+ if (commission) {+ waitUntil(+ notifyPartnerSale({+ link,+ commission,+ }),+ );}}diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.tsindex 9c4ac598ac..12cc70f46e 100644--- a/apps/web/app/api/track/sale/route.ts+++ b/apps/web/app/api/track/sale/route.ts@@ -5,7 +5,6 @@ import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";-import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";@@ -19,7 +18,6 @@ import {import { prisma } from "@dub/prisma";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";-import { differenceInMonths } from "date-fns";import { NextResponse } from "next/server";import { z } from "zod";@@ -175,68 +173,26 @@ export const POST = withWorkspace(// for program linksif (link.programId && link.partnerId) {- const reward = await determinePartnerReward({+ const commission = await createPartnerCommission({+ event: "sale",programId: link.programId,partnerId: link.partnerId,- event: "sale",+ linkId: link.id,+ eventId,+ customerId: customer.id,+ amount: saleData.amount,+ quantity: 1,+ invoiceId,+ currency,});- if (reward) {- let eligibleForCommission = true;-- if (typeof reward.maxDuration === "number") {- // Get the first commission (earliest sale) for this customer-partner pair- const firstCommission = await prisma.commission.findFirst({- where: {- partnerId: link.partnerId,- customerId: customer.id,- type: "sale",- },- orderBy: {- createdAt: "asc",- },- });-- if (firstCommission) {- if (reward.maxDuration === 0) {- eligibleForCommission = false;- } else {- // Calculate months difference between first commission and now- const monthsDifference = differenceInMonths(- new Date(),- firstCommission.createdAt,- );-- if (monthsDifference >= reward.maxDuration) {- eligibleForCommission = false;- }- }- }- }-- if (eligibleForCommission) {- const commission = await createPartnerCommission({- event: "sale",- programId: link.programId,- partnerId: link.partnerId,- linkId: link.id,- eventId,- customerId: customer.id,- amount: saleData.amount,- quantity: 1,- invoiceId,- currency,- });-- if (commission) {- waitUntil(- notifyPartnerSale({- link,- commission,- }),- );- }- }+ if (commission) {+ waitUntil(+ notifyPartnerSale({+ link,+ commission,+ }),+ );}}diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.tsindex dbf60c0483..c68cc40e43 100644--- a/apps/web/lib/actions/partners/create-reward.ts+++ b/apps/web/lib/actions/partners/create-reward.ts@@ -18,7 +18,7 @@ export const createRewardAction = authActionClientamount,type,maxDuration,- maxRewardAmount,+ maxAmount,} = parsedInput;const program = await getProgramOrThrow({@@ -26,7 +26,7 @@ export const createRewardAction = authActionClientprogramId,});- if (maxRewardAmount && maxRewardAmount < amount) {+ if (maxAmount && maxAmount < amount) {throw new Error("Max reward amount cannot be less than the reward amount.",);@@ -100,7 +100,7 @@ export const createRewardAction = authActionClienttype,amount,maxDuration,- maxRewardAmount,+ maxAmount,...(programEnrollments && {partners: {createMany: {diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.tsindex a96d32f0fb..27efcfb50b 100644--- a/apps/web/lib/actions/partners/update-reward.ts+++ b/apps/web/lib/actions/partners/update-reward.ts@@ -18,7 +18,7 @@ export const updateRewardAction = authActionClientamount,maxDuration,type,- maxRewardAmount,+ maxAmount,} = parsedInput;await getProgramOrThrow({@@ -26,7 +26,7 @@ export const updateRewardAction = authActionClientprogramId,});- if (maxRewardAmount && maxRewardAmount < amount) {+ if (maxAmount && maxAmount < amount) {throw new Error("Max reward amount cannot be less than the reward amount.",);@@ -88,7 +88,7 @@ export const updateRewardAction = authActionClienttype,amount,maxDuration,- maxRewardAmount,+ maxAmount,...(programEnrollments && {partners: {deleteMany: {},diff --git a/apps/web/lib/partners/calculate-eligible-earnings.ts b/apps/web/lib/partners/calculate-eligible-earnings.tsdeleted file mode 100644index 3653569ee2..0000000000--- a/apps/web/lib/partners/calculate-eligible-earnings.ts+++ /dev/null@@ -1,68 +0,0 @@-import { prisma } from "@dub/prisma";-import { EventType } from "@dub/prisma/client";--export const calculateEligibleEarnings = async ({- event,- partnerId,- programId,- earnings,- maxRewardAmount,-}: {- event: EventType;- partnerId: string;- programId: string;- earnings: number;- maxRewardAmount: number | null;-}) => {- if (!maxRewardAmount) {- return {- allowedEarnings: earnings,- };- }-- const result = await prisma.commission.aggregate({- where: {- earnings: {- gt: 0,- },- programId,- partnerId,- status: {- in: ["pending", "processed", "paid"],- },- type: event,- },- _sum: {- earnings: true,- },- });-- const totalEarnings = result._sum.earnings || 0;-- if (totalEarnings >= maxRewardAmount) {- console.log(- "Total earnings has reached the max reward amount, hence no more earnings are allowed",- );-- return {- allowedEarnings: 0,- };- }-- if (totalEarnings + earnings <= maxRewardAmount) {- console.log(- "Total earnings + earnings <= max reward amount, hence the earnings are allowed",- );-- return {- allowedEarnings: earnings,- };- }-- const remainingAllowance = maxRewardAmount - totalEarnings;- const allowedEarnings = Math.max(0, Math.min(earnings, remainingAllowance));-- return {- allowedEarnings,- };-};diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.tsindex 66a4cb9347..9121a1eb3c 100644--- a/apps/web/lib/partners/create-partner-commission.ts+++ b/apps/web/lib/partners/create-partner-commission.ts@@ -1,9 +1,9 @@import { prisma } from "@dub/prisma";import { EventType } from "@dub/prisma/client";import { log } from "@dub/utils";+import { differenceInMonths } from "date-fns";import { createId } from "../api/create-id";import { calculateSaleEarnings } from "../api/sales/calculate-sale-earnings";-import { calculateEligibleEarnings } from "./calculate-eligible-earnings";import { determinePartnerReward } from "./determine-partner-reward";export const createPartnerCommission = async ({@@ -29,40 +29,95 @@ export const createPartnerCommission = async ({quantity: number;currency?: string;}) => {- try {- const reward = await determinePartnerReward({- event,- programId,- partnerId,+ const reward = await determinePartnerReward({+ event,+ partnerId,+ programId,+ });++ if (!reward) {+ console.log(+ `Partner ${partnerId} has no reward for ${event} event, skipping commission creation...`,+ );+ return;+ }++ // handle rewards with max duration limit+ if (typeof reward.maxDuration === "number") {+ // Get the first commission (earliest sale) for this customer-partner pair+ const firstCommission = await prisma.commission.findFirst({+ where: {+ partnerId,+ customerId,+ type: "sale",+ },+ orderBy: {+ createdAt: "asc",+ },});- if (!reward) {- return;- }+ if (firstCommission) {+ if (reward.maxDuration === 0) {+ console.log(+ `Partner ${partnerId} is only eligible for first-sale commissions, skipping commission creation...`,+ );+ return;+ } else {+ // Calculate months difference between first commission and now+ const monthsDifference = differenceInMonths(+ new Date(),+ firstCommission.createdAt,+ );- const earnings =- event !== "sale"- ? reward.amount * quantity- : calculateSaleEarnings({- reward,- sale: {- quantity,- amount,- },- });+ if (monthsDifference >= reward.maxDuration) {+ console.log(+ `Partner ${partnerId} has reached max duration for ${event} event, skipping commission creation...`,+ );+ return;+ }+ }+ }+ }- const { allowedEarnings } = await calculateEligibleEarnings({- event,- partnerId,- programId,- maxRewardAmount: reward.maxRewardAmount,- earnings,+ // handle rewards with max reward amount limit+ if (reward.maxAmount) {+ const totalRewards = await prisma.commission.aggregate({+ where: {+ earnings: {+ gt: 0,+ },+ programId,+ partnerId,+ status: {+ in: ["pending", "processed", "paid"],+ },+ type: event,+ },+ _sum: {+ earnings: true,+ },});-- if (allowedEarnings === 0) {+ const totalEarnings = totalRewards._sum.earnings || 0;+ if (totalEarnings >= reward.maxAmount) {+ console.log(+ `Partner ${partnerId} has reached max reward amount for ${event} event, skipping commission creation...`,+ );return;}+ }++ const earnings =+ event === "sale"+ ? calculateSaleEarnings({+ reward,+ sale: {+ quantity,+ amount,+ },+ })+ : reward.amount * quantity;+ try {const commission = await prisma.commission.create({data: {id: createId({ prefix: "cm_" }),@@ -76,7 +131,7 @@ export const createPartnerCommission = async ({amount,type: event,currency,- earnings: allowedEarnings,+ earnings,},});@@ -89,5 +144,7 @@ export const createPartnerCommission = async ({type: "errors",mention: true,});++ return;}};diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.tsindex 99f2a25c70..7ca1eb15de 100644--- a/apps/web/lib/zod/schemas/rewards.ts+++ b/apps/web/lib/zod/schemas/rewards.ts@@ -23,7 +23,7 @@ export const RewardSchema = z.object({type: z.nativeEnum(CommissionType),amount: z.number(),maxDuration: z.number().nullish(),- maxRewardAmount: z.number().nullable(),+ maxAmount: z.number().nullish(),partnersCount: z.number().nullish(),});@@ -34,8 +34,8 @@ export const createOrUpdateRewardSchema = z.object({type: z.nativeEnum(CommissionType).default("flat"),amount: z.number().min(0),maxDuration: maxDurationSchema,+ maxAmount: z.number().nullish(),partnerIds: z.array(z.string()).nullish(),- maxRewardAmount: z.number().nullish(),});export const createRewardSchema = createOrUpdateRewardSchema.superRefine(diff --git a/apps/web/ui/partners/add-edit-reward-sheet.tsx b/apps/web/ui/partners/add-edit-reward-sheet.tsxindex 6a28f89187..ef80381fcc 100644--- a/apps/web/ui/partners/add-edit-reward-sheet.tsx+++ b/apps/web/ui/partners/add-edit-reward-sheet.tsx@@ -93,9 +93,7 @@ function RewardSheetContent({ setIsOpen, event, reward }: RewardSheetProps) {: 12,amount: reward?.type === "flat" ? reward.amount / 100 : reward?.amount,partnerIds: null,- maxRewardAmount: reward?.maxRewardAmount- ? reward.maxRewardAmount / 100- : null,+ maxAmount: reward?.maxAmount ? reward.maxAmount / 100 : null,},});@@ -212,7 +210,7 @@ function RewardSheetContent({ setIsOpen, event, reward }: RewardSheetProps) {amount: type === "flat" ? data.amount * 100 : data.amount,maxDuration:Infinity === Number(data.maxDuration) ? null : data.maxDuration,- maxRewardAmount: data.maxRewardAmount ? data.maxRewardAmount * 100 : null,+ maxAmount: data.maxAmount ? data.maxAmount * 100 : null,};if (!reward) {@@ -658,8 +656,8 @@ function RewardLimitSection({setValue: UseFormSetValue<FormData>;errors: FieldErrors<FormData>;}) {- const [maxRewardAmount] = watch(["maxRewardAmount"]);- const [isLimited, setIsLimited] = useState(maxRewardAmount !== null);+ const [maxAmount] = watch(["maxAmount"]);+ const [isLimited, setIsLimited] = useState(maxAmount !== null);return (<div className="flex flex-col gap-4">@@ -671,7 +669,7 @@ function RewardLimitSection({setIsLimited(checked);if (!checked) {- setValue("maxRewardAmount", null);+ setValue("maxAmount", null);}}}/>@@ -700,10 +698,10 @@ function RewardLimitSection({<inputclassName={cn("block w-full rounded-md border-neutral-300 pl-6 pr-12 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",- errors.maxRewardAmount &&+ errors.maxAmount &&"border-red-600 focus:border-red-500 focus:ring-red-600",)}- {...register("maxRewardAmount", {+ {...register("maxAmount", {required: isLimited,valueAsNumber: true,min: 0,diff --git a/packages/prisma/schema/reward.prisma b/packages/prisma/schema/reward.prismaindex da0db89c88..82287764ae 100644--- a/packages/prisma/schema/reward.prisma+++ b/packages/prisma/schema/reward.prisma@@ -7,9 +7,8 @@ model Reward {event EventTypetype CommissionType @default(percentage)amount Int @default(0)- maxDuration Int? // in months (0 -> not recurring, null -> infinite)-- maxRewardAmount Int? // how much a partner can receive payouts+ maxDuration Int? // in months (0 -> not recurring, null -> infinite)+ maxAmount Int? // how much a partner can receive payouts (in cents)createdAt DateTime @default(now())updatedAt DateTime @updatedAt