The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor promotion code creation jobs and API routes
Kiran Kc7f4f7ca86de
diff --git a/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.ts b/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.tsnew file mode 100644index 0000000000..0b6508a3c5--- /dev/null+++ b/apps/web/app/(ee)/api/cron/discounts/create-promotion-codes/route.ts@@ -0,0 +1,126 @@+import { dispatchPromotionCodeCreationJob } from "@/lib/api/discounts/promotion-code-creation-job";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { qstash } from "@/lib/cron";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { prisma } from "@dub/prisma";+import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";+import { z } from "zod";+import { logAndRespond } from "../../utils";++export const dynamic = "force-dynamic";++const PAGE_SIZE = 100;+const MAX_BATCH = 10;++const schema = z.object({+ discountId: z.string(),+ cursor: z.string().optional(),+});++// POST /api/cron/discounts/create-promotion-codes+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();+ await verifyQstashSignature({ req, rawBody });++ let { discountId, cursor } = schema.parse(JSON.parse(rawBody));++ // Find the discount+ const discount = await prisma.discount.findUnique({+ where: {+ id: discountId,+ },+ include: {+ partnerGroup: true,+ },+ });++ if (!discount) {+ return logAndRespond(`Discount ${discountId} not found.`, {+ logLevel: "error",+ });+ }++ if (!discount.couponCodeTrackingEnabledAt) {+ return logAndRespond(+ `Discount ${discountId} does not have coupon code tracking enabled.`,+ );+ }++ const group = discount.partnerGroup;++ if (!group) {+ return logAndRespond(+ `Discount ${discountId} does not have a partner group.`,+ );+ }++ let hasMore = true;+ let processedBatches = 0;++ while (processedBatches < MAX_BATCH) {+ // Find program enrollments for the group+ const programEnrollments = await prisma.programEnrollment.findMany({+ where: {+ groupId: group.id,+ ...(cursor && {+ createdAt: {+ gt: cursor,+ },+ }),+ },+ select: {+ id: true,+ links: {+ select: {+ id: true,+ key: true,+ couponCode: true,+ },+ },+ },+ take: PAGE_SIZE,+ orderBy: {+ createdAt: "asc",+ },+ });++ if (programEnrollments.length === 0) {+ hasMore = false;+ break;+ }++ // Find links without a coupon code+ const links = programEnrollments.flatMap(({ links }) =>+ links.filter(({ couponCode }) => !couponCode),+ );++ // Enqueue the coupon creation job for each link+ if (links.length > 0) {+ const linkChunks = chunk(links, 100);++ for (const linkChunk of linkChunks) {+ await dispatchPromotionCodeCreationJob(linkChunk);+ await new Promise((resolve) => setTimeout(resolve, 2000));+ }+ }++ cursor = programEnrollments[programEnrollments.length - 1].id;+ processedBatches++;+ }++ if (hasMore) {+ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/create-promotion-codes`,+ body: {+ discountId,+ cursor,+ },+ });+ }++ return new Response("Enqueued coupon creation job for the links.");+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.ts b/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.tsnew file mode 100644index 0000000000..44cd40f7b6--- /dev/null+++ b/apps/web/app/(ee)/api/cron/links/create-promotion-code/route.ts@@ -0,0 +1,129 @@+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { createStripePromotionCode } from "@/lib/stripe/create-stripe-promotion-code";+import { prisma } from "@dub/prisma";+import { nanoid } from "@dub/utils";+import { z } from "zod";+import { logAndRespond } from "../../utils";++export const dynamic = "force-dynamic";++const schema = z.object({+ linkId: z.string(),+ code: z.string(),+});++// POST /api/cron/links/create-promotion-code+export async function POST(req: Request) {+ let payload: z.infer<typeof schema> | undefined = undefined;+ const allHeaders = req.headers;++ try {+ const rawBody = await req.text();+ await verifyQstashSignature({ req, rawBody });++ payload = schema.parse(JSON.parse(rawBody));+ } catch (error) {+ return logAndRespond(error.message, {+ logLevel: "error",+ });+ }++ const { linkId, code } = payload;++ // Find the link+ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ },+ select: {+ id: true,+ key: true,+ projectId: true,+ couponCode: true,+ programEnrollment: {+ select: {+ discount: true,+ },+ },+ project: {+ select: {+ id: true,+ stripeConnectId: true,+ },+ },+ },+ });++ if (!link) {+ return logAndRespond(`Link ${linkId} not found.`, {+ logLevel: "error",+ });+ }++ if (link.couponCode) {+ return logAndRespond(`Link ${linkId} already has a coupon code.`);+ }++ const discount = link.programEnrollment?.discount;+ const workspace = link.project;++ if (!discount) {+ return logAndRespond(`Link ${linkId} does not have a discount.`);+ }++ if (!discount.couponId) {+ return logAndRespond(`Link ${linkId} does not have a couponId set.`);+ }++ if (!discount.couponCodeTrackingEnabledAt) {+ return logAndRespond(+ `Link ${linkId} does not have coupon code tracking enabled.`,+ );+ }++ if (!workspace) {+ return logAndRespond(`Link ${linkId} does not have a workspace.`, {+ logLevel: "error",+ });+ }++ const retried = Number(allHeaders.get("upstash-retried"));+ const amount =+ discount.type === "percentage" ? discount.amount : discount.amount / 100;++ try {+ // Create the promotion code using Stripe API+ const promotionCode = await createStripePromotionCode({+ workspace: {+ id: workspace.id,+ stripeConnectId: workspace.stripeConnectId,+ },+ discount: {+ id: discount.id,+ couponId: discount.couponId,+ amount: discount.amount,+ type: discount.type,+ },+ code: retried === 0 ? `${code}${amount}` : `${code}${nanoid(4)}`,+ });++ if (promotionCode?.code) {+ console.log(+ `Stripe promotion code ${promotionCode.code} created for the link ${linkId}.`,+ );++ await prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ couponCode: promotionCode.code,+ },+ });+ }+ } catch (error) {+ return logAndRespond(error.raw?.message, { status: 400 });+ }++ return logAndRespond(`Finished executing the job for the link ${linkId}.`);+}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.tsdeleted file mode 100644index ca535f68da..0000000000--- a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts+++ /dev/null@@ -1,261 +0,0 @@-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { qstash } from "@/lib/cron";-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";-import { createStripePromotionCode } from "@/lib/stripe/create-stripe-promotion-code";-import { prisma } from "@dub/prisma";-import { APP_DOMAIN_WITH_NGROK, chunk, log } from "@dub/utils";-import { Link } from "@prisma/client";-import { z } from "zod";-import { logAndRespond } from "../../utils";--export const dynamic = "force-dynamic";--const schema = z.object({- discountId: z.string(),- page: z.number().optional().default(0),- linkIds: z- .array(z.string())- .optional()- .describe(- "Process only the provided linkIds. Make sure the array is always small.",- ),-});--const PAGE_SIZE = 50;-const STRIPE_PROMO_BATCH_SIZE = 10;--/**- * Cron job to create Stripe promotion codes for partner links- *- * This job processes partner links to create unique Stripe promotion codes- * for each link associated with a specific discount. It can work in two modes:- *- * 1. Group mode (linkIds not provided): Processes ALL partner links in a partner group- * by paginating through program enrollments, finding links that don't have coupon codes yet- *- * 2. Specific mode (linkIds provided): Processes only the specified link IDs- *- * In both modes, it creates promotion codes in batches of STRIPE_PROMO_BATCH_SIZE to respect Stripe's rate limits- * and automatically schedules the next batch until all eligible links have been processed.- */--// POST /api/cron/links/create-promotion-codes-export async function POST(req: Request) {- try {- const rawBody = await req.text();- await verifyQstashSignature({ req, rawBody });-- let { discountId, page, linkIds } = schema.parse(JSON.parse(rawBody));-- // Find the discount- const discount = await prisma.discount.findUnique({- where: {- id: discountId,- },- include: {- program: true,- partnerGroup: true,- },- });-- if (!discount) {- return logAndRespond(`Discount ${discountId} not found.`, {- logLevel: "error",- });- }-- if (!discount.couponId) {- return logAndRespond(- `Discount ${discount.id} does not have a couponId set.`,- {- logLevel: "error",- },- );- }-- if (!discount.couponCodeTrackingEnabledAt) {- return logAndRespond(- `Discount ${discount.id} is not enabled for coupon code tracking.`,- );- }-- const { program, partnerGroup: group } = discount;-- if (!group) {- return logAndRespond(- `Discount ${discountId} does not associate with a partner group.`,- {- logLevel: "error",- },- );- }-- // Find the workspace for the program- const workspace = await prisma.project.findUnique({- where: {- id: program.workspaceId,- },- select: {- id: true,- stripeConnectId: true,- },- });-- if (!workspace) {- return logAndRespond(`Workspace ${program.workspaceId} not found.`, {- logLevel: "error",- });- }-- if (!workspace.stripeConnectId) {- return logAndRespond(- `Workspace ${program.workspaceId} does not have a stripeConnectId set.`,- {- logLevel: "error",- },- );- }-- let links: Pick<Link, "id" | "key" | "couponCode">[] = [];-- // Specific mode: Process only the provided linkIds- if (linkIds) {- links = await prisma.link.findMany({- where: {- id: {- in: linkIds,- },- },- select: {- id: true,- key: true,- couponCode: true,- },- orderBy: {- id: "desc",- },- });-- // Finished processing all the links- if (links.length === 0) {- return logAndRespond(- `No links found to process for discount ${discount.id}.`,- );- }- }-- // Group mode: Process all links in the partner group- else {- // Find the program enrollments for the partner group- const programEnrollments = await prisma.programEnrollment.findMany({- where: {- groupId: group.id,- status: {- in: ["approved"],- },- },- orderBy: {- id: "desc",- },- take: PAGE_SIZE,- skip: page * PAGE_SIZE,- });-- // Finished processing all the program enrollments- if (programEnrollments.length === 0) {- return logAndRespond(- `No more program enrollments found in the partner group ${group.id}.`,- );- }-- page++;-- // Find the partner links for the enrollments- links = await prisma.link.findMany({- where: {- programId: program.id,- partnerId: {- in: programEnrollments.map(({ partnerId }) => partnerId),- },- },- select: {- id: true,- key: true,- couponCode: true,- },- orderBy: {- id: "desc",- },- });-- // If no links are found, schedule the next batch- if (links.length === 0) {- await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,- body: {- discountId: discount.id,- page,- },- });-- return logAndRespond(`Scheduled the next batch (page=${page}).`);- }- }-- const linksChunks = chunk(links, STRIPE_PROMO_BATCH_SIZE);- const failedRequests: Error[] = [];-- // Create promotion codes in batches for the partner links- for (const linksChunk of linksChunks) {- const results = await Promise.allSettled(- linksChunk.map((link) =>- createStripePromotionCode({- workspace,- link,- discount,- }),- ),- );-- results.forEach((result) => {- if (result.status === "rejected") {- failedRequests.push(result.reason);- }- });-- // Wait for 2 second before the next batch- await new Promise((resolve) => setTimeout(resolve, 2000));- }-- if (failedRequests.length > 0) {- await log({- message: `Error creating promotion codes for discount ${discount.id} - ${failedRequests.map((error) => error.message).join(", ")}`,- type: "alerts",- });-- console.error(failedRequests);- }-- // Schedule the next batch- if (!linkIds) {- await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,- body: {- discountId: discount.id,- page,- },- });- }-- return logAndRespond(`Scheduled the next batch (page=${page}).`);- } catch (error) {- await log({- message: `Error creating promotion codes for discount - ${error.message}`,- type: "alerts",- });-- console.error(error);-- return handleAndReturnErrorResponse(error);- }-}diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.tsindex c469ff36b8..18f2b55a97 100644--- a/apps/web/lib/actions/partners/create-discount.ts+++ b/apps/web/lib/actions/partners/create-discount.ts@@ -117,6 +117,14 @@ export const createDiscountAction = authActionClient},}),+ discount.couponCodeTrackingEnabledAt &&+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discounts/create-promotion-codes`,+ body: {+ discountId: discount.id,+ },+ }),+recordAuditLog({workspaceId: workspace.id,programId,diff --git a/apps/web/lib/api/discounts/promotion-code-creation-job.ts b/apps/web/lib/api/discounts/promotion-code-creation-job.tsnew file mode 100644index 0000000000..6becc515d2--- /dev/null+++ b/apps/web/lib/api/discounts/promotion-code-creation-job.ts@@ -0,0 +1,54 @@+import { qstash } from "@/lib/cron";+import { APP_DOMAIN_WITH_NGROK, isRejected } from "@dub/utils";+import { Link } from "@prisma/client";++const queue = qstash.queue({+ queueName: "coupon-creation-1",+});++type DispatchPromotionCodeCreationJobInput =+ | Pick<Link, "id" | "key">+ | Pick<Link, "id" | "key">[];++// Dispatch promotion code creation job for a link or multiple links+export async function dispatchPromotionCodeCreationJob(+ input: DispatchPromotionCodeCreationJobInput,+) {+ await queue.upsert({+ parallelism: 10,+ });++ const finalLinks = Array.isArray(input) ? input : [input];++ const response = await Promise.allSettled(+ finalLinks.map((link) =>+ queue.enqueueJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-code`,+ method: "POST",+ body: {+ linkId: link.id,+ code: link.key,+ },+ }),+ ),+ );++ const rejected = response+ .map((result, index) => ({ result, linkId: finalLinks[index].id }))+ .filter(({ result }) => isRejected(result));++ if (rejected.length > 0) {+ console.error(+ `Failed to dispatch coupon creation job for ${rejected.length} links.`,+ );++ rejected.forEach(({ result: promiseResult, linkId }) => {+ if (isRejected(promiseResult)) {+ console.error(+ `Failed to enqueue coupon creation job for link ${linkId}:`,+ promiseResult.reason,+ );+ }+ });+ }+}diff --git a/apps/web/lib/stripe/create-stripe-promotion-code.ts b/apps/web/lib/stripe/create-stripe-promotion-code.tsindex 0964688218..24c8387733 100644--- a/apps/web/lib/stripe/create-stripe-promotion-code.ts+++ b/apps/web/lib/stripe/create-stripe-promotion-code.ts@@ -1,39 +1,19 @@-import { prisma } from "@dub/prisma";import { stripeAppClient } from ".";-import { DiscountProps, LinkProps, WorkspaceProps } from "../types";+import { DiscountProps, WorkspaceProps } from "../types";const stripe = stripeAppClient({...(process.env.VERCEL_ENV && { livemode: true }),});-const MAX_RETRIES = 3;-export async function createStripePromotionCode({workspace,discount,- link,+ code,}: {workspace: Pick<WorkspaceProps, "id" | "stripeConnectId">;- discount: Pick<- DiscountProps,- "id" | "couponId" | "amount" | "type" | "couponCodeTrackingEnabledAt"- >;- link: Pick<LinkProps, "id" | "key" | "couponCode">;+ discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;+ code: string;}) {- if (!discount.couponCodeTrackingEnabledAt) {- console.log(- `Coupon code tracking is not enabled for discount ${discount.id}. Stripe promotion code creation skipped.`,- );- return;- }-- if (link.couponCode) {- console.log(- `Promotion code ${link.couponCode} already exists for link ${link.id}. Stripe promotion code creation skipped.`,- );- return;- }-if (!workspace.stripeConnectId) {console.error(`stripeConnectId not found for the workspace ${workspace.id}. Stripe promotion code creation skipped.`,@@ -48,66 +28,15 @@ export async function createStripePromotionCode({return;}- let lastError: Error | null = null;- let couponCode: string | undefined;-- const amount =- discount.type === "percentage" ? discount.amount : discount.amount / 100;-- for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {- try {- couponCode = attempt === 1 ? link.key : `${link.key}${amount}`; // eg: DAVID30-- const promotionCode = await stripe.promotionCodes.create(- {- coupon: discount.couponId,- code: couponCode.toUpperCase(),- },- {- stripeAccount: workspace.stripeConnectId,- },- );-- if (promotionCode) {- await prisma.link.update({- where: {- id: link.id,- },- data: {- couponCode: promotionCode.code,- },- });-- console.info(- `Created promotion code ${promotionCode.code} (discount=${discount.id}, link=${link.id})`,- );- }-- return promotionCode;- } catch (error) {- lastError = error instanceof Error ? error : new Error(String(error));-- const isDuplicateError =- error instanceof Error &&- error.message.includes("An active promotion code with `code:") &&- error.message.includes("already exists");-- console.error(error.message);-- if (isDuplicateError) {- if (attempt === MAX_RETRIES) {- throw lastError;- }-- continue;- }-- throw lastError;- }- }-- throw (- lastError ||- new Error("Unknown error occurred while creating promotion code on Stripe.")+ const promotionCode = await stripe.promotionCodes.create(+ {+ coupon: discount.couponId,+ code: code.toUpperCase(),+ },+ {+ stripeAccount: workspace.stripeConnectId,+ },);++ return promotionCode;}diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsxindex ce67c8ebf3..8e97e5174e 100644--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx@@ -13,6 +13,10 @@ import { createDiscountSchema } from "@/lib/zod/schemas/discount";import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";import { Stripe } from "@/ui/guides/icons/stripe";import { X } from "@/ui/shared/icons";+import {+ InlineBadgePopover,+ InlineBadgePopoverMenu,+} from "@/ui/shared/inline-badge-popover";import {Button,InfoTooltip,@@ -36,10 +40,6 @@ import { toast } from "sonner";import { mutate } from "swr";import { z } from "zod";import { RewardDiscountPartnersCard } from "../groups/reward-discount-partners-card";-import {- InlineBadgePopover,- InlineBadgePopoverMenu,-} from "../rewards/inline-badge-popover";interface DiscountSheetProps {setIsOpen: Dispatch<SetStateAction<boolean>>;