The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Improve discount validation
Steven Tey0aa629c22928
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.tsindex d32e65bd28..f5758b867c 100644--- a/apps/web/lib/actions/partners/create-discount.ts+++ b/apps/web/lib/actions/partners/create-discount.ts@@ -5,13 +5,23 @@ import { createId } from "@/lib/api/create-id";import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { qstash } from "@/lib/cron";-import { createStripeCoupon } from "@/lib/stripe/create-stripe-coupon";+import { stripeAppClient } from "@/lib/stripe";+import {+ dubDiscountToStripeCoupon,+ stripeCouponToDubDiscount,+ validateStripeCouponForDubDiscount,+} from "@/lib/stripe/coupon-discount-converter";import { createDiscountSchema } from "@/lib/zod/schemas/discount";import { prisma } from "@dub/prisma";import { APP_DOMAIN_WITH_NGROK, truncate } from "@dub/utils";import { waitUntil } from "@vercel/functions";+import { Stripe } from "stripe";import { authActionClient } from "../safe-action";+const stripe = stripeAppClient({+ ...(process.env.VERCEL_ENV && { livemode: true }),+});+export const createDiscountAction = authActionClient.schema(createDiscountSchema).action(async ({ parsedInput, ctx }) => {@@ -32,40 +42,54 @@ export const createDiscountAction = authActionClient);}- // If no couponId or couponTestId is provided, create a new coupon on Stripe- const shouldCreateCouponOnStripe = !couponId && !couponTestId;-- if (shouldCreateCouponOnStripe) {- if (!workspace.stripeConnectId) {- throw new Error(- "STRIPE_CONNECTION_REQUIRED: Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create discount.",- );- }+ if (!workspace.stripeConnectId) {+ throw new Error(+ "STRIPE_CONNECTION_REQUIRED: Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create discount.",+ );+ }- try {- const stripeCoupon = await createStripeCoupon({- workspace: {- id: workspace.id,- stripeConnectId: workspace.stripeConnectId,- },- discount: {- name: `Dub Discount (${truncate(group.name, 25)})`,- amount,- type,- maxDuration: maxDuration ?? null,- },+ let stripeCoupon: Stripe.Coupon | undefined;+ try {+ if (couponId) {+ stripeCoupon = await stripe.coupons.retrieve(couponId, {+ stripeAccount: workspace.stripeConnectId,});- if (stripeCoupon) {- couponId = stripeCoupon.id;+ // Validate the Stripe coupon can be converted to a Dub discount+ const validation = validateStripeCouponForDubDiscount(stripeCoupon);+ if (!validation.isValid) {+ throw new Error(+ `Invalid Stripe coupon: ${validation.errors.join(", ")}`,+ );}- } catch (error) {- throw new Error(- error.code === "more_permissions_required_for_application"- ? "STRIPE_APP_UPGRADE_REQUIRED: Your connected Stripe account doesn't have the permissions needed to create discount codes. Please upgrade your Stripe integration in settings or reach out to our support team for help."- : error.message,- );++ // Convert Stripe coupon to Dub discount attributes+ const dubDiscountAttrs = stripeCouponToDubDiscount(stripeCoupon);+ amount = dubDiscountAttrs.amount;+ type = dubDiscountAttrs.type;+ maxDuration = dubDiscountAttrs.maxDuration;++ // if there is no couponId provided, we need to create a new coupon on Stripe+ } else {+ const stripeCouponData = dubDiscountToStripeCoupon({+ name: `Dub Discount (${truncate(group.name, 25)})`,+ amount,+ type,+ maxDuration: maxDuration ?? null,+ });++ stripeCoupon = await stripe.coupons.create(stripeCouponData, {+ stripeAccount: workspace.stripeConnectId,+ });}+ } catch (error) {+ throw new Error(+ error.code === "more_permissions_required_for_application"+ ? "STRIPE_APP_UPGRADE_REQUIRED: Your connected Stripe account doesn't have the permissions needed to create discount codes. Please upgrade your Stripe integration in settings or reach out to our support team for help."+ : error.code === "resource_missing"+ ? `The coupon ID you provided (${couponId}) was not found in your Stripe account. Please check the coupon ID and try again.`+ : error.message,+ );}// Create the discount and update the group and program enrollment@@ -77,7 +101,7 @@ export const createDiscountAction = authActionClientamount,type,maxDuration,- couponId,+ couponId: stripeCoupon?.id || couponId,...(couponTestId && { couponTestId }),},});diff --git a/apps/web/lib/api/groups/get-groups.ts b/apps/web/lib/api/groups/get-groups.tsindex 00a10448b4..250ec08c0c 100644--- a/apps/web/lib/api/groups/get-groups.ts+++ b/apps/web/lib/api/groups/get-groups.ts@@ -31,8 +31,6 @@ export async function getGroups(filters: GroupFilters) {includeExpandedFields,} = filters;- console.time("getGroups");-const groups = (await prisma.$queryRaw`SELECTpg.id,@@ -96,8 +94,6 @@ export async function getGroups(filters: GroupFilters) {LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`) satisfies Array<any>;- console.timeEnd("getGroups");-return groups.map((group) => ({...group,partners: Number(group.partners),diff --git a/apps/web/lib/stripe/coupon-discount-converter.ts b/apps/web/lib/stripe/coupon-discount-converter.tsnew file mode 100644index 0000000000..028078bbd7--- /dev/null+++ b/apps/web/lib/stripe/coupon-discount-converter.ts@@ -0,0 +1,116 @@+import { RewardStructure } from "@dub/prisma/client";+import { Stripe } from "stripe";++/**+ * Type definitions for conversion functions+ */+export interface DubDiscountAttributes {+ amount: number;+ type: RewardStructure;+ maxDuration: number | null;+ description?: string | null;+}++/**+ * Convert Dub Discount attributes to Stripe Coupon attributes+ */+export function dubDiscountToStripeCoupon(+ discount: DubDiscountAttributes & { name?: string },+): Stripe.CouponCreateParams {+ let duration: "once" | "repeating" | "forever" = "once";+ let durationInMonths: number | undefined = undefined;++ // Convert maxDuration to Stripe duration format+ if (discount.maxDuration === null) {+ duration = "forever";+ } else if (discount.maxDuration === 0) {+ duration = "once";+ } else {+ duration = "repeating";+ durationInMonths = discount.maxDuration;+ }++ const stripeCouponData: Stripe.CouponCreateParams = {+ currency: "usd",+ duration,+ ...(duration === "repeating" &&+ durationInMonths && {+ duration_in_months: durationInMonths,+ }),+ ...(discount.type === "percentage"+ ? { percent_off: discount.amount }+ : { amount_off: discount.amount }),+ ...(discount.name && { name: discount.name }),+ };++ return stripeCouponData;+}++/**+ * Convert Stripe Coupon attributes to Dub Discount attributes+ */+export function stripeCouponToDubDiscount(+ stripeCoupon: Stripe.Coupon,+): DubDiscountAttributes {+ // Determine discount type and amount+ const type: RewardStructure = stripeCoupon.percent_off+ ? "percentage"+ : "flat";+ const amount = stripeCoupon.percent_off || stripeCoupon.amount_off || 0;++ // Convert Stripe duration to Dub maxDuration+ let maxDuration: number | null = null;++ switch (stripeCoupon.duration) {+ case "once":+ maxDuration = 0;+ break;+ case "forever":+ maxDuration = null;+ break;+ case "repeating":+ maxDuration = stripeCoupon.duration_in_months || 1;+ break;+ }++ return {+ amount,+ type,+ maxDuration,+ description: stripeCoupon.name || null,+ };+}++/**+ * Validate that a Stripe coupon can be converted to a Dub discount+ */+export function validateStripeCouponForDubDiscount(+ stripeCoupon: Stripe.Coupon,+): { isValid: boolean; errors: string[] } {+ const errors: string[] = [];++ // Check if coupon has either percent_off or amount_off+ if (!stripeCoupon.percent_off && !stripeCoupon.amount_off) {+ errors.push("Coupon must have either percent_off or amount_off");+ }++ // Check if coupon has both percent_off and amount_off (invalid)+ if (stripeCoupon.percent_off && stripeCoupon.amount_off) {+ errors.push("Coupon cannot have both percent_off and amount_off");+ }++ // Check currency for amount_off coupons+ if (stripeCoupon.amount_off && stripeCoupon.currency !== "usd") {+ errors.push("Amount-based coupons must use USD currency");+ }++ // Check if coupon is valid (not deleted)+ if (stripeCoupon.valid === false) {+ errors.push("Coupon is not valid or has been deleted");+ }++ return {+ isValid: errors.length === 0,+ errors,+ };+}diff --git a/apps/web/lib/stripe/create-stripe-coupon.ts b/apps/web/lib/stripe/create-stripe-coupon.tsdeleted file mode 100644index 7f31edabe9..0000000000--- a/apps/web/lib/stripe/create-stripe-coupon.ts+++ /dev/null@@ -1,75 +0,0 @@-import { Discount } from "@dub/prisma/client";-import { stripeAppClient } from ".";-import { WorkspaceProps } from "../types";--const stripe = stripeAppClient({- ...(process.env.VERCEL_ENV && { livemode: true }),-});--// Create a coupon on Stripe for connected accounts-export async function createStripeCoupon({- workspace,- discount,-}: {- workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;- discount: Pick<Discount, "amount" | "type" | "maxDuration"> & {- name: string;- };-}) {- if (!workspace.stripeConnectId) {- console.error(- `stripeConnectId not found for the workspace ${workspace.id}. Skipping Stripe coupon creation.`,- );- return;- }-- let duration: "once" | "repeating" | "forever" = "once";- let durationInMonths: number | undefined = undefined;-- if (discount.maxDuration === null) {- duration = "forever";- } else if (discount.maxDuration === 0) {- duration = "once";- } else {- duration = "repeating";- }-- if (duration === "repeating" && discount.maxDuration) {- durationInMonths = discount.maxDuration;- }-- try {- const stripeCoupon = await stripe.coupons.create(- {- currency: "usd",- duration,- ...(duration === "repeating" && {- duration_in_months: durationInMonths,- }),- ...(discount.type === "percentage"- ? { percent_off: discount.amount }- : { amount_off: discount.amount }),- ...(discount.name && { name: discount.name }),- },- {- stripeAccount: workspace.stripeConnectId,- },- );-- console.info(- `Stripe coupon ${stripeCoupon.id} created for workspace ${workspace.id}.`,- );-- return stripeCoupon;- } catch (error) {- console.error(- `Failed create Stripe coupon for workspace ${workspace.id}.`,- {- error,- discount,- },- );-- throw error;- }-}