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.

PATCH /commissions/:commissionId

Steven Tey0c86d46c82a7
diff --git a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
new file mode 100644
index 0000000000..5d492f1f0c
--- /dev/null
+++ b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
@@ -0,0 +1,123 @@
+import { DubApiError } from "@/lib/api/errors";
+import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";
+import { redis } from "@/lib/upstash";
+import { CommissionSchema } from "@/lib/zod/schemas/commissions";
+import { updateCommissionSchema } from "@/lib/zod/schemas/partners";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// PATCH /api/commissions/:commissionId - update a commission
+export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
+ const { commissionId } = params;
+
+ const commission = await prisma.commission.findUnique({
+ where: {
+ id: commissionId,
+ },
+ include: {
+ partner: true,
+ },
+ });
+
+ if (!commission || commission.programId !== workspace.defaultProgramId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Commission ${commissionId} not found.`,
+ });
+ }
+
+ if (commission.status === "paid") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Cannot update amount: Commission ${commissionId} has already been paid.`,
+ });
+ }
+
+ const { partner, amount: originalAmount } = commission;
+
+ let { amount, modifyAmount, currency } = updateCommissionSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ // if currency is not USD, convert it to USD based on the current FX rate
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ if (currency !== "usd") {
+ const fxRates = await redis.hget("fxRates:usd", currency.toUpperCase()); // e.g. for MYR it'll be around 4.4
+ if (fxRates) {
+ currency = "usd";
+ // convert amount to USD (in cents) based on the current FX rate
+ // round it to 0 decimal places
+ amount = Math.round(originalAmount / Number(fxRates));
+ modifyAmount = modifyAmount
+ ? Math.round(modifyAmount / Number(fxRates))
+ : undefined;
+ }
+ }
+
+ const finalAmount = modifyAmount
+ ? originalAmount + modifyAmount
+ : amount ?? originalAmount;
+
+ const reward = await determinePartnerReward({
+ event: "sale",
+ partnerId: partner.id,
+ programId: commission.programId,
+ });
+
+ if (!reward) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `No reward found for partner ${partner.id} in program ${commission.programId}.`,
+ });
+ }
+
+ // Recalculate the earnings based on the new amount
+ const finalEarnings = calculateSaleEarnings({
+ reward,
+ sale: {
+ amount: finalAmount,
+ quantity: commission.quantity,
+ },
+ });
+
+ const updatedCommission = await prisma.commission.update({
+ where: {
+ id: commission.id,
+ },
+ data: {
+ amount: finalAmount,
+ earnings: finalEarnings,
+ },
+ });
+
+ // TODO:
+ // Check the reward limit
+
+ const amountDifference = finalAmount - commission.amount;
+ const earningsDifference = finalEarnings - commission.earnings;
+
+ // If the sale has already been paid, we need to update the payout
+ if (
+ amountDifference !== 0 &&
+ commission.status === "processed" &&
+ commission.payoutId
+ ) {
+ await prisma.payout.update({
+ where: {
+ id: commission.payoutId,
+ },
+ data: {
+ amount: {
+ ...(earningsDifference < 0
+ ? { decrement: Math.abs(earningsDifference) }
+ : { increment: earningsDifference }),
+ },
+ },
+ });
+ }
+
+ return NextResponse.json(CommissionSchema.parse(updatedCommission));
+});
diff --git a/apps/web/app/(ee)/api/commissions/route.ts b/apps/web/app/(ee)/api/commissions/route.ts
index 70d4cae3cb..5cbfededa2 100644
--- a/apps/web/app/(ee)/api/commissions/route.ts
+++ b/apps/web/app/(ee)/api/commissions/route.ts
@@ -26,6 +26,7 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
customerId,
payoutId,
partnerId,
+ invoiceId,
page,
pageSize,
sortBy,
@@ -42,21 +43,26 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
});
const commissions = await prisma.commission.findMany({
- where: {
- earnings: {
- gt: 0,
- },
- programId,
- partnerId,
- status,
- type,
- customerId,
- payoutId,
- createdAt: {
- gte: startDate.toISOString(),
- lte: endDate.toISOString(),
- },
- },
+ where: invoiceId
+ ? {
+ programId,
+ invoiceId,
+ }
+ : {
+ earnings: {
+ gt: 0,
+ },
+ programId,
+ partnerId,
+ status,
+ type,
+ customerId,
+ payoutId,
+ createdAt: {
+ gte: startDate.toISOString(),
+ lte: endDate.toISOString(),
+ },
+ },
include: {
customer: true,
partner: true,
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index 02d50a9b65..e05c9a5645 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -32,6 +32,7 @@ export const getCommissionsQuerySchema = z
customerId: z.string().optional(),
payoutId: z.string().optional(),
partnerId: z.string().optional(),
+ invoiceId: z.string().optional(),
status: z.nativeEnum(CommissionStatus).optional(),
sortBy: z.enum(["createdAt", "amount"]).default("createdAt"),
sortOrder: z.enum(["asc", "desc"]).default("desc"),
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 634ae6b825..19e072e554 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -484,10 +484,8 @@ export const partnerAnalyticsResponseSchema = {
}),
} as const;
-export const updatePartnerSaleSchema = z
+export const updateCommissionSchema = z
.object({
- programId: z.string(),
- invoiceId: z.string(),
amount: z
.number()
.min(0)
@@ -515,6 +513,30 @@ export const updatePartnerSaleSchema = z
},
);
+// TODO: remove this
+export const updatePartnerSaleSchema = z.object({
+ programId: z.string(),
+ invoiceId: z.string(),
+ amount: z
+ .number()
+ .min(0)
+ .describe("The new absolute amount for the sale.")
+ .optional(),
+ modifyAmount: z
+ .number()
+ .describe(
+ "Modify the current sale amount: use positive values to increase the amount, negative values to decrease it.",
+ )
+ .optional(),
+ currency: z
+ .string()
+ .default("usd")
+ .transform((val) => val.toLowerCase())
+ .describe(
+ "The currency of the sale amount to update. Accepts ISO 4217 currency codes.",
+ ),
+});
+
export const invitePartnerSchema = z.object({
workspaceId: z.string(),
programId: z.string(),