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.

Rename discount cleanup to detach and extract attachDiscount.

Kiran K1c02b4bde338
diff --git a/apps/web/app/(ee)/api/workflows/discount-deletion-cleanup/route.ts b/apps/web/app/(ee)/api/workflows/detach-discount/route.ts
similarity index 76%
rename from apps/web/app/(ee)/api/workflows/discount-deletion-cleanup/route.ts
rename to apps/web/app/(ee)/api/workflows/detach-discount/route.ts
index e9e4df7e52..f961d5e440 100644
--- a/apps/web/app/(ee)/api/workflows/discount-deletion-cleanup/route.ts
+++ b/apps/web/app/(ee)/api/workflows/detach-discount/route.ts
@@ -1,10 +1,9 @@
import { logger } from "@/lib/axiom/server";
import {
- deleteDiscount,
+ detachDiscountFromLinkRewards,
+ detachDiscountFromProgramEnrollments,
dispatchRemapDiscountCodes,
- removeDiscountFromLinkRewards,
- removeDiscountFromProgramEnrollments,
-} from "@/lib/discounts/delete-discount-cleanup";
+} from "@/lib/discounts/detach-discount";
import { prisma } from "@/lib/prisma";
import { serve } from "@upstash/workflow/nextjs";
import * as z from "zod/v4";
@@ -18,16 +17,16 @@ const inputSchema = z.object({
type Input = z.infer<typeof inputSchema>;
/**
- * Discount Deletion Cleanup Workflow
+ * Detach Discount Workflow
*
* Soft-deleted discounts (programId cleared) are cleaned up as:
*
- * 1. remove-discount-from-enrollments + remove-discount-from-link-rewards (parallel)
+ * 1. detach-discount-from-enrollments + detach-discount-from-link-rewards (parallel)
* 2. remap-discount-codes
* 3. delete-discount
*/
-// POST /api/workflows/discount-deletion-cleanup
+// POST /api/workflows/detach-discount
export const { POST } = serve<Input>(
async (context) => {
const input = inputSchema.parse(context.requestPayload);
@@ -60,7 +59,7 @@ export const { POST } = serve<Input>(
return logAndReturn({
proceed: true,
- outputLog: `Proceeding with discount deletion cleanup for ${discountId}`,
+ outputLog: `Proceeding with detach discount for ${discountId}`,
});
});
@@ -70,25 +69,25 @@ export const { POST } = serve<Input>(
// Run these in parallel
await Promise.all([
- context.run("remove-discount-from-enrollments", async () => {
- await removeDiscountFromProgramEnrollments({
+ context.run("detach-discount-from-enrollments", async () => {
+ await detachDiscountFromProgramEnrollments({
programId,
discountId,
});
return logAndReturn({
- outputLog: `Removed discount ${discountId} from program enrollments`,
+ outputLog: `Detached discount ${discountId} from program enrollments`,
});
}),
- context.run("remove-discount-from-link-rewards", async () => {
- await removeDiscountFromLinkRewards({
+ context.run("detach-discount-from-link-rewards", async () => {
+ await detachDiscountFromLinkRewards({
programId,
discountId,
});
return logAndReturn({
- outputLog: `Removed discount ${discountId} from link rewards`,
+ outputLog: `Detached discount ${discountId} from link rewards`,
});
}),
]);
@@ -107,9 +106,10 @@ export const { POST } = serve<Input>(
// This should run after the discount codes are remapped
await context.run("delete-discount", async () => {
- await deleteDiscount({
- programId,
- discountId,
+ await prisma.discount.deleteMany({
+ where: {
+ id: discountId,
+ },
});
return logAndReturn({
@@ -127,7 +127,7 @@ export const { POST } = serve<Input>(
logger.error("workflow.failed", {
service: "qstash",
event: "workflow.failed",
- workflowType: "discount-deletion-cleanup",
+ workflowType: "detach-discount",
workflowRunId: context.workflowRunId,
discountId: context.requestPayload?.discountId,
programId: context.requestPayload?.programId,
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index afec05bf56..a7d766d4ab 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -121,7 +121,7 @@ export const createDiscountAction = authActionClient
});
if (isDefault) {
- attachDiscountJob.dispatch(
+ await attachDiscountJob.dispatch(
{ discountId: discount.id },
{ label: discount.id },
);
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index 429ce53cfd..cde2033435 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -3,7 +3,8 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { softDeleteDiscount } from "@/lib/discounts/soft-delete-discount";
+import { dispatchWorkflows } from "@/lib/jobs/publish-workflows";
+import { prisma } from "@/lib/prisma";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
@@ -32,9 +33,36 @@ export const deleteDiscountAction = authActionClient
discountId,
});
- await softDeleteDiscount({
- discountId,
- programId,
+ await prisma.$transaction(async (tx) => {
+ await tx.partnerGroup.updateMany({
+ where: {
+ discountId,
+ },
+ data: {
+ discountId: null,
+ },
+ });
+
+ await tx.discount.update({
+ where: {
+ id: discountId,
+ },
+ data: {
+ programId: null,
+ },
+ });
+ });
+
+ await dispatchWorkflows({
+ name: "detach-discount-workflow",
+ payload: {
+ programId,
+ discountId,
+ },
+ options: {
+ label: discountId,
+ deduplicationId: `detach-discount-${discountId}`,
+ },
});
waitUntil(
diff --git a/apps/web/lib/discounts/attach-discount.ts b/apps/web/lib/discounts/attach-discount.ts
new file mode 100644
index 0000000000..9ead4a2a6b
--- /dev/null
+++ b/apps/web/lib/discounts/attach-discount.ts
@@ -0,0 +1,103 @@
+import { PRISMA_UPDATEMANY_LIMIT, qstash } from "@/lib/cron";
+import { prisma } from "@/lib/prisma";
+import { APP_DOMAIN_WITH_NGROK, pluck } from "@dub/utils";
+import { invalidateLinksForDiscountsJob } from "../jobs/handlers/invalidate-links-for-discounts-job";
+
+// Attach a group-level discount to one batch of enrollments in the group.
+// Returns whether more enrollments remain to attach.
+export async function attachDiscount({
+ discountId,
+}: {
+ discountId: string;
+}): Promise<{ hasMore: boolean } | null> {
+ const discount = await prisma.discount.findUnique({
+ where: {
+ id: discountId,
+ },
+ select: {
+ id: true,
+ programId: true,
+ autoProvisionEnabledAt: true,
+ defaultForPartnerGroup: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
+
+ if (!discount) {
+ console.info(`Discount ${discountId} not found. Skipping...`);
+ return null;
+ }
+
+ if (!discount.programId || !discount.defaultForPartnerGroup) {
+ console.info(
+ `Discount ${discountId} is not a group-level discount. Skipping...`,
+ );
+ return null;
+ }
+
+ const groupId = discount.defaultForPartnerGroup.id;
+
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId,
+ discountId: null,
+ },
+ select: {
+ id: 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,
+ discountId: null,
+ },
+ data: {
+ discountId: discount.id,
+ },
+ });
+
+ console.info(
+ `Attached discount ${discount.id} to ${count} enrollments in group ${groupId}.`,
+ );
+ }
+
+ if (enrollments.length === PRISMA_UPDATEMANY_LIMIT) {
+ return {
+ hasMore: true,
+ };
+ }
+
+ 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,
+ },
+ }),
+ ]
+ : []),
+ ]);
+
+ return {
+ hasMore: false,
+ };
+}
diff --git a/apps/web/lib/discounts/delete-discount-cleanup.ts b/apps/web/lib/discounts/detach-discount.ts
similarity index 86%
rename from apps/web/lib/discounts/delete-discount-cleanup.ts
rename to apps/web/lib/discounts/detach-discount.ts
index 205c4b14d6..91aef7a5c8 100644
--- a/apps/web/lib/discounts/delete-discount-cleanup.ts
+++ b/apps/web/lib/discounts/detach-discount.ts
@@ -4,22 +4,18 @@ import { Prisma } from "@prisma/client";
import { invalidateLinksForDiscountsJob } from "../jobs/handlers/invalidate-links-for-discounts-job";
import { remapDiscountCodeJob } from "../jobs/handlers/remap-discount-code-job";
-// TODO:
-// Track activity log (enrollment and link level)
-// Send email to the partners (not now)
-
-type DeleteDiscountCleanupParams = {
+type DetachDiscountParams = {
programId: string;
discountId: string;
};
const BATCH_SIZE = 500;
-// Remove discount from program enrollments
-export async function removeDiscountFromProgramEnrollments({
+// Detach discount from program enrollments
+export async function detachDiscountFromProgramEnrollments({
programId,
discountId,
-}: DeleteDiscountCleanupParams) {
+}: DetachDiscountParams) {
let startAfterId: string | null = null;
const discount = await prisma.discount.findUnique({
@@ -101,10 +97,10 @@ export async function removeDiscountFromProgramEnrollments({
}
}
-// Remove discount from link rewards
-export async function removeDiscountFromLinkRewards({
+// Detach discount from link rewards
+export async function detachDiscountFromLinkRewards({
discountId,
-}: DeleteDiscountCleanupParams) {
+}: DetachDiscountParams) {
let startAfterId: string | null = null;
while (true) {
@@ -155,7 +151,7 @@ export async function removeDiscountFromLinkRewards({
// Dispatch per-code remap jobs for codes still pointing at this discount
export async function dispatchRemapDiscountCodes({
discountId,
-}: DeleteDiscountCleanupParams) {
+}: DetachDiscountParams) {
let startAfterId: string | null = null;
while (true) {
@@ -197,11 +193,3 @@ export async function dispatchRemapDiscountCodes({
}
}
}
-
-// Dispatch discount code deletion
-export async function deleteDiscount({
- programId,
- discountId,
-}: DeleteDiscountCleanupParams) {
- //
-}
diff --git a/apps/web/lib/discounts/soft-delete-discount.ts b/apps/web/lib/discounts/soft-delete-discount.ts
deleted file mode 100644
index a662deddc4..0000000000
--- a/apps/web/lib/discounts/soft-delete-discount.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { dispatchWorkflows } from "@/lib/jobs/publish-workflows";
-import { prisma } from "@/lib/prisma";
-
-// Soft delete a discount and dispatch cleanup workflow
-export async function softDeleteDiscount({
- discountId,
- programId,
-}: {
- discountId: string;
- programId: string;
-}) {
- await prisma.$transaction(async (tx) => {
- await tx.partnerGroup.updateMany({
- where: {
- discountId,
- },
- data: {
- discountId: null,
- },
- });
-
- await tx.discount.update({
- where: {
- id: discountId,
- },
- data: {
- programId: null,
- },
- });
- });
-
- await dispatchWorkflows({
- name: "discount-deletion-cleanup-workflow",
- payload: {
- programId,
- discountId,
- },
- options: {
- label: discountId,
- deduplicationId: `discount-deletion-cleanup-${discountId}`,
- },
- });
-}
diff --git a/apps/web/lib/jobs/handlers/attach-discount-job.ts b/apps/web/lib/jobs/handlers/attach-discount-job.ts
index d5f371be38..168a2cba18 100644
--- a/apps/web/lib/jobs/handlers/attach-discount-job.ts
+++ b/apps/web/lib/jobs/handlers/attach-discount-job.ts
@@ -1,100 +1,22 @@
-import { PRISMA_UPDATEMANY_LIMIT, qstash } from "@/lib/cron";
-import { prisma } from "@/lib/prisma";
-import { APP_DOMAIN_WITH_NGROK, pluck } from "@dub/utils";
+import { attachDiscount } from "@/lib/discounts/attach-discount";
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.
+// Attach a newly created group-level discount to enrollments in the group
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,
- },
+ const result = await attachDiscount({
+ discountId,
});
- 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) {
+ if (result?.hasMore) {
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/send-workflows.ts b/apps/web/lib/jobs/send-workflows.ts
index 53b1e3b57b..dc61078ca9 100644
--- a/apps/web/lib/jobs/send-workflows.ts
+++ b/apps/web/lib/jobs/send-workflows.ts
@@ -30,8 +30,7 @@ const workflowPathMap = {
"create-partner-commission-workflow":
"/api/workflows/create-partner-commission",
"reattribute-customer-workflow": "/api/workflows/reattribute-customer",
- "discount-deletion-cleanup-workflow":
- "/api/workflows/discount-deletion-cleanup",
+ "detach-discount-workflow": "/api/workflows/detach-discount",
} as const;
for (const name of Object.keys(workflowPathMap)) {