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.

Support fractional reward percentages (#2998)

Kiran K7f14ed3c9738
diff --git a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
index 7497092b02..57f48b49bc 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
@@ -1,8 +1,10 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { analyticsResponse } from "@/lib/zod/schemas/analytics-response";
import { prisma } from "@dub/prisma";
import { CommissionType, Prisma } from "@dub/prisma/client";
@@ -120,7 +122,7 @@ export async function GET(req: Request) {
quantity: linkClicks,
type: CommissionType.click,
amount: 0,
- earnings: reward.amount * linkClicks,
+ earnings: getRewardAmount(serializeReward(reward)) * linkClicks,
};
})
.filter((c) => c !== null) as Prisma.CommissionCreateManyInput[];
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
index 1c010bf064..bfbc33081e 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
@@ -1,6 +1,5 @@
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { withPartnerProfile } from "@/lib/auth/partner";
-import { sortRewardsByEventOrder } from "@/lib/partners/sort-rewards-by-event-order";
import { ProgramEnrollmentSchema } from "@/lib/zod/schemas/programs";
import { Reward } from "@prisma/client";
import { NextResponse } from "next/server";
@@ -21,13 +20,11 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
},
});
- const rewards = sortRewardsByEventOrder(
- [
- programEnrollment.clickReward,
- programEnrollment.leadReward,
- programEnrollment.saleReward,
- ].filter((r): r is Reward => r !== null),
- );
+ const rewards = [
+ programEnrollment.clickReward,
+ programEnrollment.leadReward,
+ programEnrollment.saleReward,
+ ].filter((r): r is Reward => r !== null);
return NextResponse.json(
ProgramEnrollmentSchema.parse({
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
index 363d38d2f2..7bd5942103 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
@@ -1,5 +1,4 @@
import { withPartnerProfile } from "@/lib/auth/partner";
-import { sortRewardsByEventOrder } from "@/lib/partners/sort-rewards-by-event-order";
import { partnerProfileProgramsQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { ProgramEnrollmentSchema } from "@/lib/zod/schemas/programs";
import { prisma } from "@dub/prisma";
@@ -54,13 +53,11 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
return {
...enrollment,
rewards: includeRewardsDiscounts
- ? sortRewardsByEventOrder(
- [
- enrollment.clickReward,
- enrollment.leadReward,
- enrollment.saleReward,
- ].filter((r): r is Reward => r !== null),
- )
+ ? [
+ enrollment.clickReward,
+ enrollment.leadReward,
+ enrollment.saleReward,
+ ].filter((r): r is Reward => r !== null)
: [],
};
});
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index d47b9c13f1..1016e93443 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -257,7 +257,7 @@ export const { POST } = serve<Payload>(
}
if (error) {
- throw new Error(`Failed to send email notification to partner users.`);
+ throw new Error(error.message);
}
});
diff --git a/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/overview/page-client.tsx b/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/overview/page-client.tsx
index bc34467a9b..d83a817af2 100644
--- a/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/overview/page-client.tsx
+++ b/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/overview/page-client.tsx
@@ -3,7 +3,7 @@
import { onboardProgramAction } from "@/lib/actions/partners/onboard-program";
import { getLinkStructureOptions } from "@/lib/partners/get-link-structure-options";
import useWorkspace from "@/lib/swr/use-workspace";
-import { ProgramData } from "@/lib/types";
+import { ProgramData, RewardProps } from "@/lib/types";
import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";
import { RewardStructure } from "@dub/prisma/client";
import { Button } from "@dub/ui";
@@ -34,29 +34,29 @@ export function PageClient() {
if (!workspaceId) return;
await executeAsync({
- ...data,
workspaceId,
step: "create-program",
});
};
const isValid = useMemo(() => {
- const { name, url, domain, logo, type, amount } = data;
+ const { name, url, domain, logo, type, amountInCents, amountInPercentage } =
+ data;
- if (!name || !url || !domain || !logo || !type || !amount) {
+ const hasAmount =
+ type === "flat" ? amountInCents != null : amountInPercentage != null;
+
+ if (!name || !url || !domain || !logo || !type || !hasAmount) {
return false;
}
return true;
}, [data]);
- const reward = {
+ const reward: Omit<RewardProps, "id"> = {
type: (data.type ?? "flat") as RewardStructure,
- amount: data.amount
- ? data.type === "flat"
- ? data.amount * 100
- : data.amount
- : 0,
+ amountInCents: data.amountInCents != null ? data.amountInCents * 100 : null,
+ amountInPercentage: data.amountInPercentage,
maxDuration: data.maxDuration ?? 0,
event: data.defaultRewardType,
};
diff --git a/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/rewards/form.tsx b/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/rewards/form.tsx
index 2d91a456ce..d4beb83e87 100644
--- a/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/rewards/form.tsx
+++ b/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/rewards/form.tsx
@@ -40,8 +40,15 @@ export function Form() {
formState: { isSubmitting },
} = useFormContext<ProgramData>();
- const [amount, type, defaultRewardType, maxDuration] = watch([
- "amount",
+ const [
+ amountInCents,
+ amountInPercentage,
+ type,
+ defaultRewardType,
+ maxDuration,
+ ] = watch([
+ "amountInCents",
+ "amountInPercentage",
"type",
"defaultRewardType",
"maxDuration",
@@ -74,14 +81,21 @@ export function Form() {
await executeAsync({
...data,
- amount:
- data.amount && data.type === "flat" ? data.amount * 100 : data.amount,
+ amountInCents:
+ data.amountInCents != null && data.type === "flat"
+ ? Math.round(data.amountInCents * 100)
+ : null,
+ amountInPercentage:
+ data.amountInPercentage != null && data.type === "percentage"
+ ? data.amountInPercentage
+ : null,
workspaceId,
step: "configure-reward",
});
};
- const buttonDisabled = !amount || !type || !defaultRewardType;
+ const amount = type === "flat" ? amountInCents : amountInPercentage;
+ const buttonDisabled = amount == null || !type || !defaultRewardType;
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-10">
@@ -244,7 +258,9 @@ export function Form() {
<div className="grid grid-cols-1 gap-6">
<div>
- <h2 className="text-base font-medium text-neutral-900">Payout</h2>
+ <h2 className="text-base font-medium text-neutral-900">
+ Reward amount
+ </h2>
<p className="mt-1 text-sm font-normal text-neutral-600">
Set how much the affiliate will get rewarded
</p>
@@ -253,7 +269,7 @@ export function Form() {
{defaultRewardType === "sale" && (
<div>
<label className="text-sm font-medium text-neutral-800">
- Payout model
+ Reward structure
</label>
<select
{...register("type")}
@@ -267,7 +283,7 @@ export function Form() {
<div>
<label className="text-sm font-medium text-neutral-800">
- Amount {defaultRewardType != "sale" ? "per lead" : ""}
+ Reward amount {defaultRewardType != "sale" ? "per lead" : ""}
</label>
<div className="relative mt-2 rounded-md shadow-sm">
<span className="absolute inset-y-0 left-0 flex items-center pl-3 text-sm text-neutral-400">
@@ -278,13 +294,16 @@ export function Form() {
"block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
type === "flat" ? "pl-6 pr-12" : "pr-7",
)}
- {...register("amount", {
- required: true,
- valueAsNumber: true,
- min: 0,
- max: type === "flat" ? 1000 : 100,
- onChange: handleMoneyInputChange,
- })}
+ {...register(
+ type === "flat" ? "amountInCents" : "amountInPercentage",
+ {
+ required: true,
+ valueAsNumber: true,
+ min: 0,
+ max: type === "flat" ? 1000 : 100,
+ onChange: handleMoneyInputChange,
+ },
+ )}
onKeyDown={handleMoneyKeyDown}
/>
<span className="absolute inset-y-0 right-0 flex items-center pr-3 text-sm text-neutral-400">
diff --git a/apps/web/app/(ee)/app.dub.co/(new-program)/form-wrapper.tsx b/apps/web/app/(ee)/app.dub.co/(new-program)/form-wrapper.tsx
index ca234cc588..5a98920482 100644
--- a/apps/web/app/(ee)/app.dub.co/(new-program)/form-wrapper.tsx
+++ b/apps/web/app/(ee)/app.dub.co/(new-program)/form-wrapper.tsx
@@ -13,7 +13,8 @@ export function FormWrapper({ children }: { children: React.ReactNode }) {
linkStructure: "short",
defaultRewardType: "sale",
type: "percentage",
- amount: null,
+ amountInCents: null,
+ amountInPercentage: null,
maxDuration: 12,
partners: [{ email: "" }],
},
@@ -23,10 +24,14 @@ export function FormWrapper({ children }: { children: React.ReactNode }) {
linkStructure: programOnboarding.linkStructure ?? "short",
defaultRewardType: programOnboarding.defaultRewardType ?? "sale",
type: programOnboarding.type ?? "percentage",
- amount:
- programOnboarding.type === "flat" && programOnboarding.amount
- ? programOnboarding.amount / 100
- : programOnboarding.amount ?? null,
+ amountInCents:
+ programOnboarding.amountInCents != null
+ ? programOnboarding.amountInCents / 100
+ : null,
+ amountInPercentage:
+ programOnboarding.amountInPercentage != null
+ ? programOnboarding.amountInPercentage
+ : null,
partners: programOnboarding.partners?.length
? programOnboarding.partners
: [{ email: "" }],
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts
index 7f5fcb788d..33cdde7673 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts
@@ -1,7 +1,7 @@
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { referralsEmbedToken } from "@/lib/embed/referrals/token-class";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
-import { sortRewardsByEventOrder } from "@/lib/partners/sort-rewards-by-event-order";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { PartnerGroupProps } from "@/lib/types";
import { ReferralsEmbedLinkSchema } from "@/lib/zod/schemas/referrals-embed";
import { prisma } from "@dub/prisma";
@@ -71,11 +71,9 @@ export const getReferralsEmbedData = async (token: string) => {
email: partner.email,
},
links: z.array(ReferralsEmbedLinkSchema).parse(links),
- rewards: sortRewardsByEventOrder(
- [clickReward, leadReward, saleReward].filter(
- (r): r is Reward => r !== null,
- ),
- ),
+ rewards: [clickReward, leadReward, saleReward]
+ .filter((r): r is Reward => r !== null)
+ .map((r) => serializeReward(r)),
discount,
earnings: {
upcoming: commissions.reduce((acc, c) => {
diff --git a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/layout.tsx b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/layout.tsx
index 021aff2a4d..7ab4035ea7 100644
--- a/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/layout.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(apply)/[programSlug]/layout.tsx
@@ -32,7 +32,7 @@ export async function generateMetadata(props: {
title: `${program.name} Affiliate Program`,
description: `Join the ${program.name} affiliate program and ${
program.rewards && program.rewards.length > 0
- ? formatRewardDescription({ reward: program.rewards[0] }).toLowerCase()
+ ? formatRewardDescription(program.rewards[0]).toLowerCase()
: "earn commissions"
} by referring ${program.name} to your friends and followers.`,
image: `${APP_DOMAIN}/api/og/program?slug=${program.slug}`,
diff --git a/apps/web/app/api/og/program/route.tsx b/apps/web/app/api/og/program/route.tsx
index 38be5c370a..b9bc8680ba 100644
--- a/apps/web/app/api/og/program/route.tsx
+++ b/apps/web/app/api/og/program/route.tsx
@@ -1,6 +1,7 @@
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
-import { getGroupRewardsAndDiscount } from "@/lib/partners/get-group-rewards-and-discount";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
+import { Reward } from "@dub/prisma/client";
import { prismaEdge } from "@dub/prisma/edge";
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
@@ -56,8 +57,10 @@ export async function GET(req: NextRequest) {
const logo = program.wordmark || program.logo;
const brandColor = program.brandColor || "#000000";
- const { rewards } = getGroupRewardsAndDiscount(program.groups[0]);
-
+ const group = program.groups[0];
+ const rewards = [group.clickReward, group.leadReward, group.saleReward]
+ .filter((r): r is Reward => r !== null)
+ .map(serializeReward);
const reward = rewards[0];
return new ImageResponse(
@@ -141,7 +144,7 @@ export async function GET(req: NextRequest) {
<div tw="w-full flex items-center rounded-md bg-neutral-100 border border-neutral-200 p-8 text-2xl">
{/* @ts-ignore */}
<InvoiceDollar tw="w-8 h-8 mr-4" />
- {constructRewardAmount(rewards[0])}
+ {constructRewardAmount(reward)}
{reward.event === "sale" && reward.maxDuration === 0
? " for the first sale "
: ` per ${reward.event} `}
diff --git a/apps/web/lib/actions/partners/create-program.ts b/apps/web/lib/actions/partners/create-program.ts
index 5efaed006f..533adc9311 100644
--- a/apps/web/lib/actions/partners/create-program.ts
+++ b/apps/web/lib/actions/partners/create-program.ts
@@ -42,7 +42,8 @@ export const createProgram = async ({
url,
defaultRewardType,
type,
- amount,
+ amountInCents,
+ amountInPercentage,
maxDuration,
partners,
supportEmail,
@@ -107,12 +108,16 @@ export const createProgram = async ({
? new Date()
: null,
...(type &&
- amount && {
+ (amountInCents != null || amountInPercentage != null) && {
rewards: {
create: {
id: createId({ prefix: "rw_" }),
type,
- amount,
+ amountInCents: type === "flat" ? amountInCents : null,
+ amountInPercentage:
+ type === "percentage" && amountInPercentage != null
+ ? amountInPercentage
+ : null,
maxDuration,
event: defaultRewardType,
},
diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.ts
index 1fa1e30600..d424ce9685 100644
--- a/apps/web/lib/actions/partners/create-reward.ts
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -4,6 +4,8 @@ import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { createId } from "@/lib/api/create-id";
import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { validateReward } from "@/lib/api/rewards/validate-reward";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import {
createRewardSchema,
@@ -20,8 +22,9 @@ export const createRewardAction = authActionClient
const { workspace, user } = ctx;
const {
event,
- amount,
type,
+ amountInCents,
+ amountInPercentage,
maxDuration,
description,
modifiers,
@@ -50,6 +53,8 @@ export const createRewardAction = authActionClient
);
}
+ validateReward(parsedInput);
+
const reward = await prisma.$transaction(async (tx) => {
const reward = await tx.reward.create({
data: {
@@ -57,10 +62,18 @@ export const createRewardAction = authActionClient
programId,
event,
type,
- amount,
maxDuration,
description: description || null,
modifiers: modifiers || Prisma.DbNull,
+ ...(type === "flat"
+ ? {
+ amountInCents,
+ amountInPercentage: null,
+ }
+ : {
+ amountInCents: null,
+ amountInPercentage: new Prisma.Decimal(amountInPercentage!),
+ }),
},
});
@@ -96,7 +109,7 @@ export const createRewardAction = authActionClient
{
type: "reward",
id: reward.id,
- metadata: reward,
+ metadata: serializeReward(reward),
},
],
}),
diff --git a/apps/web/lib/actions/partners/generate-lander.ts b/apps/web/lib/actions/partners/generate-lander.ts
index 9c4d4829fa..49ea7ab710 100644
--- a/apps/web/lib/actions/partners/generate-lander.ts
+++ b/apps/web/lib/actions/partners/generate-lander.ts
@@ -1,7 +1,7 @@
"use server";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { getGroupRewardsAndDiscount } from "@/lib/partners/get-group-rewards-and-discount";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import {
programLanderSchema,
@@ -11,6 +11,7 @@ import { formatDiscountDescription } from "@/ui/partners/format-discount-descrip
import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { anthropic } from "@ai-sdk/anthropic";
import { prisma } from "@dub/prisma";
+import { Reward } from "@dub/prisma/client";
import FireCrawlApp, {
ErrorResponse,
ScrapeResponse,
@@ -52,7 +53,11 @@ export const generateLanderAction = authActionClient
},
});
- const { rewards, discount } = getGroupRewardsAndDiscount(program.groups[0]);
+ const group = program.groups[0];
+ const discount = group.discount;
+ const rewards = [group.clickReward, group.leadReward, group.saleReward]
+ .filter((r): r is Reward => r !== null)
+ .map(serializeReward);
const firecrawl = new FireCrawlApp({
apiKey: process.env.FIRECRAWL_API_KEY,
@@ -107,9 +112,9 @@ export const generateLanderAction = authActionClient
// Program details
`\n\nProgram details:` +
`\n\nName: ${program.name}\n` +
- `\nAffiliate rewards: ${rewards.map((reward) => formatRewardDescription({ reward })).join(", ")}` +
+ `\nAffiliate rewards: ${rewards.map((reward) => formatRewardDescription(reward)).join(", ")}` +
(discount
- ? `\nDiscounts for referred users: ${formatDiscountDescription({ discount })}`
+ ? `\nDiscounts for referred users: ${formatDiscountDescription(discount)}`
: "") +
// Existing page
(landerData
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index 67f3f226c1..9c44a63e96 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -3,6 +3,8 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getRewardOrThrow } from "@/lib/api/partners/get-reward-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { validateReward } from "@/lib/api/rewards/validate-reward";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { updateRewardSchema } from "@/lib/zod/schemas/rewards";
import { prisma } from "@dub/prisma";
@@ -15,12 +17,19 @@ export const updateRewardAction = authActionClient
.schema(updateRewardSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
- const { rewardId, amount, maxDuration, type, description, modifiers } =
- parsedInput;
+ const {
+ type,
+ amountInCents,
+ amountInPercentage,
+ maxDuration,
+ description,
+ modifiers,
+ rewardId,
+ } = parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
- await getRewardOrThrow({
+ const reward = await getRewardOrThrow({
rewardId,
programId,
});
@@ -33,16 +42,29 @@ export const updateRewardAction = authActionClient
);
}
+ validateReward({
+ ...parsedInput,
+ event: reward.event,
+ });
+
const updatedReward = await prisma.reward.update({
where: {
id: rewardId,
},
data: {
type,
- amount,
maxDuration,
description: description || null,
modifiers: modifiers === null ? Prisma.DbNull : modifiers,
+ ...(type === "flat"
+ ? {
+ amountInCents,
+ amountInPercentage: null,
+ }
+ : {
+ amountInCents: null,
+ amountInPercentage: new Prisma.Decimal(amountInPercentage!),
+ }),
},
include: {
program: true,
@@ -78,7 +100,7 @@ export const updateRewardAction = authActionClient
{
type: "reward",
id: rewardId,
- metadata: rewardMetadata,
+ metadata: serializeReward(rewardMetadata),
},
],
}),
diff --git a/apps/web/lib/api/audit-logs/schemas.ts b/apps/web/lib/api/audit-logs/schemas.ts
index 18cc25758a..c0ba1f9af0 100644
--- a/apps/web/lib/api/audit-logs/schemas.ts
+++ b/apps/web/lib/api/audit-logs/schemas.ts
@@ -116,7 +116,8 @@ export const auditLogTarget = z.union([
metadata: RewardSchema.pick({
event: true,
type: true,
- amount: true,
+ amountInCents: true,
+ amountInPercentage: true,
maxDuration: true,
}),
}),
diff --git a/apps/web/lib/api/partners/backfill-link-commissions.ts b/apps/web/lib/api/partners/backfill-link-commissions.ts
index 61f74d39d9..1c6622e2fe 100644
--- a/apps/web/lib/api/partners/backfill-link-commissions.ts
+++ b/apps/web/lib/api/partners/backfill-link-commissions.ts
@@ -2,6 +2,7 @@ import { getEvents } from "@/lib/analytics/get-events";
import { createId } from "@/lib/api/create-id";
import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { SaleEvent } from "@/lib/types";
import { prisma } from "@dub/prisma";
import { EventType } from "@dub/prisma/client";
@@ -41,7 +42,7 @@ export const backfillLinkCommissions = async (link: {
const { program } = programEnrollment;
- if (!reward || reward.amount === 0) {
+ if (!reward || getRewardAmount(reward) === 0) {
console.log("No reward.", reward);
return;
}
diff --git a/apps/web/lib/api/partners/get-partner-invite-rewards-and-bounties.ts b/apps/web/lib/api/partners/get-partner-invite-rewards-and-bounties.ts
index a23dd598df..33fec2d675 100644
--- a/apps/web/lib/api/partners/get-partner-invite-rewards-and-bounties.ts
+++ b/apps/web/lib/api/partners/get-partner-invite-rewards-and-bounties.ts
@@ -1,9 +1,9 @@
-import { sortRewardsByEventOrder } from "@/lib/partners/sort-rewards-by-event-order";
import { formatDiscountDescription } from "@/ui/partners/format-discount-description";
import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { prisma } from "@dub/prisma";
-import { BountyType, EventType } from "@dub/prisma/client";
+import { BountyType, EventType, Reward } from "@dub/prisma/client";
import { getGroupOrThrow } from "../groups/get-group-or-throw";
+import { serializeReward } from "./serialize-reward";
const REWARD_ICONS: Record<EventType, string> = {
click: "https://assets.dub.co/email-assets/icons/cursor-rays.png",
@@ -74,18 +74,16 @@ export async function getPartnerInviteRewardsAndBounties({
return {
rewards: [
- ...sortRewardsByEventOrder([
- ...(group.clickReward ? [group.clickReward] : []),
- ...(group.leadReward ? [group.leadReward] : []),
- ...(group.saleReward ? [group.saleReward] : []),
- ]).map((reward) => ({
- label: formatRewardDescription({ reward }),
- icon: REWARD_ICONS[reward.event],
- })),
+ ...[group.clickReward, group.leadReward, group.saleReward]
+ .filter((r): r is Reward => r !== null)
+ .map((reward) => ({
+ label: formatRewardDescription(serializeReward(reward)),
+ icon: REWARD_ICONS[reward.event],
+ })),
...(group.discount
? [
{
- label: formatDiscountDescription({ discount: group.discount }),
+ label: formatDiscountDescription(group.discount),
icon: "https://assets.dub.co/email-assets/icons/gift.png",
},
]
diff --git a/apps/web/lib/api/partners/serialize-reward.ts b/apps/web/lib/api/partners/serialize-reward.ts
new file mode 100644
index 0000000000..5ac1ae1045
--- /dev/null
+++ b/apps/web/lib/api/partners/serialize-reward.ts
@@ -0,0 +1,14 @@
+import type { Reward } from "@dub/prisma/client";
+import "server-only";
+
+// Convert Prisma.Decimal object to number
+// should not send Prisma.Decimal to the client
+export function serializeReward(reward: Reward) {
+ return {
+ ...reward,
+ amountInPercentage:
+ reward.amountInPercentage != null
+ ? Number(reward.amountInPercentage)
+ : null,
+ };
+}
diff --git a/apps/web/lib/api/rewards/validate-reward.ts b/apps/web/lib/api/rewards/validate-reward.ts
new file mode 100644
index 0000000000..73eddc8c04
--- /dev/null
+++ b/apps/web/lib/api/rewards/validate-reward.ts
@@ -0,0 +1,128 @@
+import {
+ createOrUpdateRewardSchema,
+ rewardConditionsArraySchema,
+} from "@/lib/zod/schemas/rewards";
+import { z } from "zod";
+import { DubApiError } from "../errors";
+
+export function validateReward(
+ reward: Partial<z.infer<typeof createOrUpdateRewardSchema>>,
+) {
+ if (reward.event === "click" || reward.event === "lead") {
+ if (reward.type === "percentage") {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Percentage rewards are not allowed for click and lead events.",
+ });
+ }
+
+ if (reward.amountInCents == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInCents must be provided for click and lead events.",
+ });
+ }
+
+ if (reward.amountInPercentage != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInPercentage is not allowed for click and lead events.",
+ });
+ }
+ }
+
+ if (reward.event === "sale") {
+ if (reward.amountInCents != null && reward.amountInPercentage != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "amountInCents and amountInPercentage cannot be used together.",
+ });
+ }
+
+ if (reward.amountInCents == null && reward.amountInPercentage == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInCents or amountInPercentage must be provided.",
+ });
+ }
+
+ if (reward.type === "flat" && reward.amountInCents == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInCents must be provided when type is 'flat'.",
+ });
+ }
+
+ if (reward.type === "percentage" && reward.amountInPercentage == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "amountInPercentage must be provided when type is 'percentage'.",
+ });
+ }
+ }
+
+ if (reward.modifiers != null) {
+ if (reward.event === "click") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Modifiers are only allowed for lead and sale events.",
+ });
+ }
+
+ const parsedModifiers = rewardConditionsArraySchema.safeParse(
+ reward.modifiers,
+ );
+
+ if (parsedModifiers.success) {
+ parsedModifiers.data.forEach((modifier, index) => {
+ if (modifier.type == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Modifier ${index + 1}: type must be provided.`,
+ });
+ }
+
+ if (
+ modifier.amountInCents == null &&
+ modifier.amountInPercentage == null
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Modifier ${index + 1}: amountInCents or amountInPercentage must be provided.`,
+ });
+ }
+
+ if (
+ modifier.amountInCents != null &&
+ modifier.amountInPercentage != null
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Modifier ${index + 1}: amountInCents and amountInPercentage cannot be used together.`,
+ });
+ }
+
+ if (modifier.type === "flat") {
+ if (modifier.amountInCents == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Modifier ${index + 1}: amountInCents must be provided when type is 'flat'.`,
+ });
+ }
+ }
+
+ if (modifier.type === "percentage") {
+ if (modifier.amountInPercentage == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Modifier ${index + 1}: amountInPercentage must be provided when type is 'percentage'.`,
+ });
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/apps/web/lib/api/sales/calculate-sale-earnings.ts b/apps/web/lib/api/sales/calculate-sale-earnings.ts
index 530937900c..6436fab380 100644
--- a/apps/web/lib/api/sales/calculate-sale-earnings.ts
+++ b/apps/web/lib/api/sales/calculate-sale-earnings.ts
@@ -1,3 +1,4 @@
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { RewardProps } from "@/lib/types";
import { Commission } from "@dub/prisma/client";
@@ -8,20 +9,20 @@ export const calculateSaleEarnings = ({
reward,
sale,
}: {
- reward: Pick<RewardProps, "amount" | "type">;
+ reward: Pick<RewardProps, "type" | "amountInCents" | "amountInPercentage">;
sale: Pick<Commission, "quantity" | "amount">;
}) => {
if (!reward) {
return 0;
}
- if (reward.type === "percentage") {
- return sale.amount * (reward.amount / 100);
- }
+ const amount = getRewardAmount(reward);
if (reward.type === "flat") {
- return sale.quantity * reward.amount;
+ return sale.quantity * amount;
+ } else if (reward.type === "percentage") {
+ return sale.amount * (amount / 100);
}
- throw new Error("Invalid reward type");
+ return 0;
};
diff --git a/apps/web/lib/api/sales/construct-discount-amount.ts b/apps/web/lib/api/sales/construct-discount-amount.ts
new file mode 100644
index 0000000000..7d5c64a34f
--- /dev/null
+++ b/apps/web/lib/api/sales/construct-discount-amount.ts
@@ -0,0 +1,12 @@
+import { DiscountProps } from "@/lib/types";
+import { currencyFormatter } from "@dub/utils";
+
+export const constructDiscountAmount = (
+ discount: Pick<DiscountProps, "amount" | "type">,
+) => {
+ return discount.type === "percentage"
+ ? `${discount.amount}%`
+ : currencyFormatter(discount.amount / 100, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+};
diff --git a/apps/web/lib/api/sales/construct-reward-amount.ts b/apps/web/lib/api/sales/construct-reward-amount.ts
index 289dc1afb8..5c16cd0031 100644
--- a/apps/web/lib/api/sales/construct-reward-amount.ts
+++ b/apps/web/lib/api/sales/construct-reward-amount.ts
@@ -1,9 +1,17 @@
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { RewardProps } from "@/lib/types";
import { rewardConditionsArraySchema } from "@/lib/zod/schemas/rewards";
import { currencyFormatter } from "@dub/utils";
export const constructRewardAmount = (
- reward: Pick<RewardProps, "amount" | "type" | "maxDuration" | "modifiers">,
+ reward: Pick<
+ RewardProps,
+ | "type"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "maxDuration"
+ | "modifiers"
+ >,
) => {
// If there are modifiers, we need to check if they match the primary reward
if (reward.modifiers) {
@@ -27,14 +35,24 @@ export const constructRewardAmount = (
// If the type AND maxDuration matches the primary, show a range
if (matchPrimary) {
+ const amount = getRewardAmount(reward);
+
const min = Math.min(
- reward.amount,
- ...modifiers.map((modifier) => modifier.amount),
+ amount,
+ ...modifiers.map((modifier) =>
+ reward.type === "flat"
+ ? modifier.amountInCents ?? Infinity
+ : modifier.amountInPercentage ?? Infinity,
+ ),
);
const max = Math.max(
- reward.amount,
- ...modifiers.map((modifier) => modifier.amount),
+ amount,
+ ...modifiers.map((modifier) =>
+ reward.type === "flat"
+ ? modifier.amountInCents ?? 0
+ : modifier.amountInPercentage ?? 0,
+ ),
);
if (min !== max) {
@@ -54,8 +72,8 @@ export const constructRewardAmount = (
// 1. There are no modifiers OR
// 2. type AND timelines doesn't match the primary reward
return reward.type === "percentage"
- ? `${reward.amount}%`
- : currencyFormatter(reward.amount / 100, {
+ ? `${reward.amountInPercentage}%`
+ : currencyFormatter((reward.amountInCents ?? 0) / 100, {
trailingZeroDisplay: "stripIfInteger",
});
};
diff --git a/apps/web/lib/fetchers/get-program.ts b/apps/web/lib/fetchers/get-program.ts
index d7cb8a8151..263fbf0e1d 100644
--- a/apps/web/lib/fetchers/get-program.ts
+++ b/apps/web/lib/fetchers/get-program.ts
@@ -1,6 +1,7 @@
import { prisma } from "@dub/prisma";
-import { Program } from "@prisma/client";
+import { Program, Reward } from "@prisma/client";
import { cache } from "react";
+import { serializeReward } from "../api/partners/serialize-reward";
import { DiscountProps, GroupWithFormDataProps, RewardProps } from "../types";
type Result = Program & {
@@ -54,11 +55,9 @@ export const getProgram = cache(
const group = groups[0];
- const rewards = [
- group.clickReward,
- group.leadReward,
- group.saleReward,
- ].filter(Boolean);
+ const rewards = [group.clickReward, group.leadReward, group.saleReward]
+ .filter((r) => r !== null)
+ .map((r) => serializeReward(r as Reward));
const discount = group.discount;
diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.ts
index bf3333bf66..705638079c 100644
--- a/apps/web/lib/partners/create-partner-commission.ts
+++ b/apps/web/lib/partners/create-partner-commission.ts
@@ -24,6 +24,7 @@ import { sendWorkspaceWebhook } from "../webhook/publish";
import { CommissionWebhookSchema } from "../zod/schemas/commissions";
import { aggregatePartnerLinksStats } from "./aggregate-partner-links-stats";
import { determinePartnerReward } from "./determine-partner-reward";
+import { getRewardAmount } from "./get-reward-amount";
export type CreatePartnerCommissionProps = {
event: CommissionType;
@@ -111,7 +112,7 @@ export const createPartnerCommission = async ({
// for click events, it's super simple – just multiply the reward amount by the quantity
if (event === "click") {
- earnings = reward.amount * quantity;
+ earnings = getRewardAmount(reward) * quantity;
// for lead and sale events, we need to check if this partner-customer combination was recorded already (for deduplication)
// for sale rewards specifically, we also need to check:
@@ -140,6 +141,7 @@ export const createPartnerCommission = async ({
console.log(
`Partner ${partnerId} has already been issued a lead reward for this customer ${customerId}, skipping commission creation...`,
);
+
return {
commission: null,
webhookPartner: constructWebhookPartner(programEnrollment),
@@ -221,7 +223,7 @@ export const createPartnerCommission = async ({
// for lead events, we just multiply the reward amount by the quantity
if (event === "lead") {
- earnings = reward.amount * quantity;
+ earnings = getRewardAmount(reward) * quantity;
// for sale events, we need to calculate the earnings based on the sale amount
} else {
earnings = calculateSaleEarnings({
diff --git a/apps/web/lib/partners/determine-partner-reward.ts b/apps/web/lib/partners/determine-partner-reward.ts
index 902be1e794..e2f31820b1 100644
--- a/apps/web/lib/partners/determine-partner-reward.ts
+++ b/apps/web/lib/partners/determine-partner-reward.ts
@@ -1,4 +1,5 @@
-import { EventType, Link, Reward } from "@dub/prisma/client";
+import { EventType, Link, Prisma, Reward } from "@dub/prisma/client";
+import { serializeReward } from "../api/partners/serialize-reward";
import { RewardContext } from "../types";
import {
rewardConditionsArraySchema,
@@ -6,6 +7,7 @@ import {
} 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",
@@ -67,8 +69,15 @@ export const determinePartnerReward = ({
partnerReward = {
...partnerReward,
// Override the reward amount, type and max duration with the matched condition
- amount: matchedCondition.amount,
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
@@ -78,7 +87,9 @@ export const determinePartnerReward = ({
}
}
- if (partnerReward.amount === 0) {
+ const amount = getRewardAmount(serializeReward(partnerReward));
+
+ if (amount === 0) {
return null;
}
diff --git a/apps/web/lib/partners/evaluate-reward-conditions.ts b/apps/web/lib/partners/evaluate-reward-conditions.ts
index 89c0877be2..6822736917 100644
--- a/apps/web/lib/partners/evaluate-reward-conditions.ts
+++ b/apps/web/lib/partners/evaluate-reward-conditions.ts
@@ -4,6 +4,7 @@ import {
RewardConditionsArray,
RewardContext,
} from "../types";
+import { getRewardAmount } from "./get-reward-amount";
export const evaluateRewardConditions = ({
conditions,
@@ -59,7 +60,19 @@ export const evaluateRewardConditions = ({
}
// Find the best matching condition (highest amount)
- return matchingConditions.sort((a, b) => b.amount - a.amount)[0];
+ return matchingConditions.sort(
+ (a, b) =>
+ getRewardAmount({
+ type: b.type!,
+ amountInCents: b.amountInCents,
+ amountInPercentage: b.amountInPercentage,
+ }) -
+ getRewardAmount({
+ type: a.type!,
+ amountInCents: a.amountInCents,
+ amountInPercentage: a.amountInPercentage,
+ }),
+ )[0];
};
const evaluateCondition = ({
diff --git a/apps/web/lib/partners/get-group-rewards-and-discount.ts b/apps/web/lib/partners/get-group-rewards-and-discount.ts
index 192c621d48..eb6fde431e 100644
--- a/apps/web/lib/partners/get-group-rewards-and-discount.ts
+++ b/apps/web/lib/partners/get-group-rewards-and-discount.ts
@@ -1,22 +1,18 @@
import { GroupProps, RewardProps } from "@/lib/types";
-import { sortRewardsByEventOrder } from "./sort-rewards-by-event-order";
-/**
- * Determines the rewards and discount for the partner group
- */
-export function getGroupRewardsAndDiscount(
- group: Pick<
- GroupProps,
- "clickReward" | "saleReward" | "leadReward" | "discount"
- >,
-) {
- const rewards = sortRewardsByEventOrder(
- [
- group.clickReward ?? null,
- group.saleReward ?? null,
- group.leadReward ?? null,
- ].filter((r): r is RewardProps => r !== null),
+// Determines the rewards and discount for the partner group
+export function getGroupRewardsAndDiscount({
+ clickReward,
+ saleReward,
+ leadReward,
+ discount,
+}: Pick<GroupProps, "clickReward" | "saleReward" | "leadReward" | "discount">) {
+ const rewards = [clickReward, saleReward, leadReward].filter(
+ (r): r is RewardProps => r !== null,
);
- return { rewards, discount: group.discount ?? null };
+ return {
+ rewards,
+ discount: discount ?? null,
+ };
}
diff --git a/apps/web/lib/partners/get-reward-amount.ts b/apps/web/lib/partners/get-reward-amount.ts
new file mode 100644
index 0000000000..d1cf4976a0
--- /dev/null
+++ b/apps/web/lib/partners/get-reward-amount.ts
@@ -0,0 +1,11 @@
+import { RewardProps } from "../types";
+
+export const getRewardAmount = ({
+ type,
+ amountInCents,
+ amountInPercentage,
+}: Pick<RewardProps, "type" | "amountInCents" | "amountInPercentage">) => {
+ const amount = type === "flat" ? amountInCents : amountInPercentage;
+
+ return amount === null || amount === undefined ? 0 : amount;
+};
diff --git a/apps/web/lib/rewardful/import-campaigns.ts b/apps/web/lib/rewardful/import-campaigns.ts
index 730482494e..0db4ff44e0 100644
--- a/apps/web/lib/rewardful/import-campaigns.ts
+++ b/apps/web/lib/rewardful/import-campaigns.ts
@@ -1,9 +1,12 @@
import { RESOURCE_COLORS } from "@/ui/colors";
import { prisma } from "@dub/prisma";
-import { EventType, RewardStructure } from "@dub/prisma/client";
+import { EventType, Prisma, RewardStructure } from "@dub/prisma/client";
import { randomValue } from "@dub/utils";
import { differenceInSeconds } from "date-fns";
import { createId } from "../api/create-id";
+
+import { serializeReward } from "../api/partners/serialize-reward";
+import { getRewardAmount } from "../partners/get-reward-amount";
import { RewardfulApi } from "./api";
import { rewardfulImporter } from "./importer";
import { RewardfulImportPayload } from "./types";
@@ -85,15 +88,18 @@ export async function importCampaigns(payload: RewardfulImportPayload) {
reward_type === "amount"
? RewardStructure.flat
: RewardStructure.percentage,
- amount:
- reward_type === "amount"
- ? commission_amount_cents
- : commission_percent,
+ ...(reward_type === "amount"
+ ? {
+ amountInCents: commission_amount_cents,
+ }
+ : {
+ amountInPercentage: new Prisma.Decimal(commission_percent),
+ }),
},
});
console.log(
- `Since group was newly created, also created reward ${createdReward.id} with amount ${createdReward.amount} and type ${createdReward.type}`,
+ `Since group was newly created, also created reward ${createdReward.id} with amount ${getRewardAmount(serializeReward(createdReward))} and type ${createdReward.type}`,
);
}
diff --git a/apps/web/lib/zod/schemas/program-onboarding.ts b/apps/web/lib/zod/schemas/program-onboarding.ts
index 6ca2e6f797..cb2d0cfb69 100644
--- a/apps/web/lib/zod/schemas/program-onboarding.ts
+++ b/apps/web/lib/zod/schemas/program-onboarding.ts
@@ -3,6 +3,10 @@ import { PartnerLinkStructure, RewardStructure } from "@dub/prisma/client";
import { z } from "zod";
import { maxDurationSchema } from "./misc";
import { updateProgramSchema } from "./programs";
+import {
+ FLAT_REWARD_AMOUNT_SCHEMA,
+ PERCENTAGE_REWARD_AMOUNT_SCHEMA,
+} from "./rewards";
import { parseUrlSchema } from "./utils";
// Getting started
@@ -19,7 +23,8 @@ export const programInfoSchema = z.object({
export const programRewardSchema = z.object({
defaultRewardType: z.enum(["lead", "sale"]).default("lead"),
type: z.nativeEnum(RewardStructure).nullish(),
- amount: z.number().min(0).nullish(),
+ amountInCents: FLAT_REWARD_AMOUNT_SCHEMA.nullish(),
+ amountInPercentage: PERCENTAGE_REWARD_AMOUNT_SCHEMA.nullish(),
maxDuration: maxDurationSchema,
});
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index e10284c33c..263827700a 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -129,10 +129,26 @@ export const rewardConditionSchema = z.object({
.describe("Product name used for display purposes in the UI."),
});
+export const PERCENTAGE_REWARD_AMOUNT_SCHEMA = z
+ .number()
+ .min(0, { message: "Reward percentage amount cannot be less than 0%" })
+ .max(99.99, {
+ message: "Reward percentage amount cannot be greater than 99.99%",
+ });
+
+export const FLAT_REWARD_AMOUNT_SCHEMA = z
+ .number()
+ .int()
+ .min(0, { message: "Reward amount cannot be less than $0" })
+ .max(999_999_99, {
+ message: "Reward amount cannot be greater than $999,999.99",
+ });
+
export const rewardConditionsSchema = z.object({
operator: z.enum(["AND", "OR"]).default("AND"),
conditions: z.array(rewardConditionSchema).min(1),
- amount: z.number().int().min(0),
+ amountInCents: FLAT_REWARD_AMOUNT_SCHEMA.optional(),
+ amountInPercentage: PERCENTAGE_REWARD_AMOUNT_SCHEMA.optional(),
type: z.nativeEnum(RewardStructure).optional(),
maxDuration: maxDurationSchema,
});
@@ -141,12 +157,19 @@ export const rewardConditionsArraySchema = z
.array(rewardConditionsSchema)
.min(1);
+const decimalToNumber = z
+ .any()
+ .transform((val) => (val != null && val !== "" ? Number(val) : null))
+ .nullable()
+ .optional();
+
export const RewardSchema = z.object({
id: z.string(),
event: z.nativeEnum(EventType),
description: z.string().nullish(),
type: z.nativeEnum(RewardStructure),
- amount: z.number(),
+ amountInCents: z.number().int().nullable().optional(),
+ amountInPercentage: decimalToNumber,
maxDuration: z.number().nullish(),
modifiers: z.any().nullish(), // TODO: Fix this
});
@@ -155,7 +178,8 @@ export const createOrUpdateRewardSchema = z.object({
workspaceId: z.string(),
event: z.nativeEnum(EventType),
type: z.nativeEnum(RewardStructure).default(RewardStructure.flat),
- amount: z.number().min(0),
+ amountInCents: FLAT_REWARD_AMOUNT_SCHEMA.optional(),
+ amountInPercentage: PERCENTAGE_REWARD_AMOUNT_SCHEMA.optional(),
maxDuration: maxDurationSchema,
modifiers: rewardConditionsArraySchema.nullish(),
description: z.string().max(100).nullish(),
diff --git a/apps/web/scripts/migrations/backfill-click-commissions.ts b/apps/web/scripts/migrations/backfill-click-commissions.ts
index ce1bc95996..c6ff3f848e 100644
--- a/apps/web/scripts/migrations/backfill-click-commissions.ts
+++ b/apps/web/scripts/migrations/backfill-click-commissions.ts
@@ -1,5 +1,6 @@
import { createId } from "@/lib/api/create-id";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { prisma } from "@dub/prisma";
import "dotenv-flow/config";
import { getAnalytics } from "../../lib/analytics/get-analytics";
@@ -67,7 +68,7 @@ async function main() {
type: "click",
amount: 0,
quantity,
- earnings: reward.amount * quantity,
+ earnings: getRewardAmount(reward) * quantity,
status: payoutId ? "paid" : "pending",
createdAt: new Date(start),
updatedAt: new Date(start),
diff --git a/apps/web/scripts/migrations/migrate-reward-amounts.ts b/apps/web/scripts/migrations/migrate-reward-amounts.ts
new file mode 100644
index 0000000000..4ecb0daa0b
--- /dev/null
+++ b/apps/web/scripts/migrations/migrate-reward-amounts.ts
@@ -0,0 +1,96 @@
+import { RewardConditions } from "@/lib/types";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@prisma/client";
+import "dotenv-flow/config";
+
+// One time script to migrate rewards from the old "amount" field to the new "amountInCents" and "amountInPercentage" fields.
+async function main() {
+ let totalMigrated = 0;
+ const pageSize = 50;
+ while (true) {
+ const rewards = await prisma.reward.findMany({
+ where: {
+ amountInCents: null,
+ amountInPercentage: null,
+ },
+ select: {
+ id: true,
+ type: true,
+ amount: true,
+ modifiers: true,
+ },
+ take: pageSize,
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+
+ if (rewards.length === 0) {
+ console.log("No more rewards to migrate.");
+ break;
+ }
+
+ for (const reward of rewards) {
+ const amount = reward.amount ?? 0;
+ let amountInCents: number | null = null;
+ let amountInPercentage: number | null = null;
+
+ // Migrate main amount field
+ if (reward.type === "flat") {
+ amountInCents = amount;
+ } else if (reward.type === "percentage") {
+ amountInPercentage = amount;
+ }
+
+ // Migrate modifiers
+ let updatedModifiers = reward.modifiers;
+ if (reward.modifiers && Array.isArray(reward.modifiers)) {
+ updatedModifiers = reward.modifiers.map(
+ (modifier: RewardConditions & { amount?: number }) => {
+ if (modifier.amount != null) {
+ const modifierType = modifier.type || reward.type;
+ const newModifier = { ...modifier };
+
+ if (modifierType === "flat") {
+ newModifier.amountInCents = modifier.amount;
+ } else if (modifierType === "percentage") {
+ newModifier.amountInPercentage = modifier.amount;
+ }
+
+ // Some of the old modifiers don't have a type, so we add it from the parent reward type
+ if (!newModifier.type) {
+ newModifier.type = modifierType;
+ }
+ return newModifier;
+ }
+
+ return modifier;
+ },
+ );
+ }
+
+ console.log(
+ `Migrating reward ${reward.id}: type=${reward.type} amount=${amount} -> amountInCents=${amountInCents}, amountInPercentage=${amountInPercentage}`,
+ );
+
+ await prisma.reward.update({
+ where: {
+ id: reward.id,
+ },
+ data: {
+ amountInCents,
+ amountInPercentage,
+ modifiers: updatedModifiers ?? Prisma.DbNull,
+ },
+ });
+
+ totalMigrated++;
+ }
+
+ console.log(`Migrated batch of ${rewards.length} rewards`);
+ }
+
+ console.log(`Total rewards migrated: ${totalMigrated}`);
+}
+
+main();
diff --git a/apps/web/scripts/testimonial/update-commissions.ts b/apps/web/scripts/testimonial/update-commissions.ts
index 26b140ede0..3b651b97d6 100644
--- a/apps/web/scripts/testimonial/update-commissions.ts
+++ b/apps/web/scripts/testimonial/update-commissions.ts
@@ -1,4 +1,5 @@
import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
+import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import "dotenv-flow/config";
@@ -25,7 +26,7 @@ async function main() {
commissions.map(async (commission) => {
// Recalculate the earnings based on the new amount
const earnings = calculateSaleEarnings({
- reward,
+ reward: serializeReward(reward),
sale: {
amount: commission.amount,
quantity: commission.quantity,
diff --git a/apps/web/tests/rewards/reward-conditions.test.ts b/apps/web/tests/rewards/reward-conditions.test.ts
index 4a14637b01..f644dad294 100644
--- a/apps/web/tests/rewards/reward-conditions.test.ts
+++ b/apps/web/tests/rewards/reward-conditions.test.ts
@@ -8,7 +8,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -47,7 +48,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -86,7 +88,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -127,7 +130,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "OR" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -166,7 +170,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "OR" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -205,7 +210,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "OR" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -246,7 +252,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1000,
+ type: "flat" as const,
+ amountInCents: 1000,
conditions: [
{
entity: "customer" as const,
@@ -258,7 +265,8 @@ describe("evaluateRewardConditions", () => {
},
{
operator: "AND" as const,
- amount: 2000,
+ type: "flat" as const,
+ amountInCents: 2000,
conditions: [
{
entity: "customer" as const,
@@ -270,7 +278,8 @@ describe("evaluateRewardConditions", () => {
},
{
operator: "AND" as const,
- amount: 3000,
+ type: "flat" as const,
+ amountInCents: 3000,
conditions: [
{
entity: "customer" as const,
@@ -300,7 +309,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1000,
+ type: "flat" as const,
+ amountInCents: 1000,
conditions: [
{
entity: "customer" as const,
@@ -312,7 +322,8 @@ describe("evaluateRewardConditions", () => {
},
{
operator: "AND" as const,
- amount: 2000,
+ type: "flat" as const,
+ amountInCents: 2000,
conditions: [
{
entity: "customer" as const,
@@ -345,7 +356,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -375,7 +386,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -407,7 +418,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -437,7 +448,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -469,7 +480,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -499,7 +510,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -531,7 +542,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -561,7 +572,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -593,7 +604,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "sale" as const,
@@ -623,7 +634,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "sale" as const,
@@ -655,7 +666,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "sale" as const,
@@ -685,7 +696,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "sale" as const,
@@ -717,7 +728,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -747,7 +758,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -777,7 +788,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -809,7 +820,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -839,7 +850,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -869,7 +880,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -901,7 +912,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -931,7 +942,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -961,7 +972,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -993,7 +1004,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1023,7 +1034,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1053,7 +1064,7 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1103,7 +1114,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -1127,7 +1139,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -1157,7 +1170,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1187,7 +1201,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1217,7 +1232,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1247,7 +1263,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1277,7 +1294,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1309,7 +1327,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -1355,7 +1374,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "customer" as const,
@@ -1401,7 +1421,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "OR" as const,
- amount: 5000,
+ type: "flat" as const,
+ amountInCents: 5000,
conditions: [
{
entity: "partner" as const,
@@ -1445,7 +1466,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1000,
+ type: "flat" as const,
+ amountInCents: 1000,
conditions: [
{
entity: "partner" as const,
@@ -1457,7 +1479,8 @@ describe("evaluateRewardConditions", () => {
},
{
operator: "AND" as const,
- amount: 3000, // Highest amount
+ type: "flat" as const,
+ amountInCents: 3000, // Highest amount
conditions: [
{
entity: "partner" as const,
@@ -1469,7 +1492,8 @@ describe("evaluateRewardConditions", () => {
},
{
operator: "AND" as const,
- amount: 2000,
+ type: "flat" as const,
+ amountInCents: 2000,
conditions: [
{
entity: "partner" as const,
@@ -1503,7 +1527,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1000,
+ type: "flat" as const,
+ amountInCents: 1000,
conditions: [
{
entity: "partner" as const,
@@ -1515,7 +1540,8 @@ describe("evaluateRewardConditions", () => {
},
{
operator: "AND" as const,
- amount: 2000,
+ type: "flat" as const,
+ amountInCents: 2000,
conditions: [
{
entity: "partner" as const,
@@ -1545,7 +1571,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1500,
+ type: "flat" as const,
+ amountInCents: 1500,
conditions: [
{
entity: "partner" as const,
@@ -1575,7 +1602,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1000,
+ type: "flat" as const,
+ amountInCents: 1000,
conditions: [
{
entity: "partner" as const,
@@ -1605,7 +1633,8 @@ describe("evaluateRewardConditions", () => {
const conditions = [
{
operator: "AND" as const,
- amount: 1000,
+ type: "flat" as const,
+ amountInCents: 1000,
conditions: [
{
entity: "partner" as const,
diff --git a/apps/web/tests/tracks/track-lead.test.ts b/apps/web/tests/tracks/track-lead.test.ts
index 1168ad651d..53921ac851 100644
--- a/apps/web/tests/tracks/track-lead.test.ts
+++ b/apps/web/tests/tracks/track-lead.test.ts
@@ -291,7 +291,7 @@ describe("POST /track/lead", async () => {
await verifyCommission({
http,
customerExternalId: customer.externalId,
- expectedEarnings: E2E_LEAD_REWARD.modifiers[0].amount,
+ expectedEarnings: E2E_LEAD_REWARD.modifiers[0].amountInCents,
});
});
});
diff --git a/apps/web/tests/tracks/track-sale.test.ts b/apps/web/tests/tracks/track-sale.test.ts
index 73eaf59ef4..562036082f 100644
--- a/apps/web/tests/tracks/track-sale.test.ts
+++ b/apps/web/tests/tracks/track-sale.test.ts
@@ -134,13 +134,13 @@ describe("POST /track/sale", async () => {
http,
regularInvoiceId,
response1.data.sale?.amount!,
- E2E_SALE_REWARD.amount,
+ E2E_SALE_REWARD.amountInCents,
);
await verifyCommission(
http,
premiumInvoiceId,
response2.data.sale?.amount!,
- E2E_SALE_REWARD.modifiers[0].amount,
+ E2E_SALE_REWARD.modifiers[0].amountInCents,
);
});
@@ -315,14 +315,14 @@ describe("POST /track/sale", async () => {
http,
smallSaleInvoiceId,
response1.data.sale?.amount!,
- E2E_SALE_REWARD.amount,
+ E2E_SALE_REWARD.amountInCents,
);
await verifyCommission(
http,
largeSaleInvoiceId,
response2.data.sale?.amount!,
- E2E_SALE_REWARD.modifiers[1].amount,
+ E2E_SALE_REWARD.modifiers[1].amountInCents,
);
});
});
diff --git a/apps/web/tests/utils/resource.ts b/apps/web/tests/utils/resource.ts
index 7b6256eb5f..67221a2128 100644
--- a/apps/web/tests/utils/resource.ts
+++ b/apps/web/tests/utils/resource.ts
@@ -41,11 +41,13 @@ export const E2E_CUSTOMER_EXTERNAL_ID_2 = "cus_pqc8qRtofpu6ZqvutyNDGAU2";
export const E2E_SALE_REWARD = {
id: "rw_1JYPP77NNDG6TVPAJDKNZREQN",
event: "sale",
- amount: 1000,
+ type: "flat",
+ amountInCents: 1000,
modifiers: [
{
operator: "AND",
- amount: 3000,
+ type: "flat",
+ amountInCents: 3000,
conditions: [
{
entity: "sale",
@@ -57,7 +59,8 @@ export const E2E_SALE_REWARD = {
},
{
operator: "AND",
- amount: 5000,
+ type: "flat",
+ amountInCents: 5000,
conditions: [
{
entity: "sale",
@@ -72,11 +75,12 @@ export const E2E_SALE_REWARD = {
export const E2E_LEAD_REWARD = {
id: "rw_1K82ESAT4YPY0STR20GKXZ7DR",
event: "lead",
- amount: 1000,
+ type: "flat",
+ amountInCents: 1000,
modifiers: [
{
type: "flat",
- amount: 200,
+ amountInCents: 200,
operator: "AND",
conditions: [
{
diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
index 26196e79f9..ffbecab249 100644
--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
@@ -3,7 +3,7 @@
import { createDiscountAction } from "@/lib/actions/partners/create-discount";
import { deleteDiscountAction } from "@/lib/actions/partners/delete-discount";
import { updateDiscountAction } from "@/lib/actions/partners/update-discount";
-import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { constructDiscountAmount } from "@/lib/api/sales/construct-discount-amount";
import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
import useGroup from "@/lib/swr/use-group";
import useProgram from "@/lib/swr/use-program";
@@ -417,7 +417,7 @@ function DiscountSheetContent({
<InlineBadgePopover
text={
amount
- ? constructRewardAmount({
+ ? constructDiscountAmount({
amount: type === "flat" ? amount * 100 : amount,
type,
})
diff --git a/apps/web/ui/partners/format-discount-description.ts b/apps/web/ui/partners/format-discount-description.ts
index d7d9138b87..16e44813eb 100644
--- a/apps/web/ui/partners/format-discount-description.ts
+++ b/apps/web/ui/partners/format-discount-description.ts
@@ -1,20 +1,18 @@
-import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { constructDiscountAmount } from "@/lib/api/sales/construct-discount-amount";
import { DiscountProps } from "@/lib/types";
import { pluralize } from "@dub/utils";
-export function formatDiscountDescription({
- discount,
-}: {
+export function formatDiscountDescription(
discount: Pick<
DiscountProps,
"amount" | "type" | "maxDuration" | "description"
- >;
-}): string {
+ >,
+): string {
if (discount.description) {
return discount.description;
}
- const discountAmount = constructRewardAmount(discount);
+ const discountAmount = constructDiscountAmount(discount);
const parts: string[] = [];
diff --git a/apps/web/ui/partners/format-reward-description.ts b/apps/web/ui/partners/format-reward-description.ts
index e3d41b7e76..b03a16d91d 100644
--- a/apps/web/ui/partners/format-reward-description.ts
+++ b/apps/web/ui/partners/format-reward-description.ts
@@ -1,14 +1,7 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { RewardProps } from "@/lib/types";
-export function formatRewardDescription({
- reward,
-}: {
- reward: Pick<
- RewardProps,
- "description" | "amount" | "type" | "event" | "maxDuration"
- >;
-}): string {
+export function formatRewardDescription(reward: RewardProps) {
if (reward.description) {
return reward.description;
}
diff --git a/apps/web/ui/partners/lander/blocks/earnings-calculator-block.tsx b/apps/web/ui/partners/lander/blocks/earnings-calculator-block.tsx
index 47455bfc9e..f052440cbe 100644
--- a/apps/web/ui/partners/lander/blocks/earnings-calculator-block.tsx
+++ b/apps/web/ui/partners/lander/blocks/earnings-calculator-block.tsx
@@ -1,6 +1,6 @@
"use client";
-import { sortRewardsByEventOrder } from "@/lib/partners/sort-rewards-by-event-order";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { ProgramProps } from "@/lib/types";
import { programLanderEarningsCalculatorBlockSchema } from "@/lib/zod/schemas/program-lander";
import { InvoiceDollar } from "@dub/ui";
@@ -25,12 +25,10 @@ export function EarningsCalculatorBlock({
if (!program.rewards?.length) return null;
- const reward = sortRewardsByEventOrder(program.rewards, [
- "sale",
- "lead",
- "click",
- ])[0];
- const rewardAmount = reward.amount ?? 0;
+ const reward = program.rewards.find((r) => r.event === "sale");
+ if (!reward) return null;
+
+ const rewardAmount = getRewardAmount(reward);
const revenue = value * ((block.data.productPrice || 30_00) / 100);
return (
@@ -71,7 +69,7 @@ export function EarningsCalculatorBlock({
<div className="mt-2 flex items-center gap-1">
<InvoiceDollar className="size-3.5 text-neutral-400" />
<p className="text-xs text-neutral-500">
- {formatRewardDescription({ reward })}
+ {formatRewardDescription(reward)}
</p>
</div>
</div>
diff --git a/apps/web/ui/partners/partner-info-cards.tsx b/apps/web/ui/partners/partner-info-cards.tsx
index 9f9fc25fec..fd5683df28 100644
--- a/apps/web/ui/partners/partner-info-cards.tsx
+++ b/apps/web/ui/partners/partner-info-cards.tsx
@@ -1,4 +1,3 @@
-import { sortRewardsByEventOrder } from "@/lib/partners/sort-rewards-by-event-order";
import useGroup from "@/lib/swr/use-group";
import useWorkspace from "@/lib/swr/use-workspace";
import {
@@ -268,13 +267,11 @@ export function PartnerInfoCards({
group.saleReward ||
group.discount ? (
<ProgramRewardList
- rewards={sortRewardsByEventOrder(
- [
- group.clickReward,
- group.leadReward,
- group.saleReward,
- ].filter((r): r is RewardProps => r !== null),
- )}
+ rewards={[
+ group.clickReward,
+ group.leadReward,
+ group.saleReward,
+ ].filter((r): r is RewardProps => r !== null)}
discount={group.discount}
variant="plain"
className="text-content-subtle gap-2 text-xs leading-4"
diff --git a/apps/web/ui/partners/program-reward-description.tsx b/apps/web/ui/partners/program-reward-description.tsx
index fb2f1fe58d..ef475bc7e7 100644
--- a/apps/web/ui/partners/program-reward-description.tsx
+++ b/apps/web/ui/partners/program-reward-description.tsx
@@ -1,3 +1,4 @@
+import { constructDiscountAmount } from "@/lib/api/sales/construct-discount-amount";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { DiscountProps, RewardProps } from "@/lib/types";
import { cn } from "@dub/utils";
@@ -10,10 +11,7 @@ export function ProgramRewardDescription({
periodClassName,
showModifiersTooltip = true,
}: {
- reward?: Pick<
- RewardProps,
- "amount" | "type" | "event" | "maxDuration" | "description" | "modifiers"
- > | null;
+ reward?: Omit<RewardProps, "id"> | null;
discount?: DiscountProps | null;
amountClassName?: string;
periodClassName?: string;
@@ -70,7 +68,7 @@ export function ProgramRewardDescription({
{" "}
New users get{" "}
<strong className={cn("font-semibold", amountClassName)}>
- {constructRewardAmount(discount)}
+ {constructDiscountAmount(discount)}
</strong>{" "}
off{" "}
{discount.maxDuration === null ? (
diff --git a/apps/web/ui/partners/program-reward-list.tsx b/apps/web/ui/partners/program-reward-list.tsx
index 8c42db0585..093e6d7046 100644
--- a/apps/web/ui/partners/program-reward-list.tsx
+++ b/apps/web/ui/partners/program-reward-list.tsx
@@ -1,9 +1,11 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { DiscountProps, RewardProps } from "@/lib/types";
import { Gift, Icon } from "@dub/ui";
import { cn } from "@dub/utils";
import { PropsWithChildren } from "react";
import { REWARD_EVENTS } from "./constants";
+import { formatDiscountDescription } from "./format-discount-description";
import { ProgramRewardModifiersTooltip } from "./program-reward-modifiers-tooltip";
export function ProgramRewardList({
@@ -21,7 +23,7 @@ export function ProgramRewardList({
iconClassName?: string;
showModifiersTooltip?: boolean;
}) {
- const sortedFilteredRewards = rewards.filter((r) => r.amount >= 0);
+ const sortedFilteredRewards = rewards.filter((r) => getRewardAmount(r) >= 0);
return (
<ul
@@ -75,23 +77,10 @@ export function ProgramRewardList({
)}
</Item>
))}
+
{discount && (
<Item icon={Gift} iconClassName={iconClassName}>
- {discount.description || (
- <>
- {" "}
- New users get {constructRewardAmount(discount)} off{" "}
- {discount.maxDuration === null
- ? "for their lifetime"
- : discount.maxDuration === 0
- ? "for their first purchase"
- : discount.maxDuration === 1
- ? "for their first month"
- : discount.maxDuration && discount.maxDuration > 1
- ? `for ${discount.maxDuration} months`
- : null}
- </>
- )}
+ {formatDiscountDescription(discount)}
</Item>
)}
</ul>
diff --git a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
index d5c24e0ac3..3b327f9979 100644
--- a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
+++ b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
@@ -1,6 +1,7 @@
"use client";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { RewardProps } from "@/lib/types";
import {
ATTRIBUTE_LABELS,
@@ -25,10 +26,7 @@ const REWARD_MODIFIER_LABELS = {
};
type ProgramRewardModifiersTooltipProps = {
- reward?: Pick<
- RewardProps,
- "amount" | "type" | "event" | "maxDuration" | "modifiers"
- > | null;
+ reward?: Omit<RewardProps, "id"> | null;
};
export function ProgramRewardModifiersTooltip({
@@ -53,7 +51,7 @@ export function ProgramRewardModifiersTooltipContent({
if (!reward?.modifiers?.length) return null;
- const showBaseReward = reward.amount !== 0;
+ const showBaseReward = getRewardAmount(reward) !== 0;
return (
<div className="relative">
@@ -75,9 +73,10 @@ export function ProgramRewardModifiersTooltipContent({
<RewardItem
reward={{
event: reward.event,
- amount: modifier.amount,
type:
modifier.type === undefined ? reward.type : modifier.type, // fallback to primary
+ amountInCents: modifier.amountInCents,
+ amountInPercentage: modifier.amountInPercentage,
maxDuration:
modifier.maxDuration === undefined
? reward.maxDuration
@@ -103,7 +102,7 @@ const RewardItem = ({
conditions,
operator = "AND",
}: {
- reward: Pick<RewardProps, "amount" | "type" | "event" | "maxDuration">;
+ reward: Omit<RewardProps, "id">;
conditions?: z.infer<
typeof rewardConditionsArraySchema
>[number]["conditions"];
diff --git a/apps/web/ui/partners/program-rewards-panel.tsx b/apps/web/ui/partners/program-rewards-panel.tsx
index 361fa350f1..c1c07c8b6b 100644
--- a/apps/web/ui/partners/program-rewards-panel.tsx
+++ b/apps/web/ui/partners/program-rewards-panel.tsx
@@ -1,11 +1,13 @@
"use client";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { DiscountProps, RewardProps } from "@/lib/types";
import { Gift, Tooltip } from "@dub/ui";
import { HelpCircle } from "lucide-react";
import { memo } from "react";
import { REWARD_EVENTS } from "./constants";
+import { formatDiscountDescription } from "./format-discount-description";
import { ProgramRewardModifiersTooltipContent } from "./program-reward-modifiers-tooltip";
interface ProgramRewardsPanelProps {
@@ -28,7 +30,9 @@ function CustomRewardModifiersTooltip({ reward }: { reward: RewardProps }) {
export const ProgramRewardsPanel = memo(
({ rewards, discount }: ProgramRewardsPanelProps) => {
- const sortedFilteredRewards = rewards.filter((r) => r.amount >= 0);
+ const sortedFilteredRewards = rewards.filter(
+ (r) => getRewardAmount(r) >= 0,
+ );
const rewardItems = [
...sortedFilteredRewards.map((reward) => ({
@@ -71,20 +75,7 @@ export const ProgramRewardsPanel = memo(
? [
{
icon: Gift,
- label: discount.description || (
- <>
- New users get {constructRewardAmount(discount)} off{" "}
- {discount.maxDuration === null
- ? "for their lifetime"
- : discount.maxDuration === 0
- ? "for their first purchase"
- : discount.maxDuration === 1
- ? "for their first month"
- : discount.maxDuration && discount.maxDuration > 1
- ? `for ${discount.maxDuration} months`
- : null}
- </>
- ),
+ label: formatDiscountDescription(discount),
},
]
: []),
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index 9a1aa9a5fe..e8122f5a92 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -1,5 +1,6 @@
"use client";
+import { parseActionError } from "@/lib/actions/parse-action-errors";
import { createRewardAction } from "@/lib/actions/partners/create-reward";
import { deleteRewardAction } from "@/lib/actions/partners/delete-reward";
import { updateRewardAction } from "@/lib/actions/partners/update-reward";
@@ -108,13 +109,16 @@ function RewardSheetContent({
? Infinity
: defaultValuesSource.maxDuration
: Infinity,
- amount:
- defaultValuesSource?.type === "flat"
- ? defaultValuesSource.amount / 100
- : defaultValuesSource?.amount,
+ amountInCents:
+ defaultValuesSource?.amountInCents != null
+ ? defaultValuesSource.amountInCents / 100
+ : undefined,
+ amountInPercentage:
+ defaultValuesSource?.amountInPercentage != null
+ ? defaultValuesSource.amountInPercentage
+ : undefined,
description: defaultValuesSource?.description ?? null,
modifiers: defaultValuesSource?.modifiers?.map((m) => {
- const type = m.type === undefined ? defaultValuesSource?.type : m.type;
const maxDuration =
m.maxDuration === undefined
? defaultValuesSource?.maxDuration
@@ -132,7 +136,11 @@ function RewardSheetContent({
? Number(c.value) / 100
: c.value,
})),
- amount: type === "flat" ? m.amount / 100 : m.amount,
+ amountInCents:
+ m.amountInCents !== undefined && m.amountInCents !== null
+ ? m.amountInCents / 100
+ : undefined,
+ amountInPercentage: m.amountInPercentage ?? undefined,
maxDuration: m.maxDuration === null ? Infinity : maxDuration,
};
}),
@@ -141,15 +149,26 @@ function RewardSheetContent({
const { handleSubmit, watch, setValue, setError } = form;
- const [selectedEvent, amount, type, maxDuration, description, modifiers] =
- watch([
- "event",
- "amount",
- "type",
- "maxDuration",
- "description",
- "modifiers",
- ]);
+ const [
+ selectedEvent,
+ amountInCents,
+ amountInPercentage,
+ type,
+ maxDuration,
+ description,
+ modifiers,
+ ] = watch([
+ "event",
+ "amountInCents",
+ "amountInPercentage",
+ "type",
+ "maxDuration",
+ "description",
+ "modifiers",
+ ]);
+
+ // Compute amount based on type
+ const amount = type === "flat" ? amountInCents : amountInPercentage;
const { executeAsync: createReward, isPending: isCreating } = useAction(
createRewardAction,
@@ -161,7 +180,7 @@ function RewardSheetContent({
await mutateGroup();
},
onError({ error }) {
- toast.error(error.serverError);
+ toast.error(parseActionError(error, "Failed to create reward"));
},
},
);
@@ -176,7 +195,7 @@ function RewardSheetContent({
await mutateGroup();
},
onError({ error }) {
- toast.error(error.serverError);
+ toast.error(parseActionError(error, "Failed to update reward"));
},
},
);
@@ -239,7 +258,12 @@ function RewardSheetContent({
: Math.round(Number(c.value) * 100)
: c.value,
})),
- amount: type === "flat" ? Math.round(m.amount * 100) : m.amount,
+ amountInCents:
+ type === "flat" && m.amountInCents !== undefined
+ ? Math.round(m.amountInCents * 100)
+ : undefined,
+ amountInPercentage:
+ type === "percentage" ? m.amountInPercentage : undefined,
maxDuration: maxDuration === Infinity ? null : maxDuration,
};
}),
@@ -254,10 +278,21 @@ function RewardSheetContent({
}
}
+ const amount =
+ type === "flat"
+ ? {
+ amountInCents: Math.round((data.amountInCents ?? 0) * 100),
+ amountInPercentage: undefined,
+ }
+ : {
+ amountInCents: undefined,
+ amountInPercentage: data.amountInPercentage,
+ };
+
const payload = {
...data,
+ ...amount,
workspaceId,
- amount: type === "flat" ? Math.round(data.amount * 100) : data.amount,
maxDuration:
Infinity === Number(data.maxDuration) ? null : data.maxDuration,
modifiers,
@@ -339,15 +374,18 @@ function RewardSheetContent({
)}
<InlineBadgePopover
text={
- !isNaN(amount)
+ amount != null && !isNaN(amount)
? constructRewardAmount({
- amount: type === "flat" ? amount * 100 : amount,
type,
maxDuration,
+ amountInCents:
+ type === "flat" ? amount * 100 : undefined,
+ amountInPercentage:
+ type === "percentage" ? amount : undefined,
})
: "amount"
}
- invalid={isNaN(amount)}
+ invalid={amount == null || isNaN(amount)}
>
<AmountInput />
</InlineBadgePopover>{" "}
@@ -550,10 +588,11 @@ const VerticalLine = () => (
function AmountInput() {
const { watch, register } = useAddEditRewardForm();
- const type = watch("type");
-
const { setIsOpen } = useContext(InlineBadgePopoverContext);
+ const type = watch("type");
+ const fieldName = type === "flat" ? "amountInCents" : "amountInPercentage";
+
return (
<div className="relative rounded-md shadow-sm">
{type === "flat" && (
@@ -566,7 +605,7 @@ function AmountInput() {
"block w-full rounded-md border-neutral-300 px-1.5 py-1 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm",
type === "flat" ? "pl-4 pr-12" : "pr-7",
)}
- {...register("amount", {
+ {...register(fieldName, {
required: true,
setValueAs: (value: string) => (value === "" ? undefined : +value),
min: 0,
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index 8b9406fbb7..75eb3fba2f 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -114,15 +114,22 @@ export function RewardsLogic({
)}
</div>
}
- onClick={() =>
+ onClick={() => {
+ const type = getValues("type");
+
appendModifier({
operator: "AND",
conditions: [{}],
- amount: getValues("amount") || 0,
- type: getValues("type"),
+ amountInCents:
+ type === "flat" ? getValues("amountInCents") || 0 : undefined,
+ amountInPercentage:
+ type === "percentage"
+ ? getValues("amountInPercentage") || 0
+ : undefined,
+ type,
maxDuration: getValues("maxDuration"),
- })
- }
+ });
+ }}
variant={isDefaultReward ? "primary" : "secondary"}
/>
</div>
@@ -629,24 +636,34 @@ function ResultTerms({ modifierIndex }: { modifierIndex: number }) {
const modifierKey = `modifiers.${modifierIndex}` as const;
const { control, setValue } = useAddEditRewardForm();
- const [amount, type, maxDuration, event, parentType, parentMaxDuration] =
- useWatch({
- control,
- name: [
- `${modifierKey}.amount`,
- `${modifierKey}.type`,
- `${modifierKey}.maxDuration`,
- "event",
- "type",
- "maxDuration",
- ],
- });
+ const [
+ amountInCents,
+ amountInPercentage,
+ type,
+ maxDuration,
+ event,
+ parentType,
+ parentMaxDuration,
+ ] = useWatch({
+ control,
+ name: [
+ `${modifierKey}.amountInCents`,
+ `${modifierKey}.amountInPercentage`,
+ `${modifierKey}.type`,
+ `${modifierKey}.maxDuration`,
+ "event",
+ "type",
+ "maxDuration",
+ ],
+ });
// Use parent values as fallbacks if modifier doesn't have type or maxDuration
const displayType = type || parentType;
const displayMaxDuration =
maxDuration !== undefined ? maxDuration : parentMaxDuration;
+ const amount = displayType === "flat" ? amountInCents : amountInPercentage;
+
return (
<span className="leading-relaxed">
Then pay{" "}
@@ -669,15 +686,18 @@ function ResultTerms({ modifierIndex }: { modifierIndex: number }) {
)}
<InlineBadgePopover
text={
- !isNaN(amount)
+ amount != null && !isNaN(amount)
? constructRewardAmount({
- amount: displayType === "flat" ? amount * 100 : amount,
type: displayType,
+ amountInCents:
+ displayType === "flat" ? amount * 100 : undefined,
+ amountInPercentage:
+ displayType === "percentage" ? amount : undefined,
maxDuration: displayMaxDuration,
})
: "amount"
}
- invalid={isNaN(amount)}
+ invalid={amount == null || isNaN(amount)}
>
<ResultAmountInput modifierKey={modifierKey} />
</InlineBadgePopover>{" "}
@@ -752,9 +772,14 @@ function ResultAmountInput({
}
}, [type, parentType, setValue, modifierKey]);
+ const fieldKey =
+ displayType === "flat"
+ ? (`${modifierKey}.amountInCents` as const)
+ : (`${modifierKey}.amountInPercentage` as const);
+
return (
<AmountInput
- fieldKey={`${modifierKey}.amount`}
+ fieldKey={fieldKey}
type={displayType === "flat" ? "currency" : "percentage"}
/>
);
@@ -765,7 +790,8 @@ function AmountInput({
type,
}: {
fieldKey:
- | `modifiers.${number}.amount`
+ | `modifiers.${number}.amountInCents`
+ | `modifiers.${number}.amountInPercentage`
| `modifiers.${number}.conditions.${number}.value`;
type: "currency" | "percentage" | "number";
}) {
diff --git a/packages/email/src/react-email.d.ts b/packages/email/src/react-email.d.ts
index 34d6196cf8..215c8eb09e 100644
--- a/packages/email/src/react-email.d.ts
+++ b/packages/email/src/react-email.d.ts
@@ -14,6 +14,7 @@ declare module "@react-email/components" {
export const Link: React.FC<React.AnchorHTMLAttributes<HTMLAnchorElement>>;
export const Text: React.FC<React.HTMLAttributes<HTMLParagraphElement>>;
export const Heading: React.FC<React.HTMLAttributes<HTMLHeadingElement>>;
+ export const Hr: React.FC<React.HTMLAttributes<HTMLHRElement>>;
export const Preview: React.FC<{ children: React.ReactNode }>;
export const Tailwind: React.FC<{ children: React.ReactNode }>;
}
diff --git a/packages/email/src/templates/program-invite.tsx b/packages/email/src/templates/program-invite.tsx
index 8f0c77b997..3d2ed16da3 100644
--- a/packages/email/src/templates/program-invite.tsx
+++ b/packages/email/src/templates/program-invite.tsx
@@ -16,7 +16,7 @@ import {
} from "@react-email/components";
import { Footer } from "../components/footer";
-export default function PartnerInvite({
+export default function ProgramInvite({
email = "[email protected]",
name = "John Doe",
program = {
diff --git a/packages/prisma/schema/reward.prisma b/packages/prisma/schema/reward.prisma
index ad6de5a85e..bb4b029c9e 100644
--- a/packages/prisma/schema/reward.prisma
+++ b/packages/prisma/schema/reward.prisma
@@ -10,16 +10,18 @@ enum RewardStructure {
}
model Reward {
- id String @id @default(cuid())
- programId String
- description String?
- event EventType
- type RewardStructure @default(percentage)
- amount Int @default(0)
- maxDuration Int? // in months (0 -> not recurring, null -> infinite)
- modifiers Json? @db.Json
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ programId String
+ description String?
+ event EventType
+ type RewardStructure @default(percentage)
+ amountInCents Int?
+ amountInPercentage Decimal? @db.Decimal(4, 2)
+ amount Int @default(0) // TODO: Remove after migration
+ maxDuration Int? // in months (0 -> not recurring, null -> infinite)
+ modifiers Json? @db.Json
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
program Program @relation(fields: [programId], references: [id])
clickEnrollments ProgramEnrollment[] @relation("ClickRewardEnrollments")