The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
support updating status
Steven Tey4d7328837062
diff --git a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts b/apps/web/app/(ee)/api/commissions/[commissionId]/route.tsindex 5e1a951895..c54a7d4786 100644--- a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts+++ b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts@@ -9,6 +9,7 @@ import {updateCommissionSchema,} from "@/lib/zod/schemas/commissions";import { prisma } from "@dub/prisma";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// PATCH /api/commissions/:commissionId - update a commission@@ -42,7 +43,7 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {const { partner, amount: originalAmount } = commission;- let { amount, modifyAmount, currency } = updateCommissionSchema.parse(+ let { amount, modifyAmount, currency, status } = updateCommissionSchema.parse(await parseRequestBody(req),);@@ -61,31 +62,44 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {}}- const finalAmount = modifyAmount- ? originalAmount + modifyAmount- : amount ?? originalAmount;+ let finalAmount: number | undefined;+ let finalEarnings: number | undefined;+ let earningsDifference: number | undefined;++ if (status) {+ // if status is being set to refunded, duplicate, canceled, or fraudulent+ // we need to decrement the payout amount by the commission earnings+ earningsDifference = -commission.earnings;+ } else if (amount || modifyAmount) {+ finalAmount = Math.max(+ modifyAmount ? originalAmount + modifyAmount : amount ?? originalAmount,+ 0, // Ensure the amount is not negative+ );++ const reward = await determinePartnerReward({+ event: "sale",+ partnerId: partner.id,+ programId,+ });- const reward = await determinePartnerReward({- event: "sale",- partnerId: partner.id,- programId,- });+ if (!reward) {+ throw new DubApiError({+ code: "not_found",+ message: `No reward found for partner ${partner.id} in program ${programId}.`,+ });+ }- if (!reward) {- throw new DubApiError({- code: "not_found",- message: `No reward found for partner ${partner.id} in program ${programId}.`,+ // Recalculate the earnings based on the new amount+ finalEarnings = calculateSaleEarnings({+ reward,+ sale: {+ amount: finalAmount,+ quantity: commission.quantity,+ },});- }- // Recalculate the earnings based on the new amount- const finalEarnings = calculateSaleEarnings({- reward,- sale: {- amount: finalAmount,- quantity: commission.quantity,- },- });+ earningsDifference = finalEarnings - commission.earnings;+ }const updatedCommission = await prisma.commission.update({where: {@@ -94,33 +108,30 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {data: {amount: finalAmount,earnings: finalEarnings,+ status,},});- // 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 payoutif (- amountDifference !== 0 &&+ earningsDifference &&commission.status === "processed" &&commission.payoutId) {- await prisma.payout.update({- where: {- id: commission.payoutId,- },- data: {- amount: {- ...(earningsDifference < 0- ? { decrement: Math.abs(earningsDifference) }- : { increment: earningsDifference }),+ waitUntil(+ 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/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex cad3298979..f2a9bb1c2f 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -96,31 +96,29 @@ export const createCommissionSchema = z.object({leadEventName: z.string().nullish(),});-export const updateCommissionSchema = z- .object({- 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.",- ),- })- .refine(- (data) => data.amount !== undefined || data.modifyAmount !== undefined,- {- message: "Either amount or modifyAmount must be provided.",- path: ["amount"],- },- );+export const updateCommissionSchema = z.object({+ 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.",+ ),+ status: z+ .enum(["refunded", "duplicate", "canceled", "fraud"])+ .optional()+ .describe(+ "Useful for marking a commission as refunded, duplicate, canceled, or fraudulent. Paid commissions cannot be updated.",+ ),+});