The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Use POST /commissions for clawbacks instead of dedicated /api/clawbacks endpoint.
Kiran Ka559a71e49b8
diff --git a/apps/web/app/(ee)/api/clawbacks/route.ts b/apps/web/app/(ee)/api/clawbacks/route.tsdeleted file mode 100644index fcf05260df..0000000000--- a/apps/web/app/(ee)/api/clawbacks/route.ts+++ /dev/null@@ -1,83 +0,0 @@-import { DubApiError } from "@/lib/api/errors";-import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";-import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";-import { parseRequestBody } from "@/lib/api/utils";-import { withWorkspace } from "@/lib/auth";-import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";-import { throwIfNoPartnerIdOrTenantId } from "@/lib/partners/throw-if-no-partnerid-tenantid";-import { prisma } from "@/lib/prisma";-import {- createClawbackSchema,- createCommissionResponseSchema,-} from "@/lib/zod/schemas/commissions";-import { NextResponse } from "next/server";--// POST /api/clawbacks – create a clawback for a partner-export const POST = withWorkspace(- async ({ workspace, session, req }) => {- const programId = getDefaultProgramIdOrThrow(workspace);-- let { partnerId, tenantId, amount, reason } = createClawbackSchema.parse(- await parseRequestBody(req),- );-- throwIfNoPartnerIdOrTenantId({- partnerId,- tenantId,- });-- if (tenantId && !partnerId) {- const partner = await prisma.programEnrollment.findUnique({- where: {- tenantId_programId: {- tenantId,- programId,- },- },- select: {- partnerId: true,- },- });-- if (!partner) {- throw new DubApiError({- code: "not_found",- message: `Partner with specified tenantId ${tenantId} not found.`,- });- }-- partnerId = partner.partnerId;- }-- await getProgramEnrollmentOrThrow({- programId,- partnerId: partnerId!,- include: {},- });-- await queuePartnerCommissionCreation({- event: "custom",- partnerId: partnerId!,- programId,- description: reason,- amount: -amount,- quantity: 1,- userId: session.user.id,- triggerAggregateDueCommissions: true,- });-- return NextResponse.json(- createCommissionResponseSchema.parse({- success: true,- message: "Your clawback is being created and will appear shortly.",- }),- {- status: 202,- },- );- },- {- requiredPlan: ["business", "advanced", "enterprise"],- requiredRoles: ["owner", "member"],- },-);diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-clawback-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-clawback-sheet.tsxindex 961f0a16a9..a351a11a92 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-clawback-sheet.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-clawback-sheet.tsx@@ -3,7 +3,6 @@ import { useApiMutation } from "@/lib/swr/use-api-mutation";import useWorkspace from "@/lib/swr/use-workspace";import {CLAWBACK_REASONS,- createClawbackSchema,createCommissionResponseSchema,} from "@/lib/zod/schemas/commissions";import { PartnerSelector } from "@/ui/partners/partner-selector";@@ -21,7 +20,11 @@ interface CreateClawbackSheetProps {nested?: boolean;}-type FormData = z.infer<typeof createClawbackSchema>;+type FormData = {+ partnerId?: string;+ amount?: number;+ reason?: (typeof CLAWBACK_REASONS)[number]["value"];+};function CreateClawbackSheetContent(props: Omit<CreateClawbackSheetProps, "nested">,@@ -55,12 +58,13 @@ function CreateClawbackSheetContent(return;}- await makeRequest("/api/clawbacks", {+ await makeRequest("/api/commissions", {method: "POST",body: {+ type: "custom",partnerId: data.partnerId,- amount: data.amount ? Math.round(data.amount * 100) : 0,- reason: data.reason,+ amount: data.amount ? -Math.round(data.amount * 100) : 0,+ description: data.reason,},onSuccess: async ({ message }) => {toast.success(message);diff --git a/apps/web/lib/auth/product-access-guard.ts b/apps/web/lib/auth/product-access-guard.tsindex 6cebbd3b97..e09a179c77 100644--- a/apps/web/lib/auth/product-access-guard.ts+++ b/apps/web/lib/auth/product-access-guard.ts@@ -34,7 +34,6 @@ export const PROGRAM_API_PATHS = ["/api/programs","/api/partners","/api/commissions",- "/api/clawbacks","/api/payouts","/api/rewards","/api/bounties",diff --git a/apps/web/lib/openapi/clawbacks/create-clawback.ts b/apps/web/lib/openapi/clawbacks/create-clawback.tsdeleted file mode 100644index 2e922320ce..0000000000--- a/apps/web/lib/openapi/clawbacks/create-clawback.ts+++ /dev/null@@ -1,34 +0,0 @@-import {- createClawbackSchema,- createCommissionResponseSchema,-} from "@/lib/zod/schemas/commissions";-import { ZodOpenApiOperationObject } from "zod-openapi";-import { openApiErrorResponses } from "../responses";--export const createClawback: ZodOpenApiOperationObject = {- operationId: "createClawback",- "x-speakeasy-name-override": "create",- summary: "Create clawback",- description:- "Create a clawback for a partner. Clawback creation is processed asynchronously. Use the List Commissions endpoint or webhooks to be notified when the clawback is created.",- requestBody: {- content: {- "application/json": {- schema: createClawbackSchema,- },- },- },- responses: {- "202": {- description: "The request was accepted and clawback creation was queued.",- content: {- "application/json": {- schema: createCommissionResponseSchema,- },- },- },- ...openApiErrorResponses,- },- tags: ["Commissions"],- security: [{ token: [] }],-};diff --git a/apps/web/lib/openapi/clawbacks/index.ts b/apps/web/lib/openapi/clawbacks/index.tsdeleted file mode 100644index 22a2253e50..0000000000--- a/apps/web/lib/openapi/clawbacks/index.ts+++ /dev/null@@ -1,8 +0,0 @@-import { ZodOpenApiPathsObject } from "zod-openapi";-import { createClawback } from "./create-clawback";--export const clawbacksPaths: ZodOpenApiPathsObject = {- "/clawbacks": {- post: createClawback,- },-};diff --git a/apps/web/lib/openapi/commissions/create-commission.ts b/apps/web/lib/openapi/commissions/create-commission.tsindex 9c6c9edf0c..9ccee783d9 100644--- a/apps/web/lib/openapi/commissions/create-commission.ts+++ b/apps/web/lib/openapi/commissions/create-commission.ts@@ -10,7 +10,7 @@ export const createCommission: ZodOpenApiOperationObject = {"x-speakeasy-name-override": "create",summary: "Create commission",description:- "Create one or more commissions (custom, lead or sale) for a partner. Commission creation is processed asynchronously. Use the List Commissions endpoint or webhooks to be notified when the commission is created.",+ "Create one or more commissions (custom, lead or sale) for a partner. Custom commissions accept a negative `amount` to create a clawback; in that case `description` is required and may be a known clawback reason or any other string. Commission creation is processed asynchronously. Use the List Commissions endpoint or webhooks to be notified when the commission is created.",requestBody: {content: {"application/json": {diff --git a/apps/web/lib/openapi/index.ts b/apps/web/lib/openapi/index.tsindex aa29420983..0044fc30b0 100644--- a/apps/web/lib/openapi/index.ts+++ b/apps/web/lib/openapi/index.ts@@ -7,7 +7,6 @@ import { LinkErrorSchema, LinkSchema } from "../zod/schemas/links";import { LinkTagSchema } from "../zod/schemas/tags";import { analyticsPath } from "./analytics";import { bountiesPaths } from "./bounties";-import { clawbacksPaths } from "./clawbacks";import { commissionsPaths } from "./commissions";import { customersPaths } from "./customers";import { discountCodesPaths } from "./discount-codes";@@ -58,7 +57,6 @@ export const document = createDocument({...partnersPaths,...discountCodesPaths,...commissionsPaths,- ...clawbacksPaths,...payoutsPaths,...embedTokensPaths,...qrCodePaths,diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex b764fd1ba5..7cf8af8034 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -7,11 +7,7 @@ import {getCursorPaginationQuerySchema,getPaginationQuerySchema,} from "./misc";-import {- EnrolledPartnerSchema,- partnerIdTenantIdSchema,- WebhookPartnerSchema,-} from "./partners";+import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";import { PayoutSchema } from "./payouts";import { rewardContextSchema, RewardSchema } from "./rewards";import { UserSchema } from "./users";@@ -322,15 +318,6 @@ export const CLAWBACK_REASONS_MAP = Object.fromEntries(CLAWBACK_REASONS.map((r) => [r.value, r]),);-export const createClawbackSchema = partnerIdTenantIdSchema.extend({- amount: centsSchema- .pipe(z.number().gt(0, "Amount must be greater than 0."))- .describe("The clawback amount in cents (positive)."),- reason: z- .enum(CLAWBACK_REASONS.map((r) => r.value) as [string, ...string[]])- .describe("The reason for the clawback."),-});-export const COMMISSION_EXPORT_COLUMNS = [{ id: "id", label: "ID", type: "string", default: true },{ id: "type", label: "Type", type: "string", default: true },@@ -465,15 +452,21 @@ export const createPartnerCommissionSchema = z.object({export const createManualCommissionBodySchema = z.discriminatedUnion("type", [- // Custom commission+ // Custom commission (negative amount = clawback)z.object({type: z.literal("custom"),partnerId: z.string().describe("The ID of the partner to create the commission for."),amount: centsSchema- .pipe(z.number().min(1))- .describe("The commission amount in cents."),+ .pipe(+ z.number().refine((n) => n !== 0, {+ message: "Amount cannot be 0.",+ }),+ )+ .describe(+ "The commission amount in cents. Use a negative amount to create a clawback.",+ ),date: parseDateSchema.nullish().describe("If not provided, the current date will be used."),@@ -481,7 +474,9 @@ export const createManualCommissionBodySchema = z.string().max(190).nullish()- .describe("The description of the commission."),+ .describe(+ "The description of the commission. Required for clawbacks (negative `amount`). May be a known clawback reason (`order_canceled`, `fraud`, `terms_violation`, `tracking_error`, `payment_failed`, `ineligible_partner`, `duplicate_commission`, `other`) or any other string.",+ ),}),// Lead commission@@ -577,6 +572,18 @@ export const createManualCommissionBodySchema = z}),]).superRefine((data, ctx) => {+ if (data.type === "custom" && data.amount < 0) {+ if (!data.description?.trim()) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ "`description` is required when creating a clawback (negative amount).",+ path: ["description"],+ });+ }+ return;+ }+if (data.type !== "sale") return;if (!data.importStripeInvoices && data.saleAmount == null) {diff --git a/apps/web/playwright/api/clawbacks/clawbacks.spec.ts b/apps/web/playwright/api/clawbacks/clawbacks.spec.tsindex 52b10a09ef..8a0a6a9fb7 100644--- a/apps/web/playwright/api/clawbacks/clawbacks.spec.ts+++ b/apps/web/playwright/api/clawbacks/clawbacks.spec.ts@@ -7,10 +7,60 @@ import { createPartner, deletePartner } from "../partners/helpers";const expectedQueuedResponse = {success: true,- message: "Your clawback is being created and will appear shortly.",+ message: "Your commissions are being created and will appear shortly.",};-test("POST /clawbacks – by partnerId", async ({ api, program }) => {+async function expectClawbackCreated({+ partnerId,+ programId,+ amount,+ description,+}: {+ partnerId: string;+ programId: string;+ amount: number;+ description: string;+}) {+ await expect+ .poll(async () => {+ const commission = await prisma.commission.findFirst({+ where: {+ partnerId,+ programId,+ type: "custom",+ description,+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ if (!commission) {+ return null;+ }++ return {+ partnerId: commission.partnerId,+ programId: commission.programId,+ type: commission.type,+ amount: Number(commission.amount),+ earnings: Number(commission.earnings),+ quantity: commission.quantity,+ description: commission.description,+ };+ })+ .toEqual({+ partnerId,+ programId,+ type: "custom",+ amount: 0,+ earnings: -amount,+ quantity: 1,+ description,+ });+}++test("POST /commissions – clawback by partnerId", async ({ api, program }) => {let partnerId: string | undefined;try {@@ -20,10 +70,11 @@ test("POST /clawbacks – by partnerId", async ({ api, program }) => {partnerId = created.id;expect(createStatus).toEqual(201);- const { status, data } = await api.post("/api/clawbacks", {+ const { status, data } = await api.post("/api/commissions", {+ type: "custom",partnerId,- amount: 500,- reason: "fraud",+ amount: -500,+ description: "fraud",});expect(status).toEqual(202);@@ -33,30 +84,32 @@ test("POST /clawbacks – by partnerId", async ({ api, program }) => {partnerId: created.id,programId: program.id,amount: 500,- reason: "fraud",+ description: "fraud",});} finally {await deletePartner(partnerId);}});-test("POST /clawbacks – by tenantId", async ({ api, program }) => {+test("POST /commissions – clawback with arbitrary description", async ({+ api,+ program,+}) => {let partnerId: string | undefined;- const tenantId = nanoid();+ const description = `chargeback-${nanoid()}`;try {const { status: createStatus, data: created } = await createPartner(api, {- tenantId,groupId: program.defaultGroupId,});partnerId = created.id;expect(createStatus).toEqual(201);- expect(created.tenantId).toBe(tenantId);- const { status, data } = await api.post("/api/clawbacks", {- tenantId,- amount: 250,- reason: "order_canceled",+ const { status, data } = await api.post("/api/commissions", {+ type: "custom",+ partnerId,+ amount: -100,+ description,});expect(status).toEqual(202);@@ -65,8 +118,8 @@ test("POST /clawbacks – by tenantId", async ({ api, program }) => {await expectClawbackCreated({partnerId: created.id,programId: program.id,- amount: 250,- reason: "order_canceled",+ amount: 100,+ description,});} finally {await deletePartner(partnerId);@@ -74,12 +127,16 @@ test("POST /clawbacks – by tenantId", async ({ api, program }) => {});const missingPartnerId = `pn_${nanoid()}`;-const missingTenantId = nanoid();const clawbackErrorCases = [{- name: "POST /clawbacks – partner not found",- body: { partnerId: missingPartnerId, amount: 500, reason: "fraud" },+ name: "POST /commissions – clawback partner not found",+ body: {+ type: "custom",+ partnerId: missingPartnerId,+ amount: -500,+ description: "fraud",+ },expected: ({ program }: { program: { id: string } }) =>apiError({code: "not_found",@@ -87,111 +144,42 @@ const clawbackErrorCases = [}),},{- name: "POST /clawbacks – tenantId not found",- body: { tenantId: missingTenantId, amount: 500, reason: "fraud" },- expected: apiError({- code: "not_found",- message: `Partner with specified tenantId ${missingTenantId} not found.`,- }),- },- {- name: "POST /clawbacks – missing partnerId and tenantId",- body: { amount: 500, reason: "fraud" },- expected: apiError({- code: "bad_request",- message: "Either `partnerId` or `tenantId` must be provided.",- }),- },- {- name: "POST /clawbacks – amount 0",- body: { partnerId: "pn_test", amount: 0, reason: "fraud" },- expected: apiError({- code: "unprocessable_entity",- message: "too_small: amount: Amount must be greater than 0.",- }),- },- {- name: "POST /clawbacks – amount negative",- body: { partnerId: "pn_test", amount: -100, reason: "fraud" },+ name: "POST /commissions – clawback missing partnerId",+ body: { type: "custom", amount: -500, description: "fraud" },expected: apiError({code: "unprocessable_entity",- message: "too_small: amount: Amount must be greater than 0.",+ message:+ "invalid_type: partnerId: Invalid input: expected string, received undefined",}),},{- name: "POST /clawbacks – missing reason",- body: { partnerId: "pn_test", amount: 500 },+ name: "POST /commissions – clawback amount 0",+ body: {+ type: "custom",+ partnerId: "pn_test",+ amount: 0,+ description: "fraud",+ },expected: apiError({code: "unprocessable_entity",- message:- 'invalid_value: reason: Invalid option: expected one of "order_canceled"|"fraud"|"terms_violation"|"tracking_error"|"payment_failed"|"ineligible_partner"|"duplicate_commission"|"other"',+ message: "custom: amount: Amount cannot be 0.",}),},{- name: "POST /clawbacks – invalid reason",- body: { partnerId: "pn_test", amount: 500, reason: "not_a_reason" },+ name: "POST /commissions – clawback missing description",+ body: { type: "custom", partnerId: "pn_test", amount: -500 },expected: apiError({code: "unprocessable_entity",message:- 'invalid_value: reason: Invalid option: expected one of "order_canceled"|"fraud"|"terms_violation"|"tracking_error"|"payment_failed"|"ineligible_partner"|"duplicate_commission"|"other"',+ "custom: description: `description` is required when creating a clawback (negative amount).",}),},];for (const { name, body, expected } of clawbackErrorCases) {test(name, async ({ api, program }) => {- expect(await api.post("/api/clawbacks", body)).toEqual(+ expect(await api.post("/api/commissions", body)).toEqual(typeof expected === "function" ? expected({ program }) : expected,);});}--async function expectClawbackCreated({- partnerId,- programId,- amount,- reason,-}: {- partnerId: string;- programId: string;- amount: number;- reason: string;-}) {- await expect- .poll(async () => {- const commission = await prisma.commission.findFirst({- where: {- partnerId,- programId,- type: "custom",- description: reason,- },- orderBy: {- createdAt: "desc",- },- });-- if (!commission) {- return null;- }-- return {- partnerId: commission.partnerId,- programId: commission.programId,- type: commission.type,- amount: Number(commission.amount),- earnings: Number(commission.earnings),- quantity: commission.quantity,- description: commission.description,- };- })- .toEqual({- partnerId,- programId,- type: "custom",- amount: 0,- earnings: -amount,- quantity: 1,- description: reason,- });-}diff --git a/apps/web/tests/commissions/create-commission.test.ts b/apps/web/tests/commissions/create-commission.test.tsindex 04aae324f0..903a87033b 100644--- a/apps/web/tests/commissions/create-commission.test.ts+++ b/apps/web/tests/commissions/create-commission.test.ts@@ -31,7 +31,7 @@ const validationCases = [name: "custom commission with amount 0",body: { type: "custom", partnerId: E2E_PARTNER.id, amount: 0 },expectedStatus: 422,- expectedMessage: "too_small: amount: Too small: expected number to be >=1",+ expectedMessage: "custom: amount: Amount cannot be 0.",},{name: "sale commission missing saleAmount",