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.

Add custom discount code webhooks, update helper, and API tests

Kiran Kac7833fae42f
diff --git a/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts b/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts
index b8dc4f672a..bd58cb109f 100644
--- a/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts
+++ b/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts
@@ -1,18 +1,15 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
-import { DubApiError } from "@/lib/api/errors";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { getDiscountCodeOrThrow } from "@/lib/discount-codes/get-discount-code-or-throw";
import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";
-import { sendDiscountCodeWebhook } from "@/lib/discounts/discount-code-webhook";
+import { updateDiscountCode } from "@/lib/discounts/update-discount-code";
import { prisma } from "@/lib/prisma";
import {
DiscountCodeSchema,
updateDiscountCodeSchema,
} from "@/lib/zod/schemas/discount";
-import { APP_DOMAIN } from "@dub/utils";
-import { DiscountProvider, Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -76,111 +73,31 @@ export const PATCH = withWorkspace(
programId,
});
- if (discountCode.discount.provider !== DiscountProvider.custom) {
- throw new DubApiError({
- code: "bad_request",
- message: `This operation is only available for "custom" discount provider.`,
- });
- }
-
const { code: newCode } = updateDiscountCodeSchema.parse(
await parseRequestBody(req),
);
- if (newCode !== discountCode.code) {
- const duplicateByCode = await prisma.discountCode.findUnique({
- where: {
- programId_code: {
- programId,
- code: newCode,
- },
- },
- include: {
- partner: true,
- },
- });
-
- if (duplicateByCode) {
- throw new DubApiError({
- code: "conflict",
- message: `This discount code "${newCode}" is already in use by [${duplicateByCode.partner.email}](${APP_DOMAIN}/${workspace.slug}/program/partners/${duplicateByCode.partner.id}). Please choose a different code.`,
- });
- }
- }
-
- let updatedDiscountCode: Prisma.DiscountCodeGetPayload<{
- include: { discount: true };
- }>;
-
- try {
- updatedDiscountCode = await prisma.discountCode.update({
- where: {
- id: discountCodeId,
- },
- data: {
- code: newCode,
- },
- include: {
- discount: true,
- },
- });
- } catch (error) {
- if (
- error instanceof Prisma.PrismaClientKnownRequestError &&
- error.code === "P2002"
- ) {
- const duplicateByCode = await prisma.discountCode.findUnique({
- where: {
- programId_code: {
- programId,
- code: newCode,
- },
- },
- include: {
- partner: {
- select: {
- email: true,
- id: true,
- },
- },
- },
- });
-
- throw new DubApiError({
- code: "conflict",
- message: duplicateByCode
- ? `This discount code "${newCode}" is already in use by [${duplicateByCode.partner.email}](${APP_DOMAIN}/${workspace.slug}/program/partners/${duplicateByCode.partner.id}). Please choose a different code.`
- : `This discount code "${newCode}" is already in use. Please choose a different code.`,
- });
- }
-
- throw error;
- }
+ const updatedDiscountCode = await updateDiscountCode({
+ workspace,
+ discountCode,
+ newCode,
+ });
waitUntil(
- Promise.allSettled([
- recordAuditLog({
- workspaceId: workspace.id,
- programId,
- action: "discount_code.updated",
- description: `Discount code (${updatedDiscountCode.code}) updated`,
- actor: session.user,
- targets: [
- {
- type: "discount_code",
- id: updatedDiscountCode.id,
- metadata: updatedDiscountCode,
- },
- ],
- }),
-
- sendDiscountCodeWebhook({
- trigger: "discount_code.updated",
- workspaceId: workspace.id,
- programId,
- data: updatedDiscountCode,
- }),
- ]),
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "discount_code.updated",
+ description: `Discount code (${updatedDiscountCode.code}) updated`,
+ actor: session.user,
+ targets: [
+ {
+ type: "discount_code",
+ id: updatedDiscountCode.id,
+ metadata: updatedDiscountCode,
+ },
+ ],
+ }),
);
return NextResponse.json(DiscountCodeSchema.parse(updatedDiscountCode));
diff --git a/apps/web/lib/discounts/create-discount-code.ts b/apps/web/lib/discounts/create-discount-code.ts
index d6d5b02c01..6a3e2b007e 100644
--- a/apps/web/lib/discounts/create-discount-code.ts
+++ b/apps/web/lib/discounts/create-discount-code.ts
@@ -2,11 +2,16 @@ import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { prisma } from "@/lib/prisma";
import { Discount, Link, Partner, Prisma, Project } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
import { constructDiscountCode } from "./construct-discount-code";
+import { sendDiscountCodeWebhook } from "./discount-code-webhook";
import { getDiscountProvider } from "./discount-provider";
interface CreateDiscountCodeArgs {
- workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;
+ workspace: Pick<
+ Project,
+ "id" | "stripeConnectId" | "shopifyStoreId" | "webhookEnabled"
+ >;
partner: Pick<Partner, "id" | "name">;
link: Pick<Link, "id">;
discount: Discount;
@@ -48,8 +53,12 @@ export async function createDiscountCode({
shouldRetry: code ? false : true,
});
+ let discountCode: Prisma.DiscountCodeGetPayload<{
+ include: { discount: true };
+ }>;
+
try {
- return await prisma.discountCode.create({
+ discountCode = await prisma.discountCode.create({
data: {
id: createId({ prefix: "dcode_" }),
code: externalDiscountCode.code,
@@ -58,6 +67,9 @@ export async function createDiscountCode({
linkId: link.id,
discountId: discount.id,
},
+ include: {
+ discount: true,
+ },
});
} catch (error) {
try {
@@ -85,4 +97,14 @@ export async function createDiscountCode({
throw error;
}
+
+ waitUntil(
+ sendDiscountCodeWebhook({
+ trigger: "discount_code.created",
+ data: discountCode,
+ workspace,
+ }),
+ );
+
+ return discountCode;
}
diff --git a/apps/web/lib/discounts/delete-discount-code.ts b/apps/web/lib/discounts/delete-discount-code.ts
index 3594084d77..72d8c5d374 100644
--- a/apps/web/lib/discounts/delete-discount-code.ts
+++ b/apps/web/lib/discounts/delete-discount-code.ts
@@ -104,3 +104,5 @@ export async function enqueueDeleteDiscountCode(
);
}
}
+
+// TODO: Send webhook when a discount code is deleted
diff --git a/apps/web/lib/discounts/discount-code-webhook.ts b/apps/web/lib/discounts/discount-code-webhook.ts
new file mode 100644
index 0000000000..1b34e0291b
--- /dev/null
+++ b/apps/web/lib/discounts/discount-code-webhook.ts
@@ -0,0 +1,28 @@
+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
+import { DiscountCodeWebhookSchema } from "@/lib/zod/schemas/discount";
+import { DiscountProvider, Project } from "@prisma/client";
+import * as z from "zod/v4";
+
+export async function sendDiscountCodeWebhook({
+ trigger,
+ data,
+ workspace,
+}: {
+ trigger:
+ | "discount_code.created"
+ | "discount_code.updated"
+ | "discount_code.deleted";
+ data: z.infer<typeof DiscountCodeWebhookSchema>;
+ workspace: Pick<Project, "id" | "webhookEnabled">;
+}) {
+ // Only send webhook for custom discount provider for now
+ if (data.discount?.provider !== DiscountProvider.custom) {
+ return;
+ }
+
+ await sendWorkspaceWebhook({
+ trigger,
+ workspace,
+ data: DiscountCodeWebhookSchema.parse(data),
+ });
+}
diff --git a/apps/web/lib/discounts/discount-provider-custom.ts b/apps/web/lib/discounts/discount-provider-custom.ts
new file mode 100644
index 0000000000..10a73e40c6
--- /dev/null
+++ b/apps/web/lib/discounts/discount-provider-custom.ts
@@ -0,0 +1,31 @@
+function createCustomDiscountProvider() {
+ const getCoupon = async () => {
+ throw new Error("Custom discount provider does not support this method.");
+ };
+
+ const createCoupon = async () => {
+ throw new Error("Custom discount provider does not support this method.");
+ };
+
+ const createDiscountCode = async ({ code }: { code: string }) => {
+ return { code };
+ };
+
+ const disableDiscountCode = async () => {
+ // Dub is the source of truth; external apps disable coupons via webhook.
+ };
+
+ const assertDiscountIntegration = async () => {
+ // Custom discounts do not require Stripe or Shopify.
+ };
+
+ return {
+ getCoupon,
+ createCoupon,
+ createDiscountCode,
+ disableDiscountCode,
+ assertDiscountIntegration,
+ };
+}
+
+export const customDiscountProvider = createCustomDiscountProvider();
diff --git a/apps/web/lib/discounts/update-discount-code.ts b/apps/web/lib/discounts/update-discount-code.ts
new file mode 100644
index 0000000000..b1192733b7
--- /dev/null
+++ b/apps/web/lib/discounts/update-discount-code.ts
@@ -0,0 +1,110 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getDiscountCodeOrThrow } from "@/lib/discount-codes/get-discount-code-or-throw";
+import { prisma } from "@/lib/prisma";
+import { DiscountProvider, Prisma, Project } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { sendDiscountCodeWebhook } from "./discount-code-webhook";
+
+interface UpdateDiscountCodeArgs {
+ workspace: Pick<Project, "id" | "webhookEnabled">;
+ discountCode: Awaited<ReturnType<typeof getDiscountCodeOrThrow>>;
+ newCode: string;
+}
+
+export async function updateDiscountCode({
+ workspace,
+ discountCode,
+ newCode,
+}: UpdateDiscountCodeArgs) {
+ if (discountCode.discount.provider !== DiscountProvider.custom) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `This operation is only available for "custom" discount provider.`,
+ });
+ }
+
+ if (newCode !== discountCode.code) {
+ await assertDiscountCodeAvailable({
+ programId: discountCode.programId,
+ code: newCode,
+ });
+ }
+
+ let updatedDiscountCode: Prisma.DiscountCodeGetPayload<{
+ include: { discount: true };
+ }>;
+
+ try {
+ updatedDiscountCode = await prisma.discountCode.update({
+ where: {
+ id: discountCode.id,
+ },
+ data: {
+ code: newCode,
+ },
+ include: {
+ discount: true,
+ },
+ });
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ await assertDiscountCodeAvailable({
+ programId: discountCode.programId,
+ code: newCode,
+ });
+
+ throw new DubApiError({
+ code: "conflict",
+ message: `This discount code "${newCode}" is already in use. Please choose a different code.`,
+ });
+ }
+
+ throw error;
+ }
+
+ waitUntil(
+ sendDiscountCodeWebhook({
+ trigger: "discount_code.updated",
+ data: updatedDiscountCode,
+ workspace,
+ }),
+ );
+
+ return updatedDiscountCode;
+}
+
+async function assertDiscountCodeAvailable({
+ programId,
+ code,
+}: {
+ programId: string;
+ code: string;
+}) {
+ const duplicateByCode = await prisma.discountCode.findUnique({
+ where: {
+ programId_code: {
+ programId,
+ code,
+ },
+ },
+ select: {
+ partner: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ if (!duplicateByCode) {
+ return;
+ }
+
+ throw new DubApiError({
+ code: "conflict",
+ message: `This discount code "${code}" is already in use by partner "${duplicateByCode.partner.email}". Please choose a different code.`,
+ });
+}
diff --git a/apps/web/lib/integrations/slack/transform.ts b/apps/web/lib/integrations/slack/transform.ts
index f3288b5255..921901ac84 100644
--- a/apps/web/lib/integrations/slack/transform.ts
+++ b/apps/web/lib/integrations/slack/transform.ts
@@ -10,6 +10,7 @@ import {
BountyEventWebhookPayload,
ClickEventWebhookPayload,
CommissionEventWebhookPayload,
+ DiscountCodeEventWebhookPayload,
LeadEventWebhookPayload,
PartnerApplicationWebhookPayload,
PartnerEventWebhookPayload,
@@ -596,6 +597,45 @@ const payoutConfirmedTemplate = ({
};
};
+const discountCodeTemplates = ({
+ data,
+ event,
+}: {
+ data: DiscountCodeEventWebhookPayload;
+ event: WebhookTrigger;
+}) => {
+ const eventMessages = {
+ "discount_code.created": "*Discount code created* :ticket:",
+ "discount_code.updated": "*Discount code updated* :ticket:",
+ "discount_code.deleted": "*Discount code deleted* :ticket:",
+ };
+
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: eventMessages[event as keyof typeof eventMessages],
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Code*\n${data.code}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Partner ID*\n${data.partnerId}`,
+ },
+ ],
+ },
+ ],
+ };
+};
+
const slackTemplates: Record<WebhookTrigger, any> = {
"link.created": linkTemplates,
"link.updated": linkTemplates,
@@ -609,6 +649,9 @@ const slackTemplates: Record<WebhookTrigger, any> = {
"bounty.created": bountyTemplates,
"bounty.updated": bountyTemplates,
"payout.confirmed": payoutConfirmedTemplate,
+ "discount_code.created": discountCodeTemplates,
+ "discount_code.updated": discountCodeTemplates,
+ "discount_code.deleted": discountCodeTemplates,
};
export const formatEventForSlack = (
@@ -625,9 +668,14 @@ export const formatEventForSlack = (
event,
);
const isBountyEvent = ["bounty.created", "bounty.updated"].includes(event);
+ const isDiscountCodeEvent = [
+ "discount_code.created",
+ "discount_code.updated",
+ "discount_code.deleted",
+ ].includes(event);
return template({
data,
- ...((isLinkEvent || isBountyEvent) && { event }),
+ ...((isLinkEvent || isBountyEvent || isDiscountCodeEvent) && { event }),
});
};
diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.ts
index 0894da4c82..d9541bb38f 100644
--- a/apps/web/lib/zod/schemas/discount.ts
+++ b/apps/web/lib/zod/schemas/discount.ts
@@ -33,7 +33,7 @@ export const createDiscountSchema = z.object({
amount: z.number().min(0),
type: z.enum(RewardStructure).default("flat"),
maxDuration: maxDurationSchema,
- couponId: z.string(),
+ couponId: z.string().optional(),
couponTestId: z.string().nullish(),
groupId: z.string(),
autoProvision: z.boolean().optional(),
@@ -90,17 +90,19 @@ export const DiscountCodeSchema = z
title: "DiscountCode",
});
+const discountCodeValueSchema = z
+ .string()
+ .trim()
+ .max(100, "Code must be 100 characters or fewer.")
+ .regex(
+ /^[a-zA-Z0-9\-_]+$/,
+ "Code can only contain letters, numbers, dashes, and underscores.",
+ );
+
export const createDiscountCodeSchema = z.object({
code: z.preprocess(
(val) => (typeof val === "string" && val.trim() === "" ? undefined : val),
- z
- .string()
- .trim()
- .max(100, "Code must be 100 characters or fewer.")
- .regex(
- /^[a-zA-Z0-9\-_]+$/,
- "Code can only contain letters, numbers, dashes, and underscores.",
- )
+ discountCodeValueSchema
.optional()
.describe(
"The discount code to create. If omitted, a unique code will be generated automatically from the partner's name.",
@@ -116,8 +118,36 @@ export const createDiscountCodeSchema = z.object({
),
});
-export const getDiscountCodesQuerySchema = z.object({
- partnerId: z
- .string()
- .describe("The ID of the partner to retrieve discount codes for."),
+export const updateDiscountCodeSchema = z.object({
+ code: discountCodeValueSchema.describe(
+ "The updated discount code. Only available for custom discount providers.",
+ ),
+});
+
+export const getDiscountCodesQuerySchema = z
+ .object({
+ partnerId: z
+ .string()
+ .optional()
+ .describe(
+ "The ID of the partner to retrieve discount codes for. If omitted, returns discount codes for the whole program.",
+ ),
+ discountId: z
+ .string()
+ .optional()
+ .describe("Filter discount codes by discount ID."),
+ })
+ .extend(getPaginationQuerySchema({ pageSize: 100 }));
+
+// Schema for the discount code webhook
+export const DiscountCodeWebhookSchema = DiscountCodeSchema.omit({
+ discountId: true,
+}).extend({
+ discount: DiscountSchema.pick({
+ id: true,
+ amount: true,
+ type: true,
+ maxDuration: true,
+ provider: true,
+ }).nullable(),
});
diff --git a/apps/web/playwright/api/discount-codes/discount-codes.spec.ts b/apps/web/playwright/api/discount-codes/discount-codes.spec.ts
new file mode 100644
index 0000000000..050f9dbb5d
--- /dev/null
+++ b/apps/web/playwright/api/discount-codes/discount-codes.spec.ts
@@ -0,0 +1,499 @@
+import { createId } from "@/lib/api/create-id";
+import { conn } from "@/lib/planetscale";
+import { prisma } from "@/lib/prisma";
+import type { EnrolledPartnerProps } from "@/lib/types";
+import { DiscountCodeSchema } from "@/lib/zod/schemas/discount";
+import { DEFAULT_ADDITIONAL_PARTNER_LINKS } from "@/lib/zod/schemas/groups";
+import { nanoid } from "@dub/utils";
+import { expect } from "@playwright/test";
+import { DiscountProvider, RewardStructure } from "@prisma/client";
+import * as z from "zod/v4";
+import { randomName, randomPartnerEmail } from "../../utils";
+import { test, type ApiClient } from "../fixtures";
+import { TEST_WORKSPACE } from "../setup-test-workspace";
+
+type DiscountCode = z.infer<typeof DiscountCodeSchema>;
+
+test.describe.configure({
+ mode: "parallel",
+});
+
+const customDiscount = {
+ amount: 10,
+ type: RewardStructure.percentage,
+ maxDuration: 6,
+ provider: DiscountProvider.custom,
+};
+
+const expectedDiscountShape = {
+ id: expect.any(String),
+ ...customDiscount,
+};
+
+let customDiscountId: string | undefined;
+let partnerGroupId: string | undefined;
+
+test.beforeAll(async ({ program }) => {
+ const discount = await prisma.discount.create({
+ data: {
+ id: createId({ prefix: "disc_" }),
+ programId: program.id,
+ ...customDiscount,
+ },
+ });
+
+ const group = await prisma.partnerGroup.create({
+ data: {
+ id: createId({ prefix: "grp_" }),
+ programId: program.id,
+ slug: `pw-dcode-${nanoid(8).toLowerCase()}`,
+ name: "Playwright Discount Codes",
+ maxPartnerLinks: DEFAULT_ADDITIONAL_PARTNER_LINKS,
+ discountId: discount.id,
+ },
+ });
+
+ await prisma.partnerGroupDefaultLink.create({
+ data: {
+ id: createId({ prefix: "pgdl_" }),
+ programId: program.id,
+ groupId: group.id,
+ domain: TEST_WORKSPACE.program.domain,
+ url: TEST_WORKSPACE.program.url,
+ },
+ });
+
+ partnerGroupId = group.id;
+ customDiscountId = discount.id;
+});
+
+test.afterAll(async () => {
+ if (partnerGroupId) {
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId: partnerGroupId,
+ },
+ select: {
+ partnerId: true,
+ },
+ });
+
+ for (const enrollment of programEnrollments) {
+ await deletePartner(enrollment.partnerId);
+ }
+
+ await prisma.partnerGroupDefaultLink.deleteMany({
+ where: {
+ groupId: partnerGroupId,
+ },
+ });
+
+ await prisma.partnerGroup.delete({
+ where: {
+ id: partnerGroupId,
+ },
+ });
+ }
+
+ if (customDiscountId) {
+ await prisma.discountCode.deleteMany({
+ where: {
+ discountId: customDiscountId,
+ },
+ });
+
+ await prisma.programEnrollment.updateMany({
+ where: {
+ discountId: customDiscountId,
+ },
+ data: {
+ discountId: null,
+ },
+ });
+
+ await prisma.discount.delete({
+ where: {
+ id: customDiscountId,
+ },
+ });
+ }
+});
+
+async function createPartner(api: ApiClient) {
+ if (!partnerGroupId) {
+ throw new Error("Custom discount group was not seeded.");
+ }
+
+ return api.post<EnrolledPartnerProps>("/api/partners", {
+ name: randomName(),
+ email: randomPartnerEmail(),
+ groupId: partnerGroupId,
+ });
+}
+
+async function deletePartner(partnerId: string | undefined) {
+ if (!partnerId) return;
+
+ await prisma.discountCode.deleteMany({
+ where: {
+ partnerId,
+ },
+ });
+
+ await prisma.link.deleteMany({
+ where: {
+ partnerId,
+ },
+ });
+
+ await prisma.programEnrollment.deleteMany({
+ where: {
+ partnerId,
+ },
+ });
+
+ await conn.execute(`DELETE FROM Partner WHERE id = ?`, [partnerId]);
+}
+
+async function createDiscountCode(
+ api: ApiClient,
+ overrides: Record<string, unknown> = {},
+) {
+ const { data: partner } = await createPartner(api);
+ const linkId = partner.links?.[0]?.id;
+
+ if (!linkId) {
+ throw new Error("Partner was created without a default link.");
+ }
+
+ const body = {
+ partnerId: partner.id,
+ linkId,
+ code: `PW${nanoid(8)}`,
+ ...overrides,
+ };
+
+ const response = await api.post<DiscountCode>("/api/discount-codes", body);
+
+ return { partner, linkId, body, ...response };
+}
+
+test("POST /discount-codes", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const { status, data, partner, body } = await createDiscountCode(api);
+ partnerId = partner.id;
+
+ expect(status).toEqual(200);
+ expect(DiscountCodeSchema.parse(data)).toMatchObject({
+ id: expect.any(String),
+ code: body.code,
+ partnerId: partner.id,
+ linkId: body.linkId,
+ disabledAt: null,
+ discount: expectedDiscountShape,
+ });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /discount-codes – omits code and auto-generates", async ({
+ api,
+}) => {
+ let partnerId: string | undefined;
+
+ try {
+ const { data: partner } = await createPartner(api);
+ partnerId = partner.id;
+ const linkId = partner.links?.[0]?.id;
+
+ const { status, data } = await api.post<DiscountCode>(
+ "/api/discount-codes",
+ {
+ partnerId: partner.id,
+ linkId,
+ },
+ );
+
+ expect(status).toEqual(200);
+ expect(data.code).toEqual(expect.any(String));
+ expect(data.code.length).toBeGreaterThan(0);
+ expect(data.partnerId).toEqual(partner.id);
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /discount-codes – same link", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const created = await createDiscountCode(api);
+ partnerId = created.partner.id;
+
+ const { status, data } = await api.post("/api/discount-codes", {
+ partnerId: created.partner.id,
+ linkId: created.linkId,
+ code: `PW${nanoid(8)}`,
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toEqual({
+ error: {
+ code: "bad_request",
+ message: `This link already has a discount code (${created.data.code}) assigned.`,
+ doc_url: "https://dub.co/docs/api-reference/errors#bad-request",
+ },
+ });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("POST /discount-codes – duplicate code", async ({ api }) => {
+ let partnerIdA: string | undefined;
+ let partnerIdB: string | undefined;
+
+ try {
+ const first = await createDiscountCode(api);
+ partnerIdA = first.partner.id;
+
+ const { data: partnerB } = await createPartner(api);
+ partnerIdB = partnerB.id;
+
+ const { status, data } = await api.post("/api/discount-codes", {
+ partnerId: partnerB.id,
+ linkId: partnerB.links?.[0]?.id,
+ code: first.body.code,
+ });
+
+ expect(status).toEqual(409);
+ expect(data).toMatchObject({
+ error: {
+ code: "conflict",
+ message: expect.stringContaining(
+ `This discount code "${first.body.code}" is already in use`,
+ ),
+ doc_url: "https://dub.co/docs/api-reference/errors#conflict",
+ },
+ });
+ } finally {
+ await deletePartner(partnerIdA);
+ await deletePartner(partnerIdB);
+ }
+});
+
+const invalidCodeCases = [
+ {
+ name: "POST /discount-codes – invalid characters",
+ code: "NOT VALID!",
+ message:
+ "invalid_format: code: Code can only contain letters, numbers, dashes, and underscores.",
+ },
+ {
+ name: "POST /discount-codes – too long",
+ code: "A".repeat(101),
+ message: "too_big: code: Code must be 100 characters or fewer.",
+ },
+];
+
+for (const { name, code, message } of invalidCodeCases) {
+ test(name, async ({ api }) => {
+ expect(
+ await api.post("/api/discount-codes", {
+ partnerId: "pn_x",
+ linkId: "link_x",
+ code,
+ }),
+ ).toEqual({
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message,
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ });
+ });
+}
+
+test("POST /discount-codes – missing partnerId", async ({ api }) => {
+ expect(
+ await api.post("/api/discount-codes", {
+ linkId: "link_missing",
+ code: `PW${nanoid(8)}`,
+ }),
+ ).toEqual({
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "invalid_type: partnerId: Invalid input: expected string, received undefined",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ });
+});
+
+test("GET /discount-codes – by partnerId", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const created = await createDiscountCode(api);
+ partnerId = created.partner.id;
+
+ const { status, data } = await api.get<DiscountCode[]>(
+ `/api/discount-codes?partnerId=${partnerId}`,
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toEqual([created.data]);
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("GET /discount-codes – by discountId", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const created = await createDiscountCode(api);
+ partnerId = created.partner.id;
+
+ const { status, data } = await api.get<DiscountCode[]>(
+ `/api/discount-codes?discountId=${created.data.discountId}&partnerId=${partnerId}`,
+ );
+
+ expect(status).toEqual(200);
+ expect(data.map((code) => code.id)).toContain(created.data.id);
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("GET /discount-codes – pagination", async ({ api }) => {
+ let partnerIdA: string | undefined;
+ let partnerIdB: string | undefined;
+
+ try {
+ const first = await createDiscountCode(api);
+ const second = await createDiscountCode(api);
+ partnerIdA = first.partner.id;
+ partnerIdB = second.partner.id;
+
+ const { status, data } = await api.get<DiscountCode[]>(
+ "/api/discount-codes?pageSize=1&page=1",
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toHaveLength(1);
+ } finally {
+ await deletePartner(partnerIdA);
+ await deletePartner(partnerIdB);
+ }
+});
+
+test("GET /discount-codes – unknown partner", async ({ api, program }) => {
+ expect(
+ await api.get("/api/discount-codes?partnerId=pn_does_not_exist"),
+ ).toEqual({
+ status: 404,
+ data: {
+ error: {
+ code: "not_found",
+ message: `Partner pn_does_not_exist is not enrolled in program ${program.id}.`,
+ doc_url: "https://dub.co/docs/api-reference/errors#not-found",
+ },
+ },
+ });
+});
+
+test("PATCH /discount-codes/{id}", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const created = await createDiscountCode(api);
+ partnerId = created.partner.id;
+ const nextCode = `PW${nanoid(8)}`;
+
+ const { status, data } = await api.patch<DiscountCode>(
+ `/api/discount-codes/${created.data.id}`,
+ { code: nextCode },
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toEqual({
+ ...created.data,
+ code: nextCode,
+ });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("PATCH /discount-codes/{id} – invalid code", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const created = await createDiscountCode(api);
+ partnerId = created.partner.id;
+
+ expect(
+ await api.patch(`/api/discount-codes/${created.data.id}`, {
+ code: "not valid!",
+ }),
+ ).toEqual({
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message:
+ "invalid_format: code: Code can only contain letters, numbers, dashes, and underscores.",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("DELETE /discount-codes/{id}", async ({ api }) => {
+ let partnerId: string | undefined;
+
+ try {
+ const created = await createDiscountCode(api);
+ partnerId = created.partner.id;
+
+ const { status, data } = await api.delete<{ id: string }>(
+ `/api/discount-codes/${created.data.id}`,
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toEqual({ id: created.data.id });
+ } finally {
+ await deletePartner(partnerId);
+ }
+});
+
+test("DELETE /discount-codes/{id} – not found", async ({ api }) => {
+ const { status, data } = await api.delete(
+ "/api/discount-codes/dcode_does_not_exist",
+ );
+
+ expect(status).toEqual(404);
+ expect(data).toEqual({
+ error: {
+ code: "not_found",
+ message: "Discount code (dcode_does_not_exist) not found.",
+ doc_url: "https://dub.co/docs/api-reference/errors#not-found",
+ },
+ });
+});