The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
allow creating sale commissions by discount code
Pedro Ladeirac53cd2371556
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.tsindex 6998a52aa9..53f08033b7 100644--- a/apps/web/lib/api/commissions/create-manual-commissions.ts+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts@@ -259,7 +259,9 @@ async function resolveLinkAndCustomer(args: ResolveLinkAndCustomerArgs) {let targetLink: Link;let targetCustomer: Customer | null = null;- const { workspace, partner, links, linkId, customerId, customer } = args;+ const { workspace, partner, links, programId, linkId, customerId, customer } =+ args;+ const discountCode = type === "sale" ? args.discountCode : undefined;if (links.length === 0) {throw new DubApiError({@@ -282,13 +284,49 @@ async function resolveLinkAndCustomer(args: ResolveLinkAndCustomerArgs) {});}- if (linkId) {- const link = links.find((l) => l.id === linkId);+ let resolvedLinkId = linkId ?? null;++ if (discountCode) {+ const found = await prisma.discountCode.findUnique({+ where: {+ programId_code: {+ programId,+ code: discountCode,+ },+ },+ });++ if (!found) {+ throw new DubApiError({+ code: "not_found",+ message: `Discount code ${discountCode} not found.`,+ });+ }++ if (found.partnerId !== partner.id) {+ throw new DubApiError({+ code: "not_found",+ message: `Discount code ${discountCode} does not belong to partner ${partner.email} (${partner.id}).`,+ });+ }++ if (found.disabledAt) {+ throw new DubApiError({+ code: "bad_request",+ message: `Discount code ${discountCode} is disabled.`,+ });+ }++ resolvedLinkId = found.linkId;+ }++ if (resolvedLinkId) {+ const link = links.find((l) => l.id === resolvedLinkId);if (!link) {throw new DubApiError({code: "not_found",- message: `Link ${linkId} does not belong to partner ${partner.email} (${partner.id}).`,+ message: `Link ${resolvedLinkId} does not belong to partner ${partner.email} (${partner.id}).`,});}diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex d4cf40b96b..9842ae68bb 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -625,7 +625,13 @@ const createSaleCommissionSchema = z.string().nullish().describe(- "The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",+ "The partner link ID to associate the commission with. If neither `linkId` nor `discountCode` is provided, default to the link with the most revenue.",+ ),+ discountCode: z+ .string()+ .nullish()+ .describe(+ "The partner discount code to resolve the associated link. Use this when the link ID is unknown. Cannot be provided together with `linkId`.",),importStripeInvoices: z.boolean()@@ -736,6 +742,15 @@ export const createManualCommissionBodySchema = zpath: ["description"],});}+ return;+ }++ if (data.type === "sale" && data.linkId && data.discountCode) {+ ctx.addIssue({+ code: "custom",+ message: "Either `linkId` or `discountCode` may be provided, not both.",+ path: ["discountCode"],+ });}});diff --git a/apps/web/playwright/api/commissions/commissions-create.spec.ts b/apps/web/playwright/api/commissions/commissions-create.spec.tsindex da07659ceb..75e0bb7f90 100644--- a/apps/web/playwright/api/commissions/commissions-create.spec.ts+++ b/apps/web/playwright/api/commissions/commissions-create.spec.ts@@ -40,6 +40,40 @@ function customerBody() {};}+async function seedDiscountCode({+ programId,+ partnerId,+ disabledAt,+}: {+ programId: string;+ partnerId: string;+ disabledAt?: Date;+}) {+ const link = await prisma.link.findFirst({+ where: { partnerId },+ orderBy: { createdAt: "asc" },+ });++ if (!link) {+ throw new Error("Partner was created without a default link.");+ }++ const code = `PW${nanoid(8)}`;++ await prisma.discountCode.create({+ data: {+ id: createId({ prefix: "dcode_" }),+ code,+ programId,+ partnerId,+ linkId: link.id,+ disabledAt,+ },+ });++ return { code, linkId: link.id };+}+test.describe("Custom commissions", () => {test("creates a custom commission", async ({ api, program }) => {const description = `custom-${nanoid()}`;@@ -293,6 +327,38 @@ test.describe("Sale commissions", () => {});});+ test("creates using discountCode", async ({ api, program }) => {+ const invoiceId = `INV_${nanoid()}`;++ await withCommissionPartner(api, program, async (partnerId) => {+ const { code, linkId } = await seedDiscountCode({+ programId: program.id,+ partnerId,+ });++ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ discountCode: code,+ saleAmount: 1000,+ invoiceId,+ customer: customerBody(),+ }),+ ).toEqual(expectedQueuedResponse);++ await expectCommissionCreated({+ api,+ partnerId,+ programId: program.id,+ type: "sale",+ invoiceId,+ expectedLinkId: linkId,+ expectedMetadata: null,+ });+ });+ });+test("creates using nested sale", async ({ api, program }) => {const invoiceId = `INV_${nanoid()}`;const date = new Date("2024-02-20T00:00:00.000Z");@@ -804,6 +870,22 @@ test.describe("Sale commissions", () => {"custom: sale.metadata: Metadata must be less than 10,000 characters when stringified",}),},+ {+ name: "rejects linkId and discountCode together",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ saleAmount: 1000,+ linkId: "link_test",+ discountCode: "SAVE10",+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: discountCode: Either `linkId` or `discountCode` may be provided, not both.",+ }),+ },];for (const { name, body, expected } of errorCases) {@@ -829,6 +911,83 @@ test.describe("Sale commissions", () => {);});});++ test("rejects unknown discountCode", async ({ api, program }) => {+ await withCommissionPartner(api, program, async (partnerId) => {+ const code = `MISSING${nanoid(8)}`;++ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ discountCode: code,+ saleAmount: 1000,+ customer: customerBody(),+ }),+ ).toEqual(+ apiError({+ code: "not_found",+ message: `Discount code ${code} not found.`,+ }),+ );+ });+ });++ test("rejects another partner's discountCode", async ({ api, program }) => {+ await withCommissionPartner(api, program, async (partnerId) => {+ await withCommissionPartner(api, program, async (otherPartnerId) => {+ const { code } = await seedDiscountCode({+ programId: program.id,+ partnerId: otherPartnerId,+ });++ const partner = await prisma.partner.findUniqueOrThrow({+ where: { id: partnerId },+ select: { id: true, email: true },+ });++ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ discountCode: code,+ saleAmount: 1000,+ customer: customerBody(),+ }),+ ).toEqual(+ apiError({+ code: "not_found",+ message: `Discount code ${code} does not belong to partner ${partner.email} (${partner.id}).`,+ }),+ );+ });+ });+ });++ test("rejects disabled discountCode", async ({ api, program }) => {+ await withCommissionPartner(api, program, async (partnerId) => {+ const { code } = await seedDiscountCode({+ programId: program.id,+ partnerId,+ disabledAt: new Date(),+ });++ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ discountCode: code,+ saleAmount: 1000,+ customer: customerBody(),+ }),+ ).toEqual(+ apiError({+ code: "bad_request",+ message: `Discount code ${code} is disabled.`,+ }),+ );+ });+ });});});diff --git a/apps/web/playwright/api/commissions/helpers.ts b/apps/web/playwright/api/commissions/helpers.tsindex 1252491b01..3c13aa1b8e 100644--- a/apps/web/playwright/api/commissions/helpers.ts+++ b/apps/web/playwright/api/commissions/helpers.ts@@ -65,6 +65,7 @@ export async function expectCommissionCreated({expectedEarnings,expectedCreatedAt,expectedMetadata,+ expectedLinkId,}: {api: ApiClient;partnerId: string;@@ -76,6 +77,7 @@ export async function expectCommissionCreated({expectedEarnings?: number;expectedCreatedAt?: Date;expectedMetadata?: Record<string, unknown> | null;+ expectedLinkId?: string;}): Promise<string> {const amount =expectedAmount ?? (type === "lead" ? 0 : type === "sale" ? 1000 : 0);@@ -86,8 +88,7 @@ export async function expectCommissionCreated({: type === "sale"? TEST_COMMISSION_REWARDS.sale.amountInCents: 0);- const metadata =- expectedMetadata === undefined ? null : expectedMetadata;+ const metadata = expectedMetadata === undefined ? null : expectedMetadata;let commissionId: string | undefined;@@ -124,6 +125,7 @@ export async function expectCommissionCreated({currency: commission.currency,createdAt: commission.createdAt.toISOString(),metadata: commission.metadata,+ ...(expectedLinkId !== undefined ? { linkId: commission.linkId } : {}),};}).toEqual({@@ -140,6 +142,7 @@ export async function expectCommissionCreated({? expectedCreatedAt.toISOString(): expect.any(String),metadata,+ ...(expectedLinkId !== undefined ? { linkId: expectedLinkId } : {}),});if (!commissionId) {