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.

update the earnings

Kiran K4168013e1c35
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx
index 3e14e9ae78..319aed8dcc 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx
@@ -343,7 +343,16 @@ function ProgramSettingsForm({ program }: { program: ProgramProps }) {
function Summary({ program }: { program: ProgramProps }) {
const { control } = useFormContext<FormData>();
- const data = useWatch({ control, defaultValue: program }) as FormData;
+ const data = useWatch({
+ control,
+ defaultValue: {
+ ...program,
+ commissionAmount:
+ program.commissionType === "flat"
+ ? program.commissionAmount / 100
+ : program.commissionAmount,
+ },
+ }) as FormData;
return (
<SettingsRow heading="Summary">
diff --git a/apps/web/lib/actions/partners/create-manual-payout.ts b/apps/web/lib/actions/partners/create-manual-payout.ts
index 60da5c0f13..de1ca91efa 100644
--- a/apps/web/lib/actions/partners/create-manual-payout.ts
+++ b/apps/web/lib/actions/partners/create-manual-payout.ts
@@ -2,11 +2,12 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { getProgramOrThrow } from "@/lib/api/programs/get-program";
+import { calculateEarnings } from "@/lib/api/sales/commission";
import { createId } from "@/lib/api/utils";
import { createSalesPayout } from "@/lib/partners/create-sales-payout";
import { prisma } from "@/lib/prisma";
import { createManualPayoutSchema } from "@/lib/zod/schemas/payouts";
-import { Payout } from "@prisma/client";
+import { Payout, Program } from "@prisma/client";
import { authActionClient } from "../safe-action";
const schema = createManualPayoutSchema.refine(
@@ -26,7 +27,7 @@ export const createManualPayoutAction = authActionClient
const { programId, partnerId, start, end, type, amount, description } =
parsedInput;
- const [_, programEnrollment] = await Promise.all([
+ const [program, programEnrollment] = await Promise.all([
getProgramOrThrow({
workspaceId: workspace.id,
programId,
@@ -54,6 +55,20 @@ export const createManualPayoutAction = authActionClient
// Create a payout for sales
if (type === "sales") {
+ // commission amount changed for this payout
+ // recalculate the earnings for each sale within the period
+ if (program.commissionAmount !== amount) {
+ await updateSalesEarnings({
+ start: start!,
+ end: end!,
+ partnerId,
+ program: {
+ commissionAmount: amount,
+ commissionType: program.commissionType,
+ },
+ });
+ }
+
payout = await createSalesPayout({
programId,
partnerId,
@@ -78,7 +93,7 @@ export const createManualPayoutAction = authActionClient
quantity = count[type];
}
- const amountInCents = (quantity || 1) * (amount || 0) * 100;
+ const amountInCents = (quantity || 1) * (amount || 0);
const fee = amountInCents * 0.02;
payout = await prisma.payout.create({
@@ -106,3 +121,61 @@ export const createManualPayoutAction = authActionClient
return payout;
});
+
+// Recalculate earnings for sale based on new commission amount
+const updateSalesEarnings = async ({
+ start,
+ end,
+ partnerId,
+ program,
+}: {
+ start: Date;
+ end: Date;
+ partnerId: string;
+ program: Pick<Program, "commissionAmount" | "commissionType">;
+}) => {
+ const sales = await prisma.sale.findMany({
+ where: {
+ status: "pending",
+ partnerId,
+ createdAt: {
+ gte: start.toISOString(),
+ lte: end.toISOString(),
+ },
+ },
+ });
+
+ if (!sales.length) {
+ throw new Error("No sales found for this period.");
+ }
+
+ const { commissionAmount, commissionType } = program;
+
+ // Calculate the new earnings for each sale
+ const updatedEarnings = sales.map((sale) => {
+ return {
+ saleId: sale.id,
+ commissionAmount,
+ earnings: calculateEarnings({
+ program: {
+ commissionAmount,
+ commissionType,
+ },
+ sales: 1,
+ saleAmount: sale.amount,
+ }),
+ };
+ });
+
+ await Promise.all(
+ updatedEarnings.map(({ saleId, commissionAmount, earnings }) =>
+ prisma.sale.update({
+ where: { id: saleId },
+ data: {
+ commissionAmount,
+ earnings,
+ },
+ }),
+ ),
+ );
+};
diff --git a/apps/web/ui/partners/create-payout-sheet.tsx b/apps/web/ui/partners/create-payout-sheet.tsx
index a7e19c5ce8..f03fe68351 100644
--- a/apps/web/ui/partners/create-payout-sheet.tsx
+++ b/apps/web/ui/partners/create-payout-sheet.tsx
@@ -106,6 +106,9 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
const { partnerId, type: payoutType, start, end, amount } = watch();
+ const isPercentageBased =
+ payoutType === "sales" && program?.commissionType === "percentage";
+
const partnerOptions = useMemo(() => {
return partners?.map((partner) => ({
value: partner.id,
@@ -153,16 +156,34 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
programId: program.id,
start: data.start?.toISOString(),
end: data.end?.toISOString(),
+ amount: isPercentageBased ? amount : amount * 100,
});
}
};
const selectedPartner = partners?.find((p) => p.id === partnerId);
+ const salesSearchParams = useMemo(
+ () =>
+ new URLSearchParams({
+ workspaceId: workspaceId!,
+ partnerId: selectedPartner?.id || "",
+ start: start?.toISOString() || "",
+ end: end?.toISOString() || "",
+ }),
+ [workspaceId, selectedPartner?.id, start, end],
+ );
+
+ const shouldRequestSales = useMemo(
+ () => !!(payoutType === "sales" && start && end && selectedPartner?.link),
+ [payoutType, start, end, selectedPartner?.link],
+ );
+
const { data: totalEvents, isValidating } = useSWR<{
[key in AnalyticsResponseOptions]: number;
}>(
payoutType !== "custom" &&
+ payoutType !== "sales" &&
start &&
end &&
selectedPartner?.link &&
@@ -179,34 +200,30 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
const { data: salesAmount, isValidating: isValidatingSalesAmount } = useSWR<{
amount: number;
}>(
- payoutType === "sales" &&
- program?.commissionType === "percentage" &&
- start &&
- end &&
- selectedPartner?.link &&
- `/api/programs/${program?.id}/sales/amount?${new URLSearchParams({
- workspaceId: workspaceId!,
- partnerId: selectedPartner.id,
- start: start?.toISOString(),
- end: end?.toISOString(),
- }).toString()}`,
+ shouldRequestSales &&
+ `/api/programs/${program?.id}/sales/amount?${salesSearchParams.toString()}`,
fetcher,
);
- const isPercentBased =
- payoutType === "sales" && program?.commissionType === "percentage";
+ const { data: salesCount, isValidating: isValidatingSalesCount } = useSWR<{
+ pending: number;
+ duplicate: number;
+ fraud: number;
+ }>(
+ shouldRequestSales &&
+ `/api/programs/${program?.id}/sales/count?${salesSearchParams.toString()}`,
+ fetcher,
+ );
const invoiceData = useMemo(() => {
- const quantity = totalEvents?.[payoutType];
+ const quantity =
+ payoutType === "sales" ? salesCount?.pending : totalEvents?.[payoutType];
+
let payoutAmount: number | undefined = undefined;
if (payoutType === "custom") {
payoutAmount = amount;
- } else if (
- payoutType === "sales" &&
- program?.commissionType === "percentage" &&
- salesAmount?.amount
- ) {
+ } else if (isPercentageBased && salesAmount?.amount) {
payoutAmount = calculateEarnings({
program: program!,
sales: quantity,
@@ -247,16 +264,17 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
}),
...(payoutType !== "custom" && {
- [capitalize(payoutType) as string]: isValidating ? (
- <div className="h-4 w-12 animate-pulse rounded-md bg-neutral-200" />
- ) : (
- nFormatter(quantity, {
- full: true,
- })
- ),
+ [capitalize(payoutType) as string]:
+ isValidating || isValidatingSalesCount ? (
+ <div className="h-4 w-12 animate-pulse rounded-md bg-neutral-200" />
+ ) : (
+ nFormatter(quantity, {
+ full: true,
+ })
+ ),
[`Reward per ${payoutType.replace(/s$/, "")}`]: amountAsNumber
- ? !isPercentBased
+ ? !isPercentageBased
? currencyFormatter(amountAsNumber, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
@@ -265,7 +283,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
: "-",
}),
- ...(isPercentBased && {
+ ...(isPercentageBased && {
Revenue: isValidatingSalesAmount ? (
<div className="h-4 w-12 animate-pulse rounded-md bg-neutral-200" />
) : salesAmount?.amount ? (
@@ -316,6 +334,8 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
totalEvents,
amount,
isValidating,
+ isValidatingSalesAmount,
+ isValidatingSalesCount,
]);
return (
@@ -487,7 +507,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
Reward amount
</label>
<div className="relative mt-2 rounded-md shadow-sm">
- {!isPercentBased && (
+ {!isPercentageBased && (
<span className="absolute inset-y-0 left-0 flex items-center pl-3 text-sm text-neutral-400">
$
</span>
@@ -497,7 +517,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
"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",
"pr-[6.5rem]",
payoutType === "custom" && "pr-12",
- !isPercentBased && "pl-6",
+ !isPercentageBased && "pl-6",
errors.amount &&
"border-red-600 focus:border-red-500 focus:ring-red-600",
)}
@@ -509,7 +529,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
placeholder="5"
/>
<span className="absolute inset-y-0 right-0 flex items-center pr-3 text-sm text-neutral-400">
- {isPercentBased ? "%" : "USD"}
+ {isPercentageBased ? "%" : "USD"}
{payoutType !== "custom" &&
` per ${payoutType.replace(/s$/, "")}`}
</span>