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.

Attach default discounts to enrollments in a background job.

Kiran Kb8e4f0ff3573
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 990567ed99..afec05bf56 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -4,15 +4,13 @@ import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
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 { getDiscountProvider } from "@/lib/discounts/discount-provider";
-import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
+import { attachDiscountJob } from "@/lib/jobs/handlers/attach-discount-job";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";
import { DubDiscountAttributes } from "@/lib/stripe/coupon-discount-converter";
import { createDiscountSchema } from "@/lib/zod/schemas/discount";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { DiscountProvider } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { authActionClient } from "../safe-action";
@@ -81,7 +79,7 @@ export const createDiscountAction = authActionClient
});
}
- // Create the discount and update the group and program enrollment
+ // Create the discount and assign it to the group when it is the default
const discount = await prisma.$transaction(async (tx) => {
const discount = await tx.discount.create({
data: {
@@ -102,7 +100,6 @@ export const createDiscountAction = authActionClient
},
});
- // Assign to the group if it is the default discount
if (isDefault) {
const { count } = await tx.partnerGroup.updateMany({
where: {
@@ -118,75 +115,33 @@ export const createDiscountAction = authActionClient
if (count === 0) {
throw new Error("This group already has a default discount.");
}
-
- await tx.discountCode.updateMany({
- where: {
- programEnrollment: {
- groupId,
- discountId: null,
- },
- },
- data: {
- discountId: discount.id,
- },
- });
-
- await tx.programEnrollment.updateMany({
- where: {
- groupId,
- discountId: null,
- },
- data: {
- discountId: discount.id,
- },
- });
}
return discount;
});
+ if (isDefault) {
+ attachDiscountJob.dispatch(
+ { discountId: discount.id },
+ { label: discount.id },
+ );
+ }
+
waitUntil(
- Promise.allSettled([
- ...(isDefault
- ? [
- invalidateLinksForDiscountsJob.dispatch(
- {
- type: "discount",
- discountId: discount.id,
- },
- {
- label: discount.id,
- },
- ),
- ]
- : []),
-
- recordAuditLog({
- workspaceId: workspace.id,
- programId,
- action: "discount.created",
- description: `Discount ${discount.id} created`,
- actor: user,
- targets: [
- {
- type: "discount",
- id: discount.id,
- metadata: discount,
- },
- ],
- }),
-
- ...(discount.autoProvisionEnabledAt
- ? [
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/create/queue-batches`,
- body: {
- discountId: discount.id,
- },
- }),
- ]
- : []),
- ]),
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "discount.created",
+ description: `Discount ${discount.id} created`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: discount.id,
+ metadata: discount,
+ },
+ ],
+ }),
);
return {
diff --git a/apps/web/lib/jobs/handlers/attach-discount-job.ts b/apps/web/lib/jobs/handlers/attach-discount-job.ts
new file mode 100644
index 0000000000..d5f371be38
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/attach-discount-job.ts
@@ -0,0 +1,100 @@
+import { PRISMA_UPDATEMANY_LIMIT, qstash } from "@/lib/cron";
+import { prisma } from "@/lib/prisma";
+import { APP_DOMAIN_WITH_NGROK, pluck } from "@dub/utils";
+import * as z from "zod/v4";
+import { defineJob } from "../index";
+import { invalidateLinksForDiscountsJob } from "./invalidate-links-for-discounts-job";
+
+const inputSchema = z.object({
+ discountId: z.string(),
+});
+
+// Attach a newly created default discount to enrollments and discount codes
+// in the group (batched), then kick off cache invalidation and auto-provisioning.
+export const attachDiscountJob = defineJob({
+ name: "attach-discount-job",
+ schema: inputSchema,
+ async handle({ discountId }) {
+ const discount = await prisma.discount.findUnique({
+ where: {
+ id: discountId,
+ },
+ select: {
+ id: true,
+ programId: true,
+ groupId: true,
+ autoProvisionEnabledAt: true,
+ },
+ });
+
+ if (!discount) {
+ console.info(`Discount ${discountId} not found. Skipping...`);
+ return;
+ }
+
+ if (!discount.programId || !discount.groupId) {
+ console.info(
+ `Discount ${discountId} has no program or group. Skipping...`,
+ );
+ return;
+ }
+
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId: discount.groupId,
+ discountId: null,
+ },
+ select: {
+ id: true,
+ partnerId: true,
+ },
+ take: PRISMA_UPDATEMANY_LIMIT,
+ orderBy: {
+ id: "asc",
+ },
+ });
+
+ if (enrollments.length > 0) {
+ const { count } = await prisma.programEnrollment.updateMany({
+ where: {
+ id: {
+ in: pluck(enrollments, "id"),
+ },
+ groupId: discount.groupId,
+ discountId: null,
+ },
+ data: {
+ discountId: discount.id,
+ },
+ });
+
+ console.info(
+ `Attached discount ${discount.id} to ${count} enrollments in group ${discount.groupId}.`,
+ );
+ }
+
+ if (enrollments.length === PRISMA_UPDATEMANY_LIMIT) {
+ await attachDiscountJob.dispatch({ discountId }, { label: discountId });
+ return;
+ }
+
+ // Finish up by invalidating links and queueing up auto-provisioning
+ await Promise.all([
+ invalidateLinksForDiscountsJob.dispatch(
+ { type: "discount", discountId: discount.id },
+ { label: discount.id },
+ ),
+
+ ...(discount.autoProvisionEnabledAt
+ ? [
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/create/queue-batches`,
+ body: {
+ discountId: discount.id,
+ },
+ }),
+ ]
+ : []),
+ ]);
+ },
+});
diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.ts
index 06b8909917..f5c7f6ef90 100644
--- a/apps/web/lib/jobs/registry.ts
+++ b/apps/web/lib/jobs/registry.ts
@@ -81,6 +81,9 @@ const jobLoaders = {
(m) => m.remapDiscountCodeJob,
),
+ "attach-discount-job": () =>
+ import("./handlers/attach-discount-job").then((m) => m.attachDiscountJob),
+
"aggregate-clicks-job": () =>
import("./handlers/aggregate-clicks-job").then((m) => m.aggregateClicksJob),
} as const satisfies Record<string, () => Promise<JobDefinition>>;