The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add nested lead/sale objects to the create-commission schema.
Kiran K41dacf3760de
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex 8b515f4918..74cb92e3c3 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -2,6 +2,7 @@ import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";import { CommissionStatus, CommissionType } from "@prisma/client";import * as z from "zod/v4";import { createCustomerBodySchema, CustomerSchema } from "./customers";+import { trackLeadRequestSchema } from "./leads";import { LinkSchema } from "./links";import {getCursorPaginationQuerySchema,@@ -10,6 +11,7 @@ import {import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";import { PayoutSchema } from "./payouts";import { rewardContextSchema, RewardSchema } from "./rewards";+import { trackSaleRequestSchema } from "./sales";import { UserSchema } from "./users";import { centsSchema, parseDateSchema } from "./utils";@@ -450,7 +452,7 @@ export const createPartnerCommissionSchema = z.object({),});-export const createManualCommissionBodySchema = z+export const createCommissionBodySchemaV2 = z.discriminatedUnion("type", [// Custom commission (negative amount = clawback)z.object({@@ -502,18 +504,42 @@ export const createManualCommissionBodySchema = z.describe("The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",),- leadEventDate: parseDateSchema+ date: parseDateSchema.nullish().describe("The date and time of the lead event. If not provided, defaults to the current date and time.",),+ lead: z+ .object({+ eventName: z+ .string()+ .trim()+ .max(255)+ .default("Sign up")+ .describe(+ "The name of the lead event to track. If not provided, defaults to 'Sign up'.",+ )+ .meta({ example: "Sign up" }),+ metadata: trackLeadRequestSchema.shape.metadata,+ })+ .nullish()+ .describe("The lead event object to associate the commission with."),++ // Deprecated fields+ leadEventDate: parseDateSchema+ .nullish()+ .describe(+ "Deprecated: Use `date` instead. The date and time of the lead event. If not provided, defaults to the current date and time.",+ )+ .meta({ deprecated: true }),leadEventName: z.string().nullish().default("Sign up").describe(- "The name of the lead event. If not provided, defaults to 'Sign up'.",- ),+ "Deprecated: Use `lead.eventName` instead. The name of the lead event. If not provided, defaults to 'Sign up'.",+ )+ .meta({ deprecated: true }),}),// Sale commission@@ -546,29 +572,50 @@ export const createManualCommissionBodySchema = z.describe("When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `saleAmount`.",),+ date: parseDateSchema+ .nullish()+ .describe(+ "Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",+ ),+ sale: z+ .object({+ amount: trackSaleRequestSchema.shape.amount,+ currency: trackSaleRequestSchema.shape.currency,+ eventName: trackSaleRequestSchema.shape.eventName,+ paymentProcessor: trackSaleRequestSchema.shape.paymentProcessor,+ invoiceId: trackSaleRequestSchema.shape.invoiceId,+ metadata: trackSaleRequestSchema.shape.metadata,+ })+ .nullish(),++ // Deprecated fieldssaleAmount: centsSchema.pipe(z.number().min(0)).nullish().describe(- "Required when `importStripeInvoices` is `false`. The sale amount in cents for the manual sale event. Ignored when importing from Stripe.",- ),+ "Deprecated: Use `sale.amount` instead. Required when `importStripeInvoices` is `false`. The sale amount in cents for the manual sale event. Ignored when importing from Stripe.",+ )+ .meta({ deprecated: true }),saleEventDate: parseDateSchema.nullish().describe(- "Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",- ),+ "Deprecated: Use `date` instead. Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",+ )+ .meta({ deprecated: true }),invoiceId: z.string().nullish().describe(- "Only used when `importStripeInvoices` is `false`. An optional invoice ID to attach to the generated sale event and commission entry for deduplication.",- ),+ "Deprecated: Use `sale.invoiceId` instead. Only used when `importStripeInvoices` is `false`. An optional invoice ID to attach to the generated sale event and commission entry for deduplication.",+ )+ .meta({ deprecated: true }),productId: z.string().nullish().describe(- "Only used when `importStripeInvoices` is `false`. An optional product ID stored on the sale event metadata – will also impact commission earnings calculation (if a `Sale` `Product ID` modifier is set).",- ),+ "Deprecated: Use `sale.metadata.productId` instead. Only used when `importStripeInvoices` is `false`. An optional product ID stored on the sale event metadata – will also impact commission earnings calculation (if a `Sale` `Product ID` modifier is set).",+ )+ .meta({ deprecated: true }),}),]).superRefine((data, ctx) => {@@ -609,6 +656,167 @@ export const createManualCommissionBodySchema = z}});+export const createManualCommissionBodySchema = createCommissionBodySchemaV2;++// z+// .discriminatedUnion("type", [+// // 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().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."),+// description: z+// .string()+// .max(190)+// .nullish()+// .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+// z.object({+// type: z.literal("lead"),+// partnerId: z+// .string()+// .describe("The ID of the partner to create the commission for."),+// customerId: z+// .string()+// .nullish()+// .describe(+// "The customer ID to associate the commission with. Useful if the customer was already created in a prior operation and you want to associate the commission with it.",+// ),+// customer: createCustomerBodySchema+// .nullish()+// .describe(+// "The full customer object to associate the commission with. Useful for creating the customer on demand.",+// ),+// linkId: z+// .string()+// .nullish()+// .describe(+// "The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",+// ),+// leadEventDate: parseDateSchema+// .nullish()+// .describe(+// "The date and time of the lead event. If not provided, defaults to the current date and time.",+// ),+// leadEventName: z+// .string()+// .nullish()+// .default("Sign up")+// .describe(+// "The name of the lead event. If not provided, defaults to 'Sign up'.",+// ),+// }),++// // Sale commission+// z.object({+// type: z.literal("sale"),+// partnerId: z+// .string()+// .describe("The ID of the partner to create the commission for."),+// customerId: z+// .string()+// .nullish()+// .describe(+// "The customer ID to associate the commission with. Useful if the customer was already created in a prior operation and you want to associate the commission with it.",+// ),+// customer: createCustomerBodySchema+// .nullish()+// .describe(+// "The full customer object to associate the commission with. Useful for creating the customer on demand.",+// ),+// linkId: z+// .string()+// .nullish()+// .describe(+// "The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",+// ),+// importStripeInvoices: z+// .boolean()+// .nullish()+// .default(false)+// .describe(+// "When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `saleAmount`.",+// ),+// saleAmount: centsSchema+// .pipe(z.number().min(0))+// .nullish()+// .describe(+// "Required when `importStripeInvoices` is `false`. The sale amount in cents for the manual sale event. Ignored when importing from Stripe.",+// ),+// saleEventDate: parseDateSchema+// .nullish()+// .describe(+// "Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",+// ),+// invoiceId: z+// .string()+// .nullish()+// .describe(+// "Only used when `importStripeInvoices` is `false`. An optional invoice ID to attach to the generated sale event and commission entry for deduplication.",+// ),+// productId: z+// .string()+// .nullish()+// .describe(+// "Only used when `importStripeInvoices` is `false`. An optional product ID stored on the sale event metadata – will also impact commission earnings calculation (if a `Sale` `Product ID` modifier is set).",+// ),+// }),+// ])+// .superRefine((data, ctx) => {+// if (data.type === "custom") {+// if (data.amount < 0 && !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") {+// if (data.importStripeInvoices) {+// return;+// }++// if (data.saleAmount == null) {+// ctx.addIssue({+// code: z.ZodIssueCode.custom,+// message:+// "`saleAmount` is required when `importStripeInvoices` is false.",+// path: ["saleAmount"],+// });+// return;+// }++// if (data.saleAmount === 0) {+// ctx.addIssue({+// code: z.ZodIssueCode.custom,+// message: "Sale amount cannot be 0.",+// path: ["saleAmount"],+// });+// }+// }+// });+export const createCommissionResponseSchema = z.object({success: z.boolean(),message: z.string(),diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.tsindex 2d1abdd75a..3a390d15d1 100644--- a/apps/web/lib/zod/schemas/leads.ts+++ b/apps/web/lib/zod/schemas/leads.ts@@ -3,6 +3,7 @@ import { clickEventSchema, clickEventSchemaTB } from "./clicks";import { CustomerSchema } from "./customers";import { commonDeprecatedEventFields } from "./deprecated";import { linkEventSchema, LinkSchema } from "./links";+import { metadataSchema } from "./misc";export const trackLeadRequestSchema = z.object({clickId: z@@ -62,16 +63,9 @@ export const trackLeadRequestSchema = z.object({.describe("The numerical value associated with this lead event (e.g., number of provisioned seats in a free trial). If defined as N, the lead event will be tracked N times.",),- metadata: z- .record(z.string(), z.any())- .nullish()- .default(null)- .refine((val) => !val || JSON.stringify(val).length <= 10000, {- message: "Metadata must be less than 10,000 characters when stringified",- })- .describe(- "Additional metadata to be stored with the lead event. Max 10,000 characters.",- ),+ metadata: metadataSchema.describe(+ "Additional metadata to be stored with the lead event. Max 10,000 characters.",+ ),});export const trackLeadResponseSchema = z.object({diff --git a/apps/web/lib/zod/schemas/misc.ts b/apps/web/lib/zod/schemas/misc.tsindex 8bde58e965..2e55ccd523 100644--- a/apps/web/lib/zod/schemas/misc.ts+++ b/apps/web/lib/zod/schemas/misc.ts@@ -93,3 +93,11 @@ export const getCursorPaginationQuerySchema = ({example,}),});++export const metadataSchema = z+ .record(z.string(), z.any())+ .nullish()+ .default(null)+ .refine((val) => !val || JSON.stringify(val).length <= 10000, {+ message: "Metadata must be less than 10,000 characters when stringified",+ });diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.tsindex c54f2add0c..df0f7f6c96 100644--- a/apps/web/lib/zod/schemas/sales.ts+++ b/apps/web/lib/zod/schemas/sales.ts@@ -3,6 +3,7 @@ import { clickEventSchema, clickEventSchemaTB } from "./clicks";import { CustomerSchema } from "./customers";import { commonDeprecatedEventFields } from "./deprecated";import { linkEventSchema } from "./links";+import { metadataSchema } from "./misc";import { centsSchema } from "./utils";export const trackSaleRequestSchema = z.object({@@ -57,16 +58,9 @@ export const trackSaleRequestSchema = z.object({.describe("The invoice ID of the sale. Can be used as a idempotency key – only one sale event can be recorded for a given invoice ID.",),- metadata: z- .record(z.string(), z.any())- .nullish()- .default(null)- .refine((val) => !val || JSON.stringify(val).length <= 10000, {- message: "Metadata must be less than 10,000 characters when stringified",- })- .describe(- "Additional metadata to be stored with the sale event. Max 10,000 characters when stringified.",- ),+ metadata: metadataSchema.describe(+ "Additional metadata to be stored with the sale event. Max 10,000 characters when stringified.",+ ),// advanced fields: leadEventName + fields for sale tracking without a lead eventleadEventName: z.string()diff --git a/apps/web/playwright/api/commissions/commissions.spec.ts b/apps/web/playwright/api/commissions/commissions.spec.tsnew file mode 100644index 0000000000..45a998ba1d--- /dev/null+++ b/apps/web/playwright/api/commissions/commissions.spec.ts@@ -0,0 +1,376 @@+import { createId } from "@/lib/api/create-id";+import { prisma } from "@/lib/prisma";+import { nanoid } from "@dub/utils";+import { expect } from "@playwright/test";+import { apiError, randomCustomer } from "../../utils";+import { test } from "../fixtures";+import { createPartner, deletePartner } from "../partners/helpers";+import {+ createPartnerWithCommissionRewards,+ deleteCommissionPartner,+ expectCommissionCreated,+ LEAD_REWARD_CENTS,+ SALE_REWARD_CENTS,+} from "./helpers";++const expectedQueuedResponse = {+ success: true,+ message: "Your commissions are being created and will appear shortly.",+};++const oversizedMetadata = {+ blob: "x".repeat(10_000),+};++test("POST /commissions – custom", async ({ api, program }) => {+ let partnerId: string | undefined;+ const description = `custom-${nanoid()}`;++ try {+ const { status: createStatus, data: created } = await createPartner(api, {+ groupId: program.defaultGroupId,+ });+ partnerId = created.id;+ expect(createStatus).toEqual(201);++ const { status, data } = await api.post("/api/commissions", {+ type: "custom",+ partnerId,+ amount: 500,+ description,+ });++ expect(status).toEqual(202);+ expect(data).toStrictEqual(expectedQueuedResponse);++ await expectCommissionCreated({+ partnerId: created.id,+ programId: program.id,+ type: "custom",+ description,+ expectedAmount: 0,+ expectedEarnings: 500,+ });+ } finally {+ await deletePartner(partnerId);+ }+});++test("POST /commissions – lead", async ({ api, program }) => {+ let partnerId: string | undefined;+ let groupId: string | undefined;+ const customer = randomCustomer();++ try {+ const created = await createPartnerWithCommissionRewards(api, {+ programId: program.id,+ });+ partnerId = created.data.id;+ groupId = created.groupId;+ expect(created.status).toEqual(201);++ const { status, data } = await api.post("/api/commissions", {+ type: "lead",+ partnerId,+ customer: {+ externalId: customer.externalId,+ email: customer.email,+ name: customer.name,+ country: "US",+ },+ });++ expect(status).toEqual(202);+ expect(data).toStrictEqual(expectedQueuedResponse);++ await expectCommissionCreated({+ partnerId: created.data.id,+ programId: program.id,+ type: "lead",+ expectedAmount: 0,+ expectedEarnings: LEAD_REWARD_CENTS,+ });+ } finally {+ await deleteCommissionPartner({ partnerId, groupId });+ }+});++test("POST /commissions – sale", async ({ api, program }) => {+ let partnerId: string | undefined;+ let groupId: string | undefined;+ const invoiceId = `INV_${nanoid()}`;+ const customer = randomCustomer();++ try {+ const created = await createPartnerWithCommissionRewards(api, {+ programId: program.id,+ });+ partnerId = created.data.id;+ groupId = created.groupId;+ expect(created.status).toEqual(201);++ const { status, data } = await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ saleAmount: 1000,+ invoiceId,+ customer: {+ externalId: customer.externalId,+ email: customer.email,+ name: customer.name,+ country: "US",+ },+ });++ expect(status).toEqual(202);+ expect(data).toStrictEqual(expectedQueuedResponse);++ await expectCommissionCreated({+ partnerId: created.data.id,+ programId: program.id,+ type: "sale",+ invoiceId,+ expectedAmount: 1000,+ expectedEarnings: SALE_REWARD_CENTS,+ });+ } finally {+ await deleteCommissionPartner({ partnerId, groupId });+ }+});++test("POST /commissions – customer not found", async ({ api, program }) => {+ let partnerId: string | undefined;++ try {+ const { status: createStatus, data: created } = await createPartner(api, {+ groupId: program.defaultGroupId,+ });+ partnerId = created.id;+ expect(createStatus).toEqual(201);++ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ customerId: "cus_nonexistent",+ saleAmount: 1000,+ }),+ ).toEqual(+ apiError({+ code: "not_found",+ message: "Customer cus_nonexistent not found.",+ }),+ );+ } finally {+ await deletePartner(partnerId);+ }+});++test("POST /commissions – duplicate invoiceId", async ({ api, program }) => {+ let partnerId: string | undefined;+ const invoiceId = `INV_${nanoid()}`;+ const customer = randomCustomer();++ try {+ const { status: createStatus, data: created } = await createPartner(api, {+ groupId: program.defaultGroupId,+ });+ partnerId = created.id;+ expect(createStatus).toEqual(201);++ await prisma.commission.create({+ data: {+ id: createId({ prefix: "cm_" }),+ programId: program.id,+ partnerId: created.id,+ type: "sale",+ amount: 1000,+ earnings: 100,+ quantity: 1,+ invoiceId,+ },+ });++ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ saleAmount: 1000,+ invoiceId,+ customer: {+ externalId: customer.externalId,+ email: customer.email,+ name: customer.name,+ country: "US",+ },+ }),+ ).toEqual(+ apiError({+ code: "conflict",+ message: `There is already a commission for the invoice ${invoiceId}.`,+ }),+ );+ } finally {+ await deleteCommissionPartner({ partnerId });+ }+});++const commissionErrorCases = [+ {+ name: "POST /commissions – missing type",+ body: { partnerId: "pn_test", amount: 500 },+ expected: apiError({+ code: "unprocessable_entity",+ message: "invalid_union: type: Invalid input",+ }),+ },+ {+ name: "POST /commissions – invalid type",+ body: { type: "invalid", partnerId: "pn_test" },+ expected: apiError({+ code: "unprocessable_entity",+ message: "invalid_union: type: Invalid input",+ }),+ },+ {+ name: "POST /commissions – custom amount 0",+ body: { type: "custom", partnerId: "pn_test", amount: 0 },+ expected: apiError({+ code: "unprocessable_entity",+ message: "custom: amount: Amount cannot be 0.",+ }),+ },+ {+ name: "POST /commissions – sale missing amount",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ importStripeInvoices: false,+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: sale.amount: `sale.amount` is required when `importStripeInvoices` is false.",+ }),+ },+ {+ name: "POST /commissions – saleAmount 0",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ importStripeInvoices: false,+ saleAmount: 0,+ },+ expected: apiError({+ code: "unprocessable_entity",+ message: "custom: saleAmount: Sale amount cannot be 0.",+ }),+ },+ {+ name: "POST /commissions – sale.amount 0",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ sale: { amount: 0 },+ },+ expected: apiError({+ code: "unprocessable_entity",+ message: "custom: sale.amount: Sale amount cannot be 0.",+ }),+ },+ {+ name: "POST /commissions – importStripeInvoices with sale",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ importStripeInvoices: true,+ sale: {},+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: sale: `sale`, `date`, `saleAmount`, `saleEventDate`, `invoiceId`, and `productId` cannot be provided when `importStripeInvoices` is enabled.",+ }),+ },+ {+ name: "POST /commissions – importStripeInvoices with date",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ importStripeInvoices: true,+ date: new Date().toISOString(),+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: date: `sale`, `date`, `saleAmount`, `saleEventDate`, `invoiceId`, and `productId` cannot be provided when `importStripeInvoices` is enabled.",+ }),+ },+ {+ name: "POST /commissions – invalid paymentProcessor",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ sale: { amount: 1000, paymentProcessor: "foo" },+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ 'invalid_value: sale.paymentProcessor: Invalid option: expected one of "stripe"|"shopify"|"polar"|"paddle"|"apple"|"revenuecat"|"dub"|"custom"',+ }),+ },+ {+ name: "POST /commissions – sale metadata too large",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ sale: { amount: 1000, metadata: oversizedMetadata },+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: sale.metadata: Metadata must be less than 10,000 characters when stringified",+ }),+ },+ {+ name: "POST /commissions – lead metadata too large",+ body: {+ type: "lead",+ partnerId: "pn_test",+ customerId: "cus_test",+ lead: { metadata: oversizedMetadata },+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: lead.metadata: Metadata must be less than 10,000 characters when stringified",+ }),+ },+ {+ name: "POST /commissions – custom metadata too large",+ body: {+ type: "custom",+ partnerId: "pn_test",+ amount: 500,+ metadata: oversizedMetadata,+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: metadata: Metadata must be less than 10,000 characters when stringified",+ }),+ },+];++for (const { name, body, expected } of commissionErrorCases) {+ test(name, async ({ api }) => {+ expect(await api.post("/api/commissions", body)).toEqual(expected);+ });+}diff --git a/apps/web/playwright/api/commissions/helpers.ts b/apps/web/playwright/api/commissions/helpers.tsnew file mode 100644index 0000000000..322d8606de--- /dev/null+++ b/apps/web/playwright/api/commissions/helpers.ts@@ -0,0 +1,217 @@+import { createId } from "@/lib/api/create-id";+import { prisma } from "@/lib/prisma";+import { DEFAULT_ADDITIONAL_PARTNER_LINKS } from "@/lib/zod/schemas/groups";+import { nanoid } from "@dub/utils";+import { expect } from "@playwright/test";+import { EventType, RewardStructure } from "@prisma/client";+import type { ApiClient } from "../fixtures";+import { createPartner, deletePartner } from "../partners/helpers";+import { TEST_WORKSPACE } from "../setup-test-workspace";++export const LEAD_REWARD_CENTS = 1000;+export const SALE_REWARD_CENTS = 2500;++export async function createPartnerWithCommissionRewards(+ api: ApiClient,+ { programId }: { programId: string },+) {+ const groupId = createId({ prefix: "grp_" });++ const [leadReward, saleReward] = await Promise.all([+ prisma.reward.create({+ data: {+ id: createId({ prefix: "rw_" }),+ programId,+ event: EventType.lead,+ type: RewardStructure.flat,+ amountInCents: LEAD_REWARD_CENTS,+ },+ }),+ prisma.reward.create({+ data: {+ id: createId({ prefix: "rw_" }),+ programId,+ event: EventType.sale,+ type: RewardStructure.flat,+ amountInCents: SALE_REWARD_CENTS,+ maxDuration: 0,+ },+ }),+ ]);++ await prisma.partnerGroup.create({+ data: {+ id: groupId,+ programId,+ slug: `pw-cm-${nanoid(8).toLowerCase()}`,+ name: "Playwright Commissions",+ maxPartnerLinks: DEFAULT_ADDITIONAL_PARTNER_LINKS,+ leadRewardId: leadReward.id,+ saleRewardId: saleReward.id,+ },+ });++ await prisma.partnerGroupDefaultLink.create({+ data: {+ id: createId({ prefix: "pgdl_" }),+ programId,+ groupId,+ domain: TEST_WORKSPACE.program.domain,+ url: TEST_WORKSPACE.program.url,+ },+ });++ const created = await createPartner(api, {+ groupId,+ });++ return {+ ...created,+ groupId,+ };+}++export async function deleteCommissionPartner({+ partnerId,+ groupId,+}: {+ partnerId: string | undefined;+ groupId?: string;+}) {+ if (partnerId) {+ const links = await prisma.link.findMany({+ where: {+ partnerId,+ },+ select: {+ id: true,+ },+ });++ await prisma.customer.deleteMany({+ where: {+ OR: [+ { partnerId },+ ...(links.length > 0+ ? [{ linkId: { in: links.map((link) => link.id) } }]+ : []),+ ],+ },+ });+ }++ await deletePartner(partnerId);++ if (!groupId) {+ return;+ }++ const group = await prisma.partnerGroup.findUnique({+ where: {+ id: groupId,+ },+ select: {+ leadRewardId: true,+ saleRewardId: true,+ },+ });++ if (!group) {+ return;+ }++ await prisma.partnerGroupDefaultLink.deleteMany({+ where: {+ groupId,+ },+ });++ await prisma.partnerGroup.update({+ where: {+ id: groupId,+ },+ data: {+ leadRewardId: null,+ saleRewardId: null,+ },+ });++ await prisma.partnerGroup.delete({+ where: {+ id: groupId,+ },+ });++ const rewardIds = [group.leadRewardId, group.saleRewardId].filter(+ (id): id is string => id != null,+ );++ if (rewardIds.length > 0) {+ await prisma.reward.deleteMany({+ where: {+ id: {+ in: rewardIds,+ },+ },+ });+ }+}++export async function expectCommissionCreated({+ partnerId,+ programId,+ type,+ description,+ invoiceId,+ expectedAmount,+ expectedEarnings,+}: {+ partnerId: string;+ programId: string;+ type: "custom" | "lead" | "sale";+ description?: string;+ invoiceId?: string;+ expectedAmount: number;+ expectedEarnings: number;+}) {+ await expect+ .poll(async () => {+ const commission = await prisma.commission.findFirst({+ where: {+ partnerId,+ programId,+ type,+ ...(description ? { description } : {}),+ ...(invoiceId ? { invoiceId } : {}),+ },+ 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,+ invoiceId: commission.invoiceId,+ };+ })+ .toEqual({+ partnerId,+ programId,+ type,+ amount: expectedAmount,+ earnings: expectedEarnings,+ quantity: 1,+ description: description ?? null,+ invoiceId: invoiceId ?? null,+ });+}diff --git a/apps/web/tests/commissions/create-commission.test.ts b/apps/web/tests/commissions/create-commission.test.tsdeleted file mode 100644index 941c92120e..0000000000--- a/apps/web/tests/commissions/create-commission.test.ts+++ /dev/null@@ -1,213 +0,0 @@-import { CommissionResponse } from "@/lib/types";-import { describe, expect, test } from "vitest";-import { randomCustomer, randomId } from "../utils/helpers";-import { IntegrationHarness } from "../utils/integration";-import {- E2E_CUSTOMER_ID,- E2E_LEAD_REWARD,- E2E_PARTNER,-} from "../utils/resource";-import { verifyCommission } from "../utils/verify-commission";--const expectedQueuedResponse = {- success: true,- message: "Your commissions are being created and will appear shortly.",-};--const validationCases = [- {- name: "missing type field",- body: { partnerId: E2E_PARTNER.id, amount: 500 },- expectedStatus: 422,- expectedMessage: "invalid_union: type: Invalid input",- },- {- name: "invalid type value",- body: { type: "invalid", partnerId: E2E_PARTNER.id },- expectedStatus: 422,- expectedMessage: "invalid_union: type: Invalid input",- },- {- name: "custom commission with amount 0",- body: { type: "custom", partnerId: E2E_PARTNER.id, amount: 0 },- expectedStatus: 422,- expectedMessage: "custom: amount: Amount cannot be 0.",- },- {- name: "sale commission missing saleAmount",- body: {- type: "sale",- partnerId: E2E_PARTNER.id,- customerId: E2E_CUSTOMER_ID,- importStripeInvoices: false,- },- expectedStatus: 422,- expectedMessage:- "custom: saleAmount: `saleAmount` is required when `importStripeInvoices` is false.",- },- {- name: "sale commission with saleAmount 0",- body: {- type: "sale",- partnerId: E2E_PARTNER.id,- customerId: E2E_CUSTOMER_ID,- importStripeInvoices: false,- saleAmount: 0,- },- expectedStatus: 422,- expectedMessage: "custom: saleAmount: Sale amount cannot be 0.",- },-];--validationCases.forEach(({ name, body, expectedStatus, expectedMessage }) => {- test(`POST /commissions - validation error: ${name}`, async (ctx) => {- const h = new IntegrationHarness(ctx);- const { http } = await h.init();- const response = await http.post<any>({ path: "/commissions", body });- expect(response.status).toEqual(expectedStatus);- expect(response.data.error.code).toEqual("unprocessable_entity");- expect(response.data.error.message).toEqual(expectedMessage);- });-});--describe.concurrent("POST /commissions", async () => {- const h = new IntegrationHarness();- const { http } = await h.init();-- test("create custom commission with required fields", async () => {- const description = randomId();- const { status, data } = await http.post<any>({- path: "/commissions",- body: {- type: "custom",- partnerId: E2E_PARTNER.id,- amount: 500,- description,- },- });-- expect(status).toEqual(202);- expect(data).toStrictEqual(expectedQueuedResponse);-- await verifyCommission({- http,- description,- expectedEarnings: 500,- expectedType: "custom",- query: {- partnerId: E2E_PARTNER.id,- type: "custom",- sortBy: "createdAt",- sortOrder: "desc",- },- });- });-- test("create lead commission", async () => {- const customer = randomCustomer();-- const { status, data } = await http.post<any>({- path: "/commissions",- body: {- type: "lead",- partnerId: E2E_PARTNER.id,- customer: {- externalId: customer.externalId,- email: customer.email,- name: customer.name,- country: "US",- },- },- });-- expect(status).toEqual(202);- expect(data).toStrictEqual(expectedQueuedResponse);-- await verifyCommission({- http,- customerExternalId: customer.externalId,- expectedEarnings: E2E_LEAD_REWARD.modifiers[1].amountInCents,- });- });-- test("create sale commission with a new customer", async () => {- const invoiceId = `INV_${randomId()}`;- const customer = randomCustomer();-- const { status, data } = await http.post<any>({- path: "/commissions",- body: {- type: "sale",- partnerId: E2E_PARTNER.id,- saleAmount: 1000,- invoiceId,- customer: {- externalId: customer.externalId,- email: customer.email,- name: customer.name,- country: "US",- },- },- });-- expect(status).toEqual(202);- expect(data).toStrictEqual(expectedQueuedResponse);-- await verifyCommission({- http,- invoiceId,- expectedSaleAmount: 1000,- expectedEarnings: 5000, // Earn $50 per sale for 3 months- });- });-- test("error when customer is not found", async () => {- const { status, data } = await http.post<any>({- path: "/commissions",- body: {- type: "sale",- partnerId: E2E_PARTNER.id,- customerId: "cus_nonexistent",- saleAmount: 1000,- },- });- expect(status).toEqual(404);- expect(data.error.code).toEqual("not_found");- expect(data.error.message).toContain("not found");- });-- test("error when invoiceId already exists", async () => {- const { data: existingCommissions } = await http.get<CommissionResponse[]>({- path: "/commissions",- query: {- type: "sale",- sortBy: "createdAt",- sortOrder: "desc",- pageSize: "50",- },- });-- const commissionWithInvoice = existingCommissions.find(- (c) => c.invoiceId != null,- );-- expect(commissionWithInvoice).toBeDefined();-- const { status, data } = await http.post<any>({- path: "/commissions",- body: {- type: "sale",- partnerId: E2E_PARTNER.id,- saleAmount: 1000,- invoiceId: commissionWithInvoice!.invoiceId,- customerId: E2E_CUSTOMER_ID,- },- });-- expect(status).toEqual(409);- expect(data.error.code).toEqual("conflict");- expect(data.error.message).toContain(- "There is already a commission for the invoice",- );- });-});