The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add API route for creating promotion codes linked to discounts
Kiran K18d46a8c7b8f
diff --git a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.tsnew file mode 100644index 0000000000..2e8b19bb93--- /dev/null+++ b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts@@ -0,0 +1,121 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { createStripePromotionCode } from "@/lib/stripe/create-promotion-code";+import { prisma } from "@dub/prisma";+import { chunk } from "@dub/utils";+import { z } from "zod";++export const dynamic = "force-dynamic";++const schema = z.object({+ discountId: z.string(),+});++// This route is used to create promotion codes for each link for link-based coupon codes tracking.+// POST /api/cron/links/create-promotion-codes+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();+ await verifyQstashSignature({ req, rawBody });++ const body = schema.parse(JSON.parse(rawBody));+ const { discountId } = body;++ const discount = await prisma.discount.findUnique({+ where: {+ id: discountId,+ },+ });++ if (!discount) {+ return new Response("Discount not found.");+ }++ const { provider, programId, couponId } = discount;++ if (provider !== "stripe") {+ return new Response("Discount is not a link-based coupon code.");+ }++ if (!couponId) {+ return new Response("Discount coupon ID not found.");+ }++ const workspace = await prisma.project.findUnique({+ where: {+ defaultProgramId: programId,+ },+ select: {+ stripeConnectId: true,+ },+ });++ if (!workspace?.stripeConnectId) {+ return new Response("Workspace not found.");+ }++ const enrollments = await prisma.programEnrollment.findMany({+ where: {+ programId,+ couponId: discount.id,+ },+ select: {+ partnerId: true,+ },+ });++ if (enrollments.length === 0) {+ return new Response("No enrollments found.");+ }++ const links = await prisma.link.findMany({+ where: {+ programId,+ partnerId: {+ in: enrollments.map(({ partnerId }) => partnerId),+ },+ },+ select: {+ key: true,+ },+ });++ if (links.length === 0) {+ return new Response("No links found.");+ }++ const { stripeConnectId } = workspace;+ const linksChunks = chunk(links, 20);+ const failedRequests: Error[] = [];++ for (const linksChunk of linksChunks) {+ const results = await Promise.allSettled(+ linksChunk.map(({ key }) =>+ createStripePromotionCode({+ couponId,+ linkKey: key,+ stripeConnectId,+ }),+ ),+ );++ results.forEach((result) => {+ if (result.status === "rejected") {+ failedRequests.push(result.reason);+ }+ });+ }++ if (failedRequests.length > 0) {+ console.error(failedRequests);+ }++ return new Response(+ failedRequests.length > 0+ ? `Failed to create promotion codes for ${failedRequests.length} links. See logs for more details.`+ : "OK",+ );+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.tsindex f259635044..543b49b5c2 100644--- a/apps/web/lib/actions/partners/create-discount.ts+++ b/apps/web/lib/actions/partners/create-discount.ts@@ -172,6 +172,14 @@ export const createDiscountAction = authActionClient},],}),++ // If the coupon code is created on Stripe, create a promotion code for each link+ stripeCoupon ? qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,+ body: {+ discountId: discount.id,+ },+ }) : Promise.resolve(),]);})(),);diff --git a/apps/web/lib/stripe/create-coupon.ts b/apps/web/lib/stripe/create-coupon.tsindex 97e5f3a6b5..82e417dc6c 100644--- a/apps/web/lib/stripe/create-coupon.ts+++ b/apps/web/lib/stripe/create-coupon.ts@@ -45,6 +45,7 @@ export async function createStripeCoupon({console.error(`Failed to create Stripe coupon for ${stripeConnectId}: ${error}`,);- return null;++ throw new Error(error instanceof Error ? error.message : "Unknown error");}}diff --git a/apps/web/lib/stripe/create-promotion-code.ts b/apps/web/lib/stripe/create-promotion-code.tsindex 30fa85e60a..032d2280da 100644--- a/apps/web/lib/stripe/create-promotion-code.ts+++ b/apps/web/lib/stripe/create-promotion-code.ts@@ -1,40 +1,41 @@-import { Link } from "@prisma/client";import { stripeAppClient } from ".";-export async function createPromotionCode({+// Create a promotion code on Stripe for connected accounts+export async function createStripePromotionCode({couponId,- link,- stripeAccount,+ linkKey,+ stripeConnectId,}: {couponId: string;- link: Pick<Link, "key" | "partnerId">;- stripeAccount: string;+ linkKey: string;+ stripeConnectId: string | null;}) {+ if (!stripeConnectId) {+ console.error(+ "stripeConnectId not found for the workspace. Stripe promotion code creation skipped.",+ );+ return;+ }+const stripe = stripeAppClient({livemode: process.env.NODE_ENV === "production",});try {- const promotionCode = await stripe.promotionCodes.create(+ return await stripe.promotionCodes.create({coupon: couponId,- code: link.key,- metadata: {- partnerId: link.partnerId,- },+ code: linkKey.toUpperCase(),},{- stripeAccount,+ stripeAccount: stripeConnectId,},);-- console.log(- `Promotion code ${promotionCode.id} created for link ${link.key} for account ${stripeAccount}`,+ } catch (error) {+ console.error(+ `Failed to create Stripe promotion code for ${stripeConnectId}: ${error}`,);- return promotionCode;- } catch (error) {- console.error("Failed to create promotion code", error);- throw error;+ throw new Error(error instanceof Error ? error.message : "Unknown error");}}