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.

Allow updating commission `earnings` for all commisions (#3723)

Steven Tey4ba41bee6e6b
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page-client.tsx
index 79284e5b6f..1f9c6af56e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page-client.tsx
@@ -249,7 +249,7 @@ function CommissionDetailsContent({
Quantity: `${nFormatter(commission.quantity)} ${pluralize("click", commission.quantity)}`,
}),
- Commission: (
+ Earnings: (
<span
className={cn("font-medium", commission.earnings < 0 && "text-red-600")}
>
@@ -285,15 +285,18 @@ function CommissionDetailsContent({
<h3 className="text-content-emphasis text-base font-semibold">
Commission details
</h3>
- {commission.status !== "paid" && (
- <Button
- variant="secondary"
- icon={<Pen2 className="size-3.5" />}
- text="Edit"
- className="h-7 w-fit rounded-lg px-2"
- onClick={() => openEditCommissionModal(commission)}
- />
- )}
+ <Button
+ variant="secondary"
+ icon={<Pen2 className="size-3.5" />}
+ text="Edit"
+ className="h-7 w-fit rounded-lg px-2"
+ onClick={() => openEditCommissionModal(commission)}
+ disabledTooltip={
+ commission.status === "paid"
+ ? "This commission has already been paid and cannot be edited."
+ : undefined
+ }
+ />
</div>
<div className="flex flex-col gap-1">
{Object.entries(detailRows).map(([key, value]) => (
diff --git a/apps/web/lib/api/commissions/update-partner-commission.ts b/apps/web/lib/api/commissions/update-partner-commission.ts
index c9d5d36b77..64d412e36e 100644
--- a/apps/web/lib/api/commissions/update-partner-commission.ts
+++ b/apps/web/lib/api/commissions/update-partner-commission.ts
@@ -32,14 +32,15 @@ export async function updatePartnerCommission({
workspaceId,
programId,
commissionId,
+ // Common commission fields
status,
userId,
+ earnings,
// Sale commission fields
saleAmount,
modifySaleAmount,
currency,
// Custom commission fields
- earnings,
updateHistoricalCommissions = false,
}: UpdatePartnerCommissionProps) {
const commission = await prisma.commission.findUnique({
@@ -168,15 +169,9 @@ export async function updatePartnerCommission({
});
}
- // Commission for custom events
+ // for sale commissions, if earnings is provided,
+ // it will override the earnings calculated based on the sale amount and currency
if (earnings !== undefined) {
- if (commission.type !== "custom") {
- throw new DubApiError({
- code: "bad_request",
- message: `Cannot update earnings: Commission ${commissionId} is not a custom commission.`,
- });
- }
-
finalEarnings = earnings;
}
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index d44cdbd63e..74bd5ab852 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -202,25 +202,25 @@ export const commissionPatchStatusSchema = z.enum([
]);
export const updateCommissionSchema = z.object({
- saleAmount: z
+ earnings: z
.number()
.min(0)
.optional()
.describe(
- "The new absolute amount for the sale. Paid commissions cannot be updated.",
+ "The new earnings amount for the commission. Paid commissions cannot be updated. If provided, will override the earnings calculated based on the sale amount and currency.",
),
- modifySaleAmount: z
+ saleAmount: z
.number()
+ .min(0)
.optional()
.describe(
- "Modify the current sale amount: use positive values to increase the amount, negative values to decrease it. Takes precedence over `saleAmount`. Paid commissions cannot be updated.",
+ "The new absolute amount for the sale. Paid commissions cannot be updated.",
),
- earnings: z
+ modifySaleAmount: z
.number()
- .min(0)
.optional()
.describe(
- "The new absolute earnings for the custom commission. Paid commissions cannot be updated.",
+ "Modify the current sale amount: use positive values to increase the amount, negative values to decrease it. Takes precedence over `saleAmount`. Paid commissions cannot be updated.",
),
currency: z
.string()
diff --git a/apps/web/tests/commissions/index.test.ts b/apps/web/tests/commissions/index.test.ts
index 8ac750e6da..cb6c927b4d 100644
--- a/apps/web/tests/commissions/index.test.ts
+++ b/apps/web/tests/commissions/index.test.ts
@@ -64,9 +64,9 @@ describe.sequential("/commissions/**", async () => {
testPaidCommissionId = paidCommissions[0].id;
});
- test("PATCH /commissions/{id} - update amount", async () => {
+ test("PATCH /commissions/{id} - update earnings", async () => {
const toUpdate = {
- amount: 5000, // $50.00 in cents
+ earnings: 3000, // $30.00 in cents
};
const { status, data: commission } = await http.patch<CommissionResponse>({
@@ -77,11 +77,28 @@ describe.sequential("/commissions/**", async () => {
expect(status).toEqual(200);
expect(commission).toMatchObject({
...expectedCommission,
- amount: toUpdate.amount,
+ earnings: toUpdate.earnings,
+ });
+ });
+
+ test("PATCH /commissions/{id} - update saleAmount", async () => {
+ const toUpdate = {
+ saleAmount: 5000, // $50.00 in cents
+ };
+
+ const { status, data: commission } = await http.patch<CommissionResponse>({
+ path: `/commissions/${testCommissionId}`,
+ body: toUpdate,
+ });
+
+ expect(status).toEqual(200);
+ expect(commission).toMatchObject({
+ ...expectedCommission,
+ amount: toUpdate.saleAmount,
});
});
- test("PATCH /commissions/{id} - modify saleAmount", async () => {
+ test("PATCH /commissions/{id} - modifySaleAmount", async () => {
const toUpdate = {
modifySaleAmount: 1000, // Add $10.00 to existing amount
currency: "usd",
@@ -96,6 +113,23 @@ describe.sequential("/commissions/**", async () => {
expect(commission.amount).toEqual(6000);
});
+ test("PATCH /commissions/{id} - update amount (backward compatibility)", async () => {
+ const toUpdate = {
+ amount: 4000, // $40.00 in cents
+ };
+
+ const { status, data: commission } = await http.patch<CommissionResponse>({
+ path: `/commissions/${testCommissionId}`,
+ body: toUpdate,
+ });
+
+ expect(status).toEqual(200);
+ expect(commission).toMatchObject({
+ ...expectedCommission,
+ amount: toUpdate.amount,
+ });
+ });
+
test("PATCH /commissions/{id} - foreign currency conversion", async () => {
const toUpdate = {
saleAmount: 1580, // approximately 1000 USD cents
diff --git a/apps/web/ui/activity-logs/commission-activity.tsx b/apps/web/ui/activity-logs/commission-activity.tsx
index c01aae71bc..55a98f86e3 100644
--- a/apps/web/ui/activity-logs/commission-activity.tsx
+++ b/apps/web/ui/activity-logs/commission-activity.tsx
@@ -10,7 +10,7 @@ import { ActivityEvent } from "@/ui/partners/activity-event";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
import { CommentCardDisplay } from "@/ui/partners/partner-comments";
import { UserAvatar } from "@/ui/users/user-avatar";
-import { InvoiceDollar, StatusBadge } from "@dub/ui";
+import { InvoiceDollar, Receipt2, StatusBadge } from "@dub/ui";
import { currencyFormatter } from "@dub/utils";
import Link from "next/link";
@@ -29,22 +29,34 @@ function parseChangeSet(log: ActivityLog) {
if (!cur) return null;
+ const {
+ amount: curSaleAmount,
+ earnings: curEarnings,
+ status: curStatus,
+ } = cur;
+ const oldSaleAmount = old?.amount;
+ const oldEarnings = old?.earnings;
+
const statusChanged =
- old?.status !== cur.status &&
- typeof cur.status === "string" &&
- cur.status in CommissionStatusBadges;
+ old?.status !== curStatus &&
+ typeof curStatus === "string" &&
+ curStatus in CommissionStatusBadges;
- const amountChanged =
- !statusChanged &&
- (old?.amount !== cur.amount || old?.earnings !== cur.earnings);
+ const saleAmountChanged = oldSaleAmount !== curSaleAmount;
+ const earningsChanged = oldEarnings !== curEarnings;
return {
old,
cur,
statusChanged,
- amountChanged,
+ saleAmountChanged,
+ earningsChanged,
+ curSaleAmount,
+ curEarnings,
+ oldSaleAmount,
+ oldEarnings,
newStatus: statusChanged
- ? (cur.status as keyof typeof CommissionStatusBadges)
+ ? (curStatus as keyof typeof CommissionStatusBadges)
: null,
};
}
@@ -146,123 +158,133 @@ export function CommissionActivity({
const fmt = (v: number) =>
currencyFormatter(v, { trailingZeroDisplay: "stripIfInteger" });
- const logEvents = (activityLogs ?? [])
- .map((log) => {
- const parsed = parseChangeSet(log);
- if (!parsed) return null;
+ const logEvents = (activityLogs ?? []).flatMap((log) => {
+ const parsed = parseChangeSet(log);
+ if (!parsed) return [];
- const { old, cur, statusChanged, amountChanged, newStatus } = parsed;
+ const {
+ statusChanged,
+ saleAmountChanged,
+ earningsChanged,
+ newStatus,
+ curSaleAmount,
+ curEarnings,
+ oldSaleAmount,
+ oldEarnings,
+ } = parsed;
- const note = log.description ? (
- <CommentCardDisplay timestamp={log.createdAt} text={log.description} />
- ) : undefined;
+ const financialsChanged = saleAmountChanged || earningsChanged;
- const userByline = log.user ? (
- <>
- <span className="text-sm text-neutral-500">by</span>
- <div className="flex h-6 items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1">
- <UserAvatar user={log.user} className="size-4" />
- <span className="text-[13px] text-neutral-700">
- {log.user.name}
- </span>
- </div>
- </>
- ) : null;
+ if (!statusChanged && !financialsChanged) {
+ return [];
+ }
- if (statusChanged && newStatus) {
- const badge = CommissionStatusBadges[newStatus];
+ const note = log.description ? (
+ <CommentCardDisplay timestamp={log.createdAt} text={log.description} />
+ ) : undefined;
- return {
- key: log.id,
- icon: badge.icon,
- timestamp: log.createdAt,
- note,
- children: (
- <>
+ const userByline = log.user ? (
+ <>
+ <span className="text-sm text-neutral-500">by</span>
+ <div className="flex h-6 items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1">
+ <UserAvatar user={log.user} className="size-4" />
+ <span className="text-[13px] text-neutral-700">{log.user.name}</span>
+ </div>
+ </>
+ ) : null;
+
+ const events: {
+ key: string;
+ icon: React.ElementType;
+ timestamp: string | Date;
+ note?: typeof note;
+ children: React.ReactNode;
+ }[] = [];
+
+ if (statusChanged && newStatus) {
+ const badge = CommissionStatusBadges[newStatus];
+
+ events.push({
+ key: `${log.id}-status`,
+ icon: badge.icon,
+ timestamp: log.createdAt,
+ note,
+ children: (
+ <>
+ <span className="text-sm text-neutral-700">Status updated to</span>
+ <StatusBadge icon={null} variant={badge.variant}>
+ {badge.label}
+ </StatusBadge>
+ {newStatus === "processed" && commission.holdingPeriodDays ? (
<span className="text-sm text-neutral-700">
- Status updated to
+ after {commission.holdingPeriodDays}-day{" "}
+ <a
+ href="https://dub.co/help/article/partner-payouts#payout-holding-period"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ holding period
+ </a>
</span>
- <StatusBadge icon={null} variant={badge.variant}>
- {badge.label}
- </StatusBadge>
- {newStatus === "processed" && commission.holdingPeriodDays ? (
- <span className="text-sm text-neutral-700">
- after {commission.holdingPeriodDays}-day{" "}
- <a
- href="https://dub.co/help/article/partner-payouts#payout-holding-period"
- target="_blank"
- rel="noopener noreferrer"
- className="cursor-help underline decoration-dotted underline-offset-2"
- >
- holding period
- </a>
+ ) : null}
+ {userByline}
+ {newStatus === "paid" && commission.payout?.id ? (
+ <Link
+ href={`/${slug}/program/payouts/${commission.payout.id}`}
+ className="flex h-6 cursor-pointer items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1 transition-colors hover:bg-neutral-200"
+ >
+ <InvoiceDollar className="size-4 shrink-0 text-neutral-500" />
+ <span className="font-mono text-[13px] text-neutral-700">
+ {commission.payout.id}
</span>
- ) : null}
- {userByline}
- {newStatus === "paid" && commission.payout?.id ? (
- <Link
- href={`/${slug}/program/payouts/${commission.payout.id}`}
- className="flex h-6 cursor-pointer items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1 transition-colors hover:bg-neutral-200"
- >
- <InvoiceDollar className="size-4 shrink-0 text-neutral-500" />
- <span className="font-mono text-[13px] text-neutral-700">
- {commission.payout.id}
- </span>
- </Link>
- ) : null}
- </>
- ),
- };
- }
-
- if (amountChanged) {
- const parts: React.ReactNode[] = [];
+ </Link>
+ ) : null}
+ </>
+ ),
+ });
+ }
- if (old?.amount !== cur.amount) {
- parts.push(
- <span key="amount" className="text-sm text-neutral-700">
+ if (saleAmountChanged) {
+ events.push({
+ key: `${log.id}-sale`,
+ icon: Receipt2,
+ timestamp: log.createdAt,
+ note: !statusChanged ? note : undefined,
+ children: (
+ <>
+ <span className="text-sm text-neutral-700">
Sale amount updated
- </span>,
- <span
- key="amount-val"
- className="rounded-md bg-neutral-100 px-2 py-0.5 font-mono text-[13px] text-neutral-700"
- >
- {fmt(old?.amount ?? 0)} → {fmt(cur.amount)}
- </span>,
- );
- }
-
- if (old?.earnings !== cur.earnings) {
- parts.push(
- <span key="earnings" className="text-sm text-neutral-700">
- Earnings updated
- </span>,
- <span
- key="earnings-val"
- className="rounded-md bg-neutral-100 px-2 py-0.5 font-mono text-[13px] text-neutral-700"
- >
- {fmt(old?.earnings ?? 0)} → {fmt(cur.earnings)}
- </span>,
- );
- }
+ </span>
+ <span className="rounded-md bg-neutral-100 px-2 py-0.5 font-mono text-[13px] text-neutral-700">
+ {fmt(oldSaleAmount ?? 0)} → {fmt(curSaleAmount)}
+ </span>
+ {userByline}
+ </>
+ ),
+ });
+ }
- return {
- key: log.id,
- icon: InvoiceDollar,
- timestamp: log.createdAt,
- note,
- children: (
- <>
- {parts}
- {userByline}
- </>
- ),
- };
- }
+ if (earningsChanged) {
+ events.push({
+ key: `${log.id}-earnings`,
+ icon: InvoiceDollar,
+ timestamp: log.createdAt,
+ note: !statusChanged && !saleAmountChanged ? note : undefined,
+ children: (
+ <>
+ <span className="text-sm text-neutral-700">Earnings updated</span>
+ <span className="rounded-md bg-neutral-100 px-2 py-0.5 font-mono text-[13px] text-neutral-700">
+ {fmt(oldEarnings ?? 0)} → {fmt(curEarnings)}
+ </span>
+ {userByline}
+ </>
+ ),
+ });
+ }
- return null;
- })
- .filter((event): event is NonNullable<typeof event> => event !== null);
+ return events;
+ });
const allEvents = [...logEvents, createdEvent];
diff --git a/apps/web/ui/partners/edit-commission-modal.tsx b/apps/web/ui/partners/edit-commission-modal.tsx
index cc2ef807a3..d61e380998 100644
--- a/apps/web/ui/partners/edit-commission-modal.tsx
+++ b/apps/web/ui/partners/edit-commission-modal.tsx
@@ -4,6 +4,7 @@ import { useApiMutation } from "@/lib/swr/use-api-mutation";
import { CommissionResponse } from "@/lib/types";
import { commissionPatchStatusSchema } from "@/lib/zod/schemas/commissions";
import { Button, Combobox, Modal, StatusBadge, Switch } from "@dub/ui";
+import { useParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -12,11 +13,28 @@ import { PartnerAvatar } from "./partner-avatar";
import { useCommissionStatusCombobox } from "./use-commission-status-combobox";
type FormData = {
- earnings: number | null;
+ /** Dollar amount as typed (string) so decimals / trailing zeros are preserved while editing */
+ earnings: string;
status: z.infer<typeof commissionPatchStatusSchema>;
updateHistoricalCommissions: boolean;
};
+function centsToDollarsInputValue(cents: number): string {
+ return (cents / 100).toFixed(2);
+}
+
+function formatEarningsInputOnBlur(raw: string): string {
+ const trimmed = raw.trim();
+ if (trimmed === "") {
+ return trimmed;
+ }
+ const n = parseFloat(trimmed);
+ if (Number.isNaN(n) || n < 0) {
+ return raw;
+ }
+ return n.toFixed(2);
+}
+
interface EditCommissionModalProps {
showModal: boolean;
setShowModal: (show: boolean) => void;
@@ -28,10 +46,9 @@ function EditCommissionModal({
setShowModal,
commission,
}: EditCommissionModalProps) {
+ const { commissionId, payoutId } = useParams();
const { makeRequest, isSubmitting } = useApiMutation();
- const isCustom = commission.type === "custom";
-
const {
control,
handleSubmit,
@@ -40,7 +57,7 @@ function EditCommissionModal({
formState: { isDirty },
} = useForm<FormData>({
defaultValues: {
- earnings: isCustom ? commission.earnings / 100 : null,
+ earnings: centsToDollarsInputValue(commission.earnings),
status: commission.status as FormData["status"],
updateHistoricalCommissions: false,
},
@@ -55,12 +72,12 @@ function EditCommissionModal({
useEffect(() => {
if (showModal) {
reset({
- earnings: isCustom ? commission.earnings / 100 : null,
+ earnings: centsToDollarsInputValue(commission.earnings),
status: commission.status as FormData["status"],
updateHistoricalCommissions: false,
});
}
- }, [showModal, commission, reset, isCustom]);
+ }, [showModal, commission, reset]);
const onSubmit = async (data: FormData) => {
const body: Record<string, any> = {};
@@ -76,8 +93,9 @@ function EditCommissionModal({
body.updateHistoricalCommissions = true;
}
- if (isCustom && data.earnings !== null) {
- const earningsInCents = Math.round(data.earnings * 100);
+ const earningsNum = parseFloat(data.earnings);
+ if (!Number.isNaN(earningsNum)) {
+ const earningsInCents = Math.round(earningsNum * 100);
if (earningsInCents !== commission.earnings) {
body.earnings = earningsInCents;
}
@@ -93,7 +111,11 @@ function EditCommissionModal({
body,
onSuccess: async () => {
setShowModal(false);
- await mutatePrefix(["/api/commissions", "/api/payouts"]);
+ await mutatePrefix([
+ "/api/commissions",
+ ...(commissionId ? ["/api/activity-logs"] : []),
+ ...(payoutId ? [`/api/payouts/${payoutId}`] : []),
+ ]);
toast.success("Commission updated successfully!");
},
});
@@ -128,38 +150,59 @@ function EditCommissionModal({
</div>
</div>
- {isCustom && (
- <div>
- <label className="text-content-emphasis text-sm font-normal">
- Earnings
- </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">
- $
- </span>
- <Controller
- name="earnings"
- control={control}
- rules={{ required: true, min: 0 }}
- render={({ field }) => (
- <input
- type="text"
- inputMode="decimal"
- className="block w-full rounded-md border-neutral-300 pl-6 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- value={field.value ?? ""}
- onChange={(e) => {
- handleMoneyInputChange(e);
- const val = e.target.value;
- field.onChange(val === "" ? null : parseFloat(val));
- }}
- onKeyDown={handleMoneyKeyDown}
- placeholder="0.00"
- />
- )}
- />
- </div>
+ <div>
+ <label className="text-content-emphasis text-sm font-normal">
+ Earnings
+ </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">
+ $
+ </span>
+ <Controller
+ name="earnings"
+ control={control}
+ rules={{
+ required: true,
+ validate: (v) => {
+ if (v === "") {
+ return "Required";
+ }
+ const n = parseFloat(v);
+ if (Number.isNaN(n)) {
+ return "Enter a valid amount";
+ }
+ if (n < 0) {
+ return "Must be at least 0";
+ }
+ return true;
+ },
+ }}
+ render={({ field }) => (
+ <input
+ type="text"
+ inputMode="decimal"
+ className="block w-full rounded-md border-neutral-300 pl-6 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ value={field.value}
+ onChange={(e) => {
+ handleMoneyInputChange(e);
+ field.onChange(e.target.value);
+ }}
+ onBlur={(e) => {
+ field.onBlur();
+ const formatted = formatEarningsInputOnBlur(
+ e.target.value,
+ );
+ if (formatted !== e.target.value) {
+ field.onChange(formatted);
+ }
+ }}
+ onKeyDown={handleMoneyKeyDown}
+ placeholder="0.00"
+ />
+ )}
+ />
</div>
- )}
+ </div>
<div>
<label className="text-content-emphasis text-sm font-normal">