The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Defer soft-deleted discount hard-delete to orphaned-rewards after code sync.
Kiran K4ddaf3cfafba
diff --git a/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts b/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.tsindex d1c034b996..13291f220c 100644--- a/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts+++ b/apps/web/app/(ee)/api/cron/cleanup/orphaned-rewards/route.ts@@ -1,5 +1,6 @@import { PRISMA_UPDATEMANY_LIMIT } from "@/lib/cron";import { withCron } from "@/lib/cron/with-cron";+import { deleteOrphanedDiscounts } from "@/lib/discounts/delete-orphaned-discounts";import { prisma } from "@/lib/prisma";import { deleteOrphanedRewards } from "@/lib/rewards/delete-orphaned-rewards";import { subMinutes } from "date-fns";@@ -12,6 +13,8 @@ const STALE_AFTER_MINUTES = 30;// Hard-deletes leftover rows after request-path soft-deletes / unassigns:// - Rewards: rewards/process clears enrollments on delete; this cron hard-deletes// once nothing still references the soft-deleted reward (programId null).+// - Discounts: detach-discount remaps codes first; this cron hard-deletes once+// nothing still references the soft-deleted discount (programId null).// - LinkReward: update-partner-link nulls override IDs instead of deleting the row.// Discount deletes SetNull LinkReward.discountId the same way.@@ -19,17 +22,25 @@ const STALE_AFTER_MINUTES = 30;export const POST = withCron(async () => {const cutoff = subMinutes(new Date(), STALE_AFTER_MINUTES);- const [deletedRewardsCount, deletedLinkRewardsCount] = await Promise.all([- deleteOrphanedRewards(cutoff),- deleteEmptyLinkRewards(),- ]);+ const [deletedRewardsCount, deletedDiscountsCount, deletedLinkRewardsCount] =+ await Promise.all([+ deleteOrphanedRewards(cutoff),+ deleteOrphanedDiscounts(cutoff),+ deleteEmptyLinkRewards(),+ ]);- if (deletedRewardsCount === 0 && deletedLinkRewardsCount === 0) {- return logAndRespond("No orphaned rewards or empty link rewards found.");+ if (+ deletedRewardsCount === 0 &&+ deletedDiscountsCount === 0 &&+ deletedLinkRewardsCount === 0+ ) {+ return logAndRespond(+ "No orphaned rewards, discounts, or empty link rewards found.",+ );}return logAndRespond(- `Finished cleanup (${deletedRewardsCount} rewards, ${deletedLinkRewardsCount} empty link rewards deleted).`,+ `Finished cleanup (${deletedRewardsCount} rewards, ${deletedDiscountsCount} discounts, ${deletedLinkRewardsCount} empty link rewards deleted).`,);});diff --git a/apps/web/app/(ee)/api/discount-codes/route.ts b/apps/web/app/(ee)/api/discount-codes/route.tsindex c79d0ba8ca..8c45e6ee39 100644--- a/apps/web/app/(ee)/api/discount-codes/route.ts+++ b/apps/web/app/(ee)/api/discount-codes/route.ts@@ -128,6 +128,13 @@ export const POST = withWorkspace(});}+ if (!discount.programId) {+ throw new DubApiError({+ code: "not_found",+ message: `Discount ${discount.id} not found.`,+ });+ }+// A link can have only one discount codeconst duplicateByLink = programEnrollment.discountCodes.find((discountCode) => discountCode.linkId === linkId,diff --git a/apps/web/app/(ee)/api/workflows/detach-discount/route.ts b/apps/web/app/(ee)/api/workflows/detach-discount/route.tsindex f961d5e440..4da2e09c77 100644--- a/apps/web/app/(ee)/api/workflows/detach-discount/route.ts+++ b/apps/web/app/(ee)/api/workflows/detach-discount/route.ts@@ -2,7 +2,7 @@ import { logger } from "@/lib/axiom/server";import {detachDiscountFromLinkRewards,detachDiscountFromProgramEnrollments,- dispatchRemapDiscountCodes,+ syncDiscountCodes,} from "@/lib/discounts/detach-discount";import { prisma } from "@/lib/prisma";import { serve } from "@upstash/workflow/nextjs";@@ -22,8 +22,10 @@ type Input = z.infer<typeof inputSchema>;* Soft-deleted discounts (programId cleared) are cleaned up as:** 1. detach-discount-from-enrollments + detach-discount-from-link-rewards (parallel)- * 2. remap-discount-codes- * 3. delete-discount+ * 2. sync-discount-codes+ *+ * Hard-delete is deferred to /api/cron/cleanup/orphaned-rewards once syncs+ * finish and nothing still references the soft-deleted discount.*/// POST /api/workflows/detach-discount@@ -93,27 +95,14 @@ export const { POST } = serve<Input>(]);// This should run after the enrollments and link rewards are updated- await context.run("remap-discount-codes", async () => {- await dispatchRemapDiscountCodes({+ await context.run("sync-discount-codes", async () => {+ await syncDiscountCodes({programId,discountId,});return logAndReturn({- outputLog: `Remapped discount codes for discount ${discountId}`,- });- });-- // This should run after the discount codes are remapped- await context.run("delete-discount", async () => {- await prisma.discount.deleteMany({- where: {- id: discountId,- },- });-- return logAndReturn({- outputLog: `Deleted discount ${discountId}`,+ outputLog: `Synced discount codes for discount ${discountId}`,});});},diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.tsindex a7d766d4ab..c702528436 100644--- a/apps/web/lib/actions/partners/create-discount.ts+++ b/apps/web/lib/actions/partners/create-discount.ts@@ -120,6 +120,8 @@ export const createDiscountAction = authActionClientreturn discount;});+ // No need to attach the discount to the group if it is not the default+ // because the default discount is attached to the group when the discount is createdif (isDefault) {await attachDiscountJob.dispatch({ discountId: discount.id },diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.tsindex 6b39bc04f2..05497b249a 100644--- a/apps/web/lib/actions/partners/update-discount.ts+++ b/apps/web/lib/actions/partners/update-discount.ts@@ -51,45 +51,40 @@ export const updateDiscountAction = authActionClientrevalidateProgramPublicPages(programId);}- waitUntil(- Promise.allSettled([- ...(shouldExpireCache- ? [- invalidateLinksForDiscountsJob.dispatch(- {- type: "discount",- discountId: discount.id,- },- {- label: discount.id,- },- ),- ]- : []),+ await Promise.all([+ ...(shouldExpireCache+ ? [+ invalidateLinksForDiscountsJob.dispatch(+ { type: "discount", discountId: discount.id },+ { label: discount.id },+ ),+ ]+ : []),- ...(updatedDiscount.autoProvisionEnabledAt- ? [- publishDiscountCodesCreationJob.dispatch(- { discountId: discount.id },- { label: discount.id },- ),- ]- : []),+ ...(updatedDiscount.autoProvisionEnabledAt+ ? [+ publishDiscountCodesCreationJob.dispatch(+ { discountId: discount.id },+ { label: discount.id },+ ),+ ]+ : []),+ ]);- recordAuditLog({- workspaceId: workspace.id,- programId,- action: "discount.updated",- description: `Discount ${discount.id} updated`,- actor: user,- targets: [- {- type: "discount",- id: discount.id,- metadata: updatedDiscount,- },- ],- }),- ]),+ waitUntil(+ recordAuditLog({+ workspaceId: workspace.id,+ programId,+ action: "discount.updated",+ description: `Discount ${discount.id} updated`,+ actor: user,+ targets: [+ {+ type: "discount",+ id: discount.id,+ metadata: updatedDiscount,+ },+ ],+ }),);});diff --git a/apps/web/lib/actions/partners/update-partner-enrollment.ts b/apps/web/lib/actions/partners/update-partner-enrollment.tsindex 7d66bdcd80..c8ba850212 100644--- a/apps/web/lib/actions/partners/update-partner-enrollment.ts+++ b/apps/web/lib/actions/partners/update-partner-enrollment.ts@@ -15,7 +15,7 @@ import {hasRewardIdsInput,} from "@/lib/api/rewards/reward-overrides";import { throwIfInvalidRewards } from "@/lib/api/rewards/throw-if-invalid-rewards";-import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";+import { syncPartnerDiscountCodes } from "@/lib/discounts/sync-discount-codes";import { getPlanCapabilities } from "@/lib/plan-capabilities";import { prisma } from "@/lib/prisma";import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";@@ -194,7 +194,7 @@ export const updatePartnerEnrollmentAction = authActionClient});if (discountId !== undefined) {- await remapDiscountCodes({+ await syncPartnerDiscountCodes({programId,partnerId,});diff --git a/apps/web/lib/api/groups/delete-group.ts b/apps/web/lib/api/groups/delete-group.tsindex f6b2594071..572785acb7 100644--- a/apps/web/lib/api/groups/delete-group.ts+++ b/apps/web/lib/api/groups/delete-group.ts@@ -69,7 +69,7 @@ export async function deletePartnerGroup(},}),- // Soft delete discounts (detach workflow hard-deletes after remapping)+ // Soft delete discounts (orphaned-rewards cron hard-deletes after remapping)prisma.discount.updateMany({where: {groupId: group.id,diff --git a/apps/web/lib/api/partners/update-partner-link.ts b/apps/web/lib/api/partners/update-partner-link.tsindex 5452926382..f3b6727ce5 100644--- a/apps/web/lib/api/partners/update-partner-link.ts+++ b/apps/web/lib/api/partners/update-partner-link.ts@@ -11,7 +11,7 @@ import {toPartnerLinkRewardIdFields,} from "@/lib/api/rewards/reward-overrides";import { throwIfInvalidRewards } from "@/lib/api/rewards/throw-if-invalid-rewards";-import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";+import { syncPartnerDiscountCodes } from "@/lib/discounts/sync-discount-codes";import { getPlanCapabilities } from "@/lib/plan-capabilities";import { prisma } from "@/lib/prisma";import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";@@ -155,7 +155,7 @@ export async function updatePartnerLink({}if (body.discountId !== undefined) {- await remapDiscountCodes({+ await syncPartnerDiscountCodes({programId,partnerId: link.partnerId,});diff --git a/apps/web/lib/discounts/attach-discount.ts b/apps/web/lib/discounts/attach-discount.tsindex f6cded74b7..dd37530d7d 100644--- a/apps/web/lib/discounts/attach-discount.ts+++ b/apps/web/lib/discounts/attach-discount.ts@@ -69,6 +69,20 @@ export async function attachDiscount({},});+ await prisma.discountCode.updateMany({+ where: {+ discountId: null,+ programEnrollment: {+ id: {+ in: pluck(enrollments, "id"),+ },+ },+ },+ data: {+ discountId: discount.id,+ },+ });+console.info(`Attached discount ${discount.id} to ${count} enrollments in group ${groupId}.`,);diff --git a/apps/web/lib/discounts/create-discount-code.ts b/apps/web/lib/discounts/create-discount-code.tsindex 335a0d1674..c70f2148a3 100644--- a/apps/web/lib/discounts/create-discount-code.ts+++ b/apps/web/lib/discounts/create-discount-code.ts@@ -134,6 +134,13 @@ async function createDiscountCodeRecord({canRetry: boolean;discountProvider: ReturnType<typeof getDiscountProvider>;}): Promise<CreateDiscountCodeRecordResult> {+ if (!discount.programId) {+ throw new DubApiError({+ code: "not_found",+ message: `Discount ${discount.id} not found.`,+ });+ }+try {const discountCode = await prisma.discountCode.create({data: {diff --git a/apps/web/lib/discounts/delete-orphaned-discounts.ts b/apps/web/lib/discounts/delete-orphaned-discounts.tsnew file mode 100644index 0000000000..e3a8639bf7--- /dev/null+++ b/apps/web/lib/discounts/delete-orphaned-discounts.ts@@ -0,0 +1,106 @@+import { pluck } from "@dub/utils";+import { prisma } from "../prisma";++// Hard-delete soft-deleted discounts (programId null) once nothing still+// references them. Detach workflow remaps codes first; this cron finishes+// cleanup after the stale cutoff so equivalence checks can still see the row.+export async function deleteOrphanedDiscounts(cutoff: Date) {+ const discounts = await prisma.discount.findMany({+ where: {+ programId: null,+ updatedAt: {+ lt: cutoff,+ },+ },+ select: {+ id: true,+ },+ orderBy: {+ updatedAt: "desc",+ },+ take: 50,+ });++ if (discounts.length === 0) {+ return 0;+ }++ const discountIds = pluck(discounts, "id");++ const [enrollments, groups, linkRewards, discountCodes] = await Promise.all([+ prisma.programEnrollment.findMany({+ where: {+ discountId: {+ in: discountIds,+ },+ },+ select: {+ discountId: true,+ },+ }),++ prisma.partnerGroup.findMany({+ where: {+ discountId: {+ in: discountIds,+ },+ },+ select: {+ discountId: true,+ },+ }),++ prisma.linkReward.findMany({+ where: {+ discountId: {+ in: discountIds,+ },+ },+ select: {+ discountId: true,+ },+ }),++ prisma.discountCode.findMany({+ where: {+ discountId: {+ in: discountIds,+ },+ },+ select: {+ discountId: true,+ },+ }),+ ]);++ const referencedDiscountIds = new Set<string>();++ for (const row of [+ ...enrollments,+ ...groups,+ ...linkRewards,+ ...discountCodes,+ ]) {+ if (row.discountId) {+ referencedDiscountIds.add(row.discountId);+ }+ }++ const discountIdsToHardDelete = discountIds.filter(+ (id) => !referencedDiscountIds.has(id),+ );++ if (discountIdsToHardDelete.length === 0) {+ return 0;+ }++ const { count } = await prisma.discount.deleteMany({+ where: {+ id: {+ in: discountIdsToHardDelete,+ },+ },+ });++ return count;+}diff --git a/apps/web/lib/discounts/detach-discount.ts b/apps/web/lib/discounts/detach-discount.tsindex 85c3c61686..a2a7c055a8 100644--- a/apps/web/lib/discounts/detach-discount.ts+++ b/apps/web/lib/discounts/detach-discount.ts@@ -154,9 +154,7 @@ export async function detachDiscountFromLinkRewards({}// Dispatch per-code remap jobs for codes still pointing at this discount-export async function dispatchRemapDiscountCodes({- discountId,-}: DetachDiscountParams) {+export async function syncDiscountCodes({ discountId }: DetachDiscountParams) {let startAfterId: string | null = null;while (true) {diff --git a/apps/web/lib/discounts/remap-discount-codes.ts b/apps/web/lib/discounts/sync-discount-codes.tssimilarity index 88%rename from apps/web/lib/discounts/remap-discount-codes.tsrename to apps/web/lib/discounts/sync-discount-codes.tsindex 78236785e5..46c7f73f48 100644--- a/apps/web/lib/discounts/remap-discount-codes.ts+++ b/apps/web/lib/discounts/sync-discount-codes.ts@@ -3,9 +3,10 @@ import { remapDiscountCodeJob } from "@/lib/jobs/handlers/remap-discount-code-joimport { prisma } from "@/lib/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { Discount, ProgramEnrollment } from "@prisma/client";+import { ACTIVE_ENROLLMENT_STATUSES } from "../zod/schemas/partners";// Read discount codes for a partner in a program and fan out per-code remap jobs-export async function remapDiscountCodes({+export async function syncPartnerDiscountCodes({programId,partnerId,}: Pick<ProgramEnrollment, "programId" | "partnerId">) {@@ -18,6 +19,7 @@ export async function remapDiscountCodes({},select: {id: true,+ status: true,discount: true,},});@@ -29,6 +31,13 @@ export async function remapDiscountCodes({return;}+ if (!ACTIVE_ENROLLMENT_STATUSES.includes(programEnrollment.status)) {+ console.info(+ `Program enrollment is not active for partner ${partnerId} and program ${programId}. Skipping...`,+ );+ return;+ }+const discountCodes = await prisma.discountCode.findMany({where: {programId,