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.

fix cron job

Kiran K257ec79fd4db
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.ts
index 8eba5df698..ca535f68da 100644
--- 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.ts
@@ -4,6 +4,7 @@ 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";
@@ -12,17 +13,30 @@ 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 in batches to create unique Stripe promotion codes
- * for each link associated with a specific discount. It paginates through program
- * enrollments in a partner group, finds links that don't have coupon codes yet,
- * and creates promotion codes in batches of 10 to respect Stripe's rate limits.
+ * 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
*
- * It automatically schedules the next batch until all eligible links have been processed.
+ * 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
@@ -31,7 +45,7 @@ export async function POST(req: Request) {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- let { discountId, page } = schema.parse(JSON.parse(rawBody));
+ let { discountId, page, linkIds } = schema.parse(JSON.parse(rawBody));
// Find the discount
const discount = await prisma.discount.findUnique({
@@ -102,63 +116,90 @@ export async function POST(req: Request) {
);
}
- const PAGE_SIZE = 50;
- const STRIPE_PROMO_BATCH_SIZE = 10;
+ let links: Pick<Link, "id" | "key" | "couponCode">[] = [];
- // Find the program enrollments for the partner group
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- groupId: group.id,
- status: {
- in: ["approved"],
+ // Specific mode: Process only the provided linkIds
+ if (linkIds) {
+ links = await prisma.link.findMany({
+ where: {
+ id: {
+ in: linkIds,
+ },
},
- },
- orderBy: {
- id: "desc",
- },
- take: PAGE_SIZE,
- skip: page * PAGE_SIZE,
- });
+ select: {
+ id: true,
+ key: true,
+ couponCode: true,
+ },
+ orderBy: {
+ id: "desc",
+ },
+ });
- // Finished processing all the program enrollments
- if (programEnrollments.length === 0) {
- return logAndRespond(
- `No more program enrollments found in the partner group ${group.id}.`,
- );
+ // Finished processing all the links
+ if (links.length === 0) {
+ return logAndRespond(
+ `No links found to process for discount ${discount.id}.`,
+ );
+ }
}
- page++;
-
- // Find the partner links for the enrollments
- const links = await prisma.link.findMany({
- where: {
- programId: program.id,
- partnerId: {
- in: programEnrollments.map(({ partnerId }) => partnerId),
+ // 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"],
+ },
},
- couponCode: null,
- },
- select: {
- id: true,
- key: true,
- couponCode: true,
- },
- orderBy: {
- id: "desc",
- },
- });
+ orderBy: {
+ id: "desc",
+ },
+ take: PAGE_SIZE,
+ skip: page * PAGE_SIZE,
+ });
- // 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,
+ // 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",
},
});
- return logAndRespond(`Scheduled the next batch (page=${page}).`);
+ // 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);
@@ -196,13 +237,15 @@ export async function POST(req: Request) {
}
// Schedule the next batch
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,
- body: {
- discountId: discount.id,
- page,
- },
- });
+ 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) {
diff --git a/apps/web/lib/partners/approve-partner-enrollment.ts b/apps/web/lib/partners/approve-partner-enrollment.ts
index 24faa49246..d20e67140c 100644
--- a/apps/web/lib/partners/approve-partner-enrollment.ts
+++ b/apps/web/lib/partners/approve-partner-enrollment.ts
@@ -9,7 +9,7 @@ import { getGroupOrThrow } from "../api/groups/get-group-or-throw";
import { createPartnerLink } from "../api/partners/create-partner-link";
import { createStripePromotionCode } from "../stripe/create-stripe-promotion-code";
import { recordLink } from "../tinybird/record-link";
-import { ProgramPartnerLinkProps, RewardProps, WorkspaceProps } from "../types";
+import { LinkProps, RewardProps, WorkspaceProps } from "../types";
import { sendWorkspaceWebhook } from "../webhook/publish";
import { EnrolledPartnerSchema } from "../zod/schemas/partners";
@@ -125,7 +125,7 @@ export async function approvePartnerEnrollment({
: Promise.resolve(null),
]);
- let partnerLink: ProgramPartnerLinkProps;
+ let partnerLink: LinkProps;
const { partner, discount, ...enrollment } = programEnrollment;
const workspace = program.workspace as WorkspaceProps;
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index eb682d0bf0..923bf4c995 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -86,7 +86,8 @@ export const ProgramPartnerLinkSchema = LinkSchema.pick({
leads: true,
sales: true,
saleAmount: true,
- couponCode: true,
+}).extend({
+ couponCode: z.string().nullable(),
});
export const ProgramEnrollmentSchema = z.object({