The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
allow any characters in custom provider discount codes
Pedro Ladeiracf8f25df3034
diff --git a/apps/web/app/(ee)/api/discount-codes/route.ts b/apps/web/app/(ee)/api/discount-codes/route.tsindex e459a844cd..69d556b1ff 100644--- a/apps/web/app/(ee)/api/discount-codes/route.ts+++ b/apps/web/app/(ee)/api/discount-codes/route.ts@@ -12,8 +12,10 @@ import {createDiscountCodeSchema,DiscountCodeSchema,getDiscountCodesQuerySchema,+ restrictedDiscountCodeSchema,} from "@/lib/zod/schemas/discount";import { APP_DOMAIN } from "@dub/utils";+import { DiscountProvider } from "@prisma/client";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";@@ -138,6 +140,14 @@ export const POST = withWorkspace(});}+ if (+ code &&+ (discount.provider === DiscountProvider.stripe ||+ discount.provider === DiscountProvider.shopify)+ ) {+ restrictedDiscountCodeSchema.parse({ code });+ }+// A link can have only one discount codeconst duplicateByLink = programEnrollment.discountCodes.find((discountCode) => discountCode.linkId === linkId,diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/discount-codes.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/discount-codes.tsxindex 8c9f3847ab..ed84205df5 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/discount-codes.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/discount-codes.tsx@@ -40,7 +40,7 @@ import { cn, getPrettyUrl, nFormatter, pluralize } from "@dub/utils";import { DiscountProvider } from "@prisma/client";import { Command } from "cmdk";import Link from "next/link";-import { type ReactNode, useMemo, useState } from "react";+import { type ReactNode, useCallback, useMemo, useState } from "react";type PartnerLink = ProgramPartnerLinkExtended;type PartnerForDiscountOverride = Pick<@@ -109,9 +109,25 @@ export function PartnerDiscountCodes({groupId: partner.groupId ?? undefined,});+ const getDiscountProvider = useCallback(+ (linkId: string) => {+ const link = links?.find((item) => item.id === linkId);+ if (!link) return null;++ return getEffectiveDiscountProvider({+ link,+ discounts,+ partnerDiscount: partner.discount,+ groupDiscount: group?.discount,+ });+ },+ [links, discounts, partner.discount, group?.discount],+ );+const { AddDiscountCodeModal, setShowAddDiscountCodeModal } =useAddDiscountCodeModal({partner,+ getDiscountProvider,});const usedLinkIds = useMemo(diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.tsindex 5dd6a1147a..1fa0a2d184 100644--- a/apps/web/lib/zod/schemas/discount.ts+++ b/apps/web/lib/zod/schemas/discount.ts@@ -93,18 +93,24 @@ export const DiscountCodeSchema = ztitle: "DiscountCode",});-export const createDiscountCodeSchema = z.object({+export const restrictedDiscountCodeSchema = z.object({code: 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+ .string()+ .trim()+ .max(100, "Code must be 100 characters or fewer.").optional().describe(- "The discount code to create. If omitted, a unique code will be generated automatically from the partner's name.",+ "The discount code to create. If omitted, a unique code will be generated automatically from the partner's name. Stripe and Shopify codes can only contain letters, numbers, dashes, and underscores. Custom provider codes can contain any characters.",),partnerId: z.string()diff --git a/apps/web/playwright/api/discount-codes/discount-codes.spec.ts b/apps/web/playwright/api/discount-codes/discount-codes.spec.tsindex a08bbd1d0b..55ab1507cc 100644--- a/apps/web/playwright/api/discount-codes/discount-codes.spec.ts+++ b/apps/web/playwright/api/discount-codes/discount-codes.spec.ts@@ -498,41 +498,50 @@ test("POST /discount-codes – duplicate code", async ({ api }) => {}});-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 – custom provider allows special characters", async ({+ api,+}) => {+ let partnerId: string | undefined;++ try {+ const { status, data, partner, body } = await createDiscountCode(api, {+ code: `NOT VALID!@10.${nanoid(6)}`,+ });+ partnerId = partner.id;++ expect(status).toEqual(200);+ expect(data).toEqual({+ id: expect.any(String),+ code: body.code,+ discountId: customDiscountId,+ partnerId: partner.id,+ linkId: body.linkId,+ disabledAt: null,});+ } finally {+ await deletePartner(partnerId);+ }+});++test("POST /discount-codes – too long", async ({ api }) => {+ expect(+ await api.post("/api/discount-codes", {+ partnerId: "pn_x",+ linkId: "link_x",+ code: "A".repeat(101),+ }),+ ).toEqual({+ status: 422,+ data: {+ error: {+ code: "unprocessable_entity",+ message: "too_big: code: Code must be 100 characters or fewer.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ },});-}+});test("POST /discount-codes – missing partnerId", async ({ api }) => {expect(diff --git a/apps/web/tests/discounts/restricted-discount-code-schema.test.ts b/apps/web/tests/discounts/restricted-discount-code-schema.test.tsnew file mode 100644index 0000000000..1d8d37910f--- /dev/null+++ b/apps/web/tests/discounts/restricted-discount-code-schema.test.ts@@ -0,0 +1,55 @@+import {+ createDiscountCodeSchema,+ restrictedDiscountCodeSchema,+} from "@/lib/zod/schemas/discount";+import { describe, expect, it } from "vitest";++describe("restrictedDiscountCodeSchema", () => {+ it("rejects characters outside letters, numbers, dashes, and underscores", () => {+ const result = restrictedDiscountCodeSchema.safeParse({+ code: "NOT VALID!",+ });++ expect(result.success).toBe(false);++ if (!result.success) {+ expect(result.error.issues[0]?.message).toBe(+ "Code can only contain letters, numbers, dashes, and underscores.",+ );+ }+ });++ it("accepts letters, numbers, dashes, and underscores", () => {+ expect(+ restrictedDiscountCodeSchema.parse({ code: "PARTNER_10-OFF" }).code,+ ).toBe("PARTNER_10-OFF");+ });+});++describe("createDiscountCodeSchema", () => {+ it("allows any characters so custom provider codes are not rejected up front", () => {+ expect(+ createDiscountCodeSchema.parse({+ partnerId: "pn_x",+ linkId: "link_x",+ code: "[email protected]!",+ }).code,+ ).toBe("[email protected]!");+ });++ it("still rejects codes longer than 100 characters", () => {+ const result = createDiscountCodeSchema.safeParse({+ partnerId: "pn_x",+ linkId: "link_x",+ code: "A".repeat(101),+ });++ expect(result.success).toBe(false);++ if (!result.success) {+ expect(result.error.issues[0]?.message).toBe(+ "Code must be 100 characters or fewer.",+ );+ }+ });+});diff --git a/apps/web/ui/modals/add-discount-code-modal.tsx b/apps/web/ui/modals/add-discount-code-modal.tsxindex a5b9b50ce9..bd597bdfe9 100644--- a/apps/web/ui/modals/add-discount-code-modal.tsx+++ b/apps/web/ui/modals/add-discount-code-modal.tsx@@ -12,6 +12,7 @@ import {} from "@dub/ui";import { CircleWarning, TriangleWarning } from "@dub/ui/icons";import { cn, getPrettyUrl } from "@dub/utils";+import { DiscountProvider } from "@prisma/client";import { Tag } from "lucide-react";import { useCallback, useMemo, useRef, useState } from "react";import { useForm } from "react-hook-form";@@ -25,24 +26,18 @@ import { UpgradeRequiredToast } from "../shared/upgrade-required-toast";type FormData = z.infer<typeof createDiscountCodeSchema>;-// Mirrors the createDiscountCodeSchema format: spaces become dashes,-// anything other than letters, numbers, dashes, and underscores is dropped-const sanitizeDiscountCode = (code: string) =>- code- .trim()- .replace(/\s+/g, "-")- .replace(/[^a-zA-Z0-9\-_]/g, "");-interface AddDiscountCodeModalProps {showModal: boolean;setShowModal: (showModal: boolean) => void;partner: EnrolledPartnerProps;+ getDiscountProvider: (linkId: string) => DiscountProvider | null;}const AddDiscountCodeModal = ({showModal,setShowModal,partner,+ getDiscountProvider,}: AddDiscountCodeModalProps) => {const [search, setSearch] = useState("");const [isOpen, setIsOpen] = useState(false);@@ -61,8 +56,16 @@ const AddDiscountCodeModal = ({const [linkId, code] = watch(["linkId", "code"]);- const sanitizedCode = sanitizeDiscountCode(code ?? "");- const codeWillChange = !!code && sanitizedCode !== code.trim();+ const provider = linkId ? getDiscountProvider(linkId) : null;+ const restrictsCodeFormat =+ provider === DiscountProvider.stripe ||+ provider === DiscountProvider.shopify;+ const trimmedCode = (code ?? "").trim();+ // Stripe and Shopify only allow letters, numbers, dashes, and underscores.+ const codeToCreate = restrictsCodeFormat+ ? trimmedCode.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9\-_]/g, "")+ : trimmedCode;+ const codeWillChange = restrictsCodeFormat && codeToCreate !== trimmedCode;// Get partner links for the dropdownconst partnerLinks = partner.links || [];@@ -91,7 +94,7 @@ const AddDiscountCodeModal = ({method: "POST",body: {...formData,- code: sanitizeDiscountCode(formData.code ?? ""),+ code: codeToCreate,partnerId: partner.id,},onSuccess: async (data) => {@@ -220,13 +223,13 @@ const AddDiscountCodeModal = ({/></div>{codeWillChange &&- (sanitizedCode ? (+ (codeToCreate ? (<p className="flex items-center gap-1.5 text-xs text-neutral-500"><TriangleWarning className="size-3.5 shrink-0 text-amber-500" /><span className="min-w-0">Will be created as{" "}<code className="break-all rounded-md bg-neutral-100 px-1.5 py-0.5 font-mono text-neutral-800">- {sanitizedCode}+ {codeToCreate}</code></span></p>@@ -256,7 +259,7 @@ const AddDiscountCodeModal = ({}className="h-8 w-fit pl-2.5 pr-1.5"loading={isSubmitting}- disabled={!linkId || (codeWillChange && !sanitizedCode)}+ disabled={!linkId || (codeWillChange && !codeToCreate)}/></div></form>@@ -266,8 +269,10 @@ const AddDiscountCodeModal = ({export function useAddDiscountCodeModal({partner,+ getDiscountProvider,}: {partner: EnrolledPartnerProps;+ getDiscountProvider: (linkId: string) => DiscountProvider | null;}) {const [showAddDiscountCodeModal, setShowAddDiscountCodeModal] =useState(false);@@ -278,9 +283,15 @@ export function useAddDiscountCodeModal({showModal={showAddDiscountCodeModal}setShowModal={setShowAddDiscountCodeModal}partner={partner}+ getDiscountProvider={getDiscountProvider}/>);- }, [showAddDiscountCodeModal, setShowAddDiscountCodeModal]);+ }, [+ showAddDiscountCodeModal,+ setShowAddDiscountCodeModal,+ partner,+ getDiscountProvider,+ ]);return useMemo(() => ({