The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Soft-delete discounts and remap codes via cleanup workflow
Kiran K2e08e517c2d7
diff --git a/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts b/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.tsindex cfb9461ed8..7bebc2c207 100644--- a/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts+++ b/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts@@ -44,6 +44,10 @@ export const POST = withCron(async ({ rawBody }) => {return logAndRespond(`Discount ${discountId} not found. Skipping...`);}+ if (!discount.programId) {+ return logAndRespond(`Discount ${discountId} is soft-deleted. Skipping...`);+ }+if (!discount.autoProvisionEnabledAt) {return logAndRespond(`Discount ${discountId} does not have auto-provision enabled. Skipping...`,@@ -52,6 +56,10 @@ export const POST = withCron(async ({ rawBody }) => {const { program } = discount;+ if (!program) {+ return logAndRespond(`Discount ${discountId} has no program. Skipping...`);+ }+const discountProvider = getDiscountProvider(discount.provider);try {diff --git a/apps/web/app/(ee)/api/workflows/discount-deletion-cleanup/route.ts b/apps/web/app/(ee)/api/workflows/discount-deletion-cleanup/route.tsnew file mode 100644index 0000000000..e9e4df7e52--- /dev/null+++ b/apps/web/app/(ee)/api/workflows/discount-deletion-cleanup/route.ts@@ -0,0 +1,142 @@+import { logger } from "@/lib/axiom/server";+import {+ deleteDiscount,+ dispatchRemapDiscountCodes,+ removeDiscountFromLinkRewards,+ removeDiscountFromProgramEnrollments,+} from "@/lib/discounts/delete-discount-cleanup";+import { prisma } from "@/lib/prisma";+import { serve } from "@upstash/workflow/nextjs";+import * as z from "zod/v4";+import { logAndReturn } from "../../cron/utils";++const inputSchema = z.object({+ programId: z.string(),+ discountId: z.string(),+});++type Input = z.infer<typeof inputSchema>;++/**+ * Discount Deletion Cleanup Workflow+ *+ * Soft-deleted discounts (programId cleared) are cleaned up as:+ *+ * 1. remove-discount-from-enrollments + remove-discount-from-link-rewards (parallel)+ * 2. remap-discount-codes+ * 3. delete-discount+ */++// POST /api/workflows/discount-deletion-cleanup+export const { POST } = serve<Input>(+ async (context) => {+ const input = inputSchema.parse(context.requestPayload);+ const { programId, discountId } = input;++ const shouldProceed = await context.run("validate-discount", async () => {+ const discount = await prisma.discount.findUnique({+ where: {+ id: discountId,+ },+ select: {+ id: true,+ programId: true,+ },+ });++ if (!discount) {+ return logAndReturn({+ proceed: false,+ outputLog: `Discount ${discountId} not found. Skipping...`,+ });+ }++ if (discount.programId !== null) {+ return logAndReturn({+ proceed: false,+ outputLog: `Discount ${discountId} is still associated with a program. Skipping...`,+ });+ }++ return logAndReturn({+ proceed: true,+ outputLog: `Proceeding with discount deletion cleanup for ${discountId}`,+ });+ });++ if (!shouldProceed.proceed) {+ return;+ }++ // Run these in parallel+ await Promise.all([+ context.run("remove-discount-from-enrollments", async () => {+ await removeDiscountFromProgramEnrollments({+ programId,+ discountId,+ });++ return logAndReturn({+ outputLog: `Removed discount ${discountId} from program enrollments`,+ });+ }),++ context.run("remove-discount-from-link-rewards", async () => {+ await removeDiscountFromLinkRewards({+ programId,+ discountId,+ });++ return logAndReturn({+ outputLog: `Removed discount ${discountId} from link rewards`,+ });+ }),+ ]);++ // This should run after the enrollments and link rewards are updated+ await context.run("remap-discount-codes", async () => {+ await dispatchRemapDiscountCodes({+ 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 deleteDiscount({+ programId,+ discountId,+ });++ return logAndReturn({+ outputLog: `Deleted discount ${discountId}`,+ });+ });+ },+ {+ failureFunction: async ({+ context,+ failStatus,+ failResponse,+ failHeaders,+ }) => {+ logger.error("workflow.failed", {+ service: "qstash",+ event: "workflow.failed",+ workflowType: "discount-deletion-cleanup",+ workflowRunId: context.workflowRunId,+ discountId: context.requestPayload?.discountId,+ programId: context.requestPayload?.programId,+ failStatus,+ failResponse,+ failHeaders,+ });++ await logger.flush();+ },+ },+);diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.tsindex 0144e7aef3..429ce53cfd 100644--- a/apps/web/lib/actions/partners/delete-discount.ts+++ b/apps/web/lib/actions/partners/delete-discount.ts@@ -3,11 +3,7 @@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 { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";-import { getPartnersByDiscountIds } from "@/lib/discounts/get-partners-by-discount-ids";-import { deleteDiscountJob } from "@/lib/jobs/handlers/delete-discount-job";-import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";-import { prisma } from "@/lib/prisma";+import { softDeleteDiscount } from "@/lib/discounts/soft-delete-discount";import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";import { authActionClient } from "../safe-action";@@ -31,138 +27,30 @@ export const deleteDiscountAction = authActionClientconst programId = getDefaultProgramIdOrThrow(workspace);- const [discount, partners] = await Promise.all([- getDiscountOrThrow({- programId,- discountId,- include: {- partnerGroup: {- select: {- discountId: true,- },- },- },- }),-- getPartnersByDiscountIds({- discountIds: [discountId],- }),- ]);-- const partnerIds = partners.map((partner) => partner.id);-- // If the partner group has a discountId and it is not the same as the discount being deleted,- // restore to that discountId; otherwise, set to null- const groupDiscountId = discount.partnerGroup?.discountId;- const restoredDiscountId =- groupDiscountId !== discount.id ? groupDiscountId : null;-- // No override, so we need to remove all discount codes for this discount- const discountCodesToRemove =- restoredDiscountId == null- ? await prisma.discountCode.findMany({- where: {- discountId: discount.id,- },- include: {- discount: true,- },- })- : null;-- await prisma.$transaction(async (tx) => {- await tx.partnerGroup.updateMany({- where: {- discountId: discount.id,- },- data: {- discountId: null,- },- });-- // Restore enrollments to the group level discount, or clear them if none- await tx.programEnrollment.updateMany({- where: {- discountId: discount.id,- },- data: {- discountId: restoredDiscountId,- },- });-- // Clear link-level discount overrides that pointed at this discount- await tx.linkReward.updateMany({- where: {- discountId: discount.id,- },- data: {- discountId: null,- },- });-- // Nothing to remap onto: delete now. If partners fall back to a group default,- // keep this row until deleteDiscountJob remaps codes (equivalence needs both discounts).- if (restoredDiscountId == null) {- await tx.discount.delete({- where: {- id: discount.id,- },- });- }+ const discount = await getDiscountOrThrow({+ programId,+ discountId,});- if (restoredDiscountId != null) {- await deleteDiscountJob.dispatch(- {- programId,- discountId: discount.id,- partnerIds,- },- {- label: discount.id,- flowControl: {- key: `delete-discount-${discount.id}`,- parallelism: 1,- },- },- );- }+ await softDeleteDiscount({+ discountId,+ programId,+ });waitUntil(- Promise.allSettled([- ...(partners.length > 0- ? [- invalidateLinksForDiscountsJob.dispatch(- {- type: "partners",- partnerIds,- programId,- },- {- label: discountId,- },- ),- ]- : []),-- ...(discountCodesToRemove != null- ? [deleteDiscountCodes(discountCodesToRemove)]- : []),-- recordAuditLog({- workspaceId: workspace.id,- programId,- action: "discount.deleted",- description: `Discount ${discountId} deleted`,- actor: user,- targets: [- {- type: "discount",- id: discountId,- metadata: discount,- },- ],- }),- ]),+ recordAuditLog({+ workspaceId: workspace.id,+ programId,+ action: "discount.deleted",+ description: `Discount ${discountId} deleted`,+ actor: user,+ targets: [+ {+ type: "discount",+ id: discountId,+ metadata: discount,+ },+ ],+ }),);});diff --git a/apps/web/lib/actions/partners/update-partner-enrollment.ts b/apps/web/lib/actions/partners/update-partner-enrollment.tsindex 5085c2974d..0e6ce5f9e8 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 { remapDiscountCodesForPartnerJob } from "@/lib/jobs/handlers/remap-discount-codes-for-partner-job";+import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";import { getPlanCapabilities } from "@/lib/plan-capabilities";import { prisma } from "@/lib/prisma";import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";@@ -189,15 +189,10 @@ export const updatePartnerEnrollmentAction = authActionClient});if (discountId !== undefined) {- await remapDiscountCodesForPartnerJob.dispatch(- {- programId,- partnerId,- },- {- label: partnerId,- },- );+ await remapDiscountCodes({+ programId,+ partnerId,+ });}waitUntil(diff --git a/apps/web/lib/api/partners/update-partner-link.ts b/apps/web/lib/api/partners/update-partner-link.tsindex fa4975fa99..2f9fd56304 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 { remapDiscountCodesForPartnerJob } from "@/lib/jobs/handlers/remap-discount-codes-for-partner-job";+import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";import { getPlanCapabilities } from "@/lib/plan-capabilities";import { prisma } from "@/lib/prisma";import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";@@ -141,15 +141,10 @@ export async function updatePartnerLink({: null;if (body.discountId !== undefined) {- await remapDiscountCodesForPartnerJob.dispatch(- {- programId,- partnerId: link.partnerId,- },- {- label: link.partnerId,- },- );+ await remapDiscountCodes({+ programId,+ partnerId: link.partnerId,+ });}waitUntil(diff --git a/apps/web/lib/discounts/delete-discount-cleanup.ts b/apps/web/lib/discounts/delete-discount-cleanup.tsnew file mode 100644index 0000000000..205c4b14d6--- /dev/null+++ b/apps/web/lib/discounts/delete-discount-cleanup.ts@@ -0,0 +1,207 @@+import { prisma } from "@/lib/prisma";+import { pluck } from "@dub/utils";+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 = {+ programId: string;+ discountId: string;+};++const BATCH_SIZE = 500;++// Remove discount from program enrollments+export async function removeDiscountFromProgramEnrollments({+ programId,+ discountId,+}: DeleteDiscountCleanupParams) {+ let startAfterId: string | null = null;++ const discount = await prisma.discount.findUnique({+ where: {+ id: discountId,+ },+ select: {+ defaultForPartnerGroup: {+ select: {+ id: true,+ },+ },+ },+ });++ if (!discount) {+ console.info(`Discount ${discountId} not found. Skipping...`);+ return;+ }++ const groupDiscountId = discount.defaultForPartnerGroup?.id ?? null;++ while (true) {+ const where: Prisma.ProgramEnrollmentWhereInput = {+ discountId,+ ...(startAfterId+ ? {+ id: {+ gt: startAfterId,+ },+ }+ : {}),+ };++ const enrollments = await prisma.programEnrollment.findMany({+ where,+ select: {+ id: true,+ partnerId: true,+ },+ orderBy: {+ id: "asc",+ },+ take: BATCH_SIZE,+ });++ if (enrollments.length === 0) {+ break;+ }++ await prisma.programEnrollment.updateMany({+ where: {+ id: {+ in: pluck(enrollments, "id"),+ },+ discountId,+ },+ data: {+ discountId: groupDiscountId,+ },+ });++ await invalidateLinksForDiscountsJob.dispatch(+ {+ type: "partners",+ programId,+ partnerIds: pluck(enrollments, "partnerId"),+ },+ {+ label: discountId,+ },+ );++ startAfterId = enrollments[enrollments.length - 1].id;++ if (enrollments.length < BATCH_SIZE) {+ break;+ }+ }+}++// Remove discount from link rewards+export async function removeDiscountFromLinkRewards({+ discountId,+}: DeleteDiscountCleanupParams) {+ let startAfterId: string | null = null;++ while (true) {+ const where: Prisma.LinkRewardWhereInput = {+ discountId,+ ...(startAfterId && {+ id: {+ gt: startAfterId,+ },+ }),+ };++ const linkRewards = await prisma.linkReward.findMany({+ where,+ select: {+ id: true,+ },+ orderBy: {+ id: "asc",+ },+ take: BATCH_SIZE,+ });++ if (linkRewards.length === 0) {+ break;+ }++ await prisma.linkReward.updateMany({+ where: {+ id: {+ in: pluck(linkRewards, "id"),+ },+ discountId,+ },+ data: {+ discountId: null,+ },+ });++ startAfterId = linkRewards[linkRewards.length - 1].id;++ if (linkRewards.length < BATCH_SIZE) {+ break;+ }+ }+}++// Dispatch per-code remap jobs for codes still pointing at this discount+export async function dispatchRemapDiscountCodes({+ discountId,+}: DeleteDiscountCleanupParams) {+ let startAfterId: string | null = null;++ while (true) {+ const where: Prisma.DiscountCodeWhereInput = {+ discountId,+ disabledAt: null,+ ...(startAfterId && {+ id: {+ gt: startAfterId,+ },+ }),+ };++ const discountCodes = await prisma.discountCode.findMany({+ where,+ select: {+ id: true,+ },+ orderBy: {+ id: "asc",+ },+ take: BATCH_SIZE,+ });++ if (discountCodes.length === 0) {+ break;+ }++ await remapDiscountCodeJob.dispatchBatch(+ discountCodes.map(({ id }) => ({+ discountCodeId: id,+ })),+ );++ startAfterId = discountCodes[discountCodes.length - 1].id;++ if (discountCodes.length < BATCH_SIZE) {+ break;+ }+ }+}++// Dispatch discount code deletion+export async function deleteDiscount({+ programId,+ discountId,+}: DeleteDiscountCleanupParams) {+ //+}diff --git a/apps/web/lib/discounts/remap-discount-code.ts b/apps/web/lib/discounts/remap-discount-code.tsnew file mode 100644index 0000000000..31a7701aed--- /dev/null+++ b/apps/web/lib/discounts/remap-discount-code.ts@@ -0,0 +1,97 @@+import { prisma } from "@/lib/prisma";+import { deleteDiscountCodes } from "./delete-discount-code";+import { isDiscountEquivalent } from "./is-discount-equivalent";++// Remap a single discount code to the partner's current enrollment/link discount+export async function remapDiscountCode({+ discountCodeId,+}: {+ discountCodeId: string;+}) {+ const discountCode = await prisma.discountCode.findUnique({+ where: {+ id: discountCodeId,+ },+ include: {+ discount: true,+ link: {+ select: {+ id: true,+ linkReward: {+ select: {+ discount: true,+ },+ },+ },+ },+ },+ });++ if (!discountCode) {+ console.info(+ `Discount code ${discountCodeId} not found. Skipping remap...`,+ );+ return;+ }++ if (discountCode.disabledAt) {+ console.info(+ `Discount code ${discountCodeId} is disabled. Skipping remap...`,+ );+ return;+ }++ const programEnrollment = await prisma.programEnrollment.findUnique({+ where: {+ partnerId_programId: {+ partnerId: discountCode.partnerId,+ programId: discountCode.programId,+ },+ },+ select: {+ discount: true,+ },+ });++ if (!programEnrollment) {+ console.info(+ `Program enrollment not found for partner ${discountCode.partnerId} and program ${discountCode.programId}. Skipping remap of discount code ${discountCodeId}...`,+ );+ return;+ }++ const existingDiscount = discountCode.discount;++ // Prefer the link discount if it exists, otherwise use the enrollment discount+ const newDiscount =+ discountCode.link?.linkReward?.discount ?? programEnrollment.discount;++ // No discount exists for this discount code, delete it+ if (!newDiscount) {+ await deleteDiscountCodes([discountCode]);+ return;+ }++ // The discount is already the correct one, skip+ if (existingDiscount?.id === newDiscount.id) {+ return;+ }++ const isEquivalent = isDiscountEquivalent(newDiscount, existingDiscount);++ // The discounts are equivalent, update the discount code to use the new discount+ if (isEquivalent) {+ await prisma.discountCode.updateMany({+ where: {+ id: discountCode.id,+ },+ data: {+ discountId: newDiscount.id,+ },+ });+ return;+ }++ // The discounts are different, delete the discount code+ await deleteDiscountCodes([discountCode]);+}diff --git a/apps/web/lib/discounts/remap-discount-codes.ts b/apps/web/lib/discounts/remap-discount-codes.tsindex f18775cd47..78236785e5 100644--- a/apps/web/lib/discounts/remap-discount-codes.ts+++ b/apps/web/lib/discounts/remap-discount-codes.ts@@ -1,11 +1,10 @@import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";+import { remapDiscountCodeJob } from "@/lib/jobs/handlers/remap-discount-code-job";import { prisma } from "@/lib/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { Discount, ProgramEnrollment } from "@prisma/client";-import { deleteDiscountCodes } from "./delete-discount-code";-import { isDiscountEquivalent } from "./is-discount-equivalent";-// Remap discount codes for a partner in a program+// Read discount codes for a partner in a program and fan out per-code remap jobsexport async function remapDiscountCodes({programId,partnerId,@@ -24,7 +23,7 @@ export async function remapDiscountCodes({});if (!programEnrollment) {- console.log(+ console.info(`Program enrollment not found for partner ${partnerId} and program ${programId}. Skipping...`,);return;@@ -36,74 +35,31 @@ export async function remapDiscountCodes({partnerId,disabledAt: null,},- include: {- discount: true,- link: {- select: {- id: true,- linkReward: {- select: {- discount: true,- },- },- },- },+ select: {+ id: true,},});if (discountCodes.length === 0) {- console.log(- `No discount codes found for partner ${partnerId} and program ${programId}. Skipping...`,+ console.info(+ `No discount codes found for partner ${partnerId} and program ${programId}. Skipping remap jobs...`,+ );+ } else {+ await remapDiscountCodeJob.dispatchBatch(+ discountCodes.map(({ id }) => ({+ discountCodeId: id,+ })),+ ({ discountCodeId }) => ({+ label: discountCodeId,+ deduplicationId: `remap-discount-code-${discountCodeId}`,+ }),);- }-- const enrollmentDiscount = programEnrollment.discount;- const discountCodesToDelete: (typeof discountCodes)[number][] = [];-- for (const discountCode of discountCodes) {- const existingDiscount = discountCode.discount;- // Prefer the link discount if it exists, otherwise use the enrollment discount- const newDiscount =- discountCode.link?.linkReward?.discount ?? enrollmentDiscount;-- // No discount exists for this discount code, delete it- if (!newDiscount) {- discountCodesToDelete.push(discountCode);- continue;- }-- // The discount is already the correct one, skip- if (existingDiscount?.id === newDiscount.id) {- continue;- }-- const isEquivalent = isDiscountEquivalent(newDiscount, existingDiscount);-- // The discounts are equivalent, update the discount code to use the new discount- if (isEquivalent) {- await prisma.discountCode.updateMany({- where: {- id: discountCode.id,- },- data: {- discountId: newDiscount.id,- },- });- continue;- }-- // The discounts are different, delete the discount code- discountCodesToDelete.push(discountCode);- }-- if (discountCodesToDelete.length > 0) {- await deleteDiscountCodes(discountCodesToDelete);}await enqueueMissingDiscountCodes({programId,partnerId,- enrollmentDiscount,+ enrollmentDiscount: programEnrollment.discount,});}diff --git a/apps/web/lib/discounts/soft-delete-discount.ts b/apps/web/lib/discounts/soft-delete-discount.tsnew file mode 100644index 0000000000..a662deddc4--- /dev/null+++ b/apps/web/lib/discounts/soft-delete-discount.ts@@ -0,0 +1,43 @@+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/delete-discount-job.ts b/apps/web/lib/jobs/handlers/delete-discount-job.tsdeleted file mode 100644index b34d1d989e..0000000000--- a/apps/web/lib/jobs/handlers/delete-discount-job.ts+++ /dev/null@@ -1,74 +0,0 @@-import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";-import { prisma } from "@/lib/prisma";-import * as z from "zod/v4";-import { defineJob } from "../index";--const BATCH_SIZE = 25;--const inputSchema = z.object({- programId: z.string(),- discountId: z.string(),- partnerIds: z.array(z.string()),-});--// Remap partner discount codes onto the restored group default, then delete-// the additional discount. Equivalence checks need both discount rows to exist.-export const deleteDiscountJob = defineJob({- name: "delete-discount-job",- schema: inputSchema,- async handle(input) {- const { programId, discountId, partnerIds } = input;-- const discount = await prisma.discount.findUnique({- where: {- id: discountId,- },- select: {- id: true,- },- });-- if (!discount) {- console.info(- `[deleteDiscountJob] Discount ${discountId} not found. Skipping...`,- );- return;- }-- for (const partnerId of partnerIds.slice(0, BATCH_SIZE)) {- await remapDiscountCodes({- programId,- partnerId,- });- }-- const remainingPartnerIds = partnerIds.slice(BATCH_SIZE);-- if (remainingPartnerIds.length > 0) {- await deleteDiscountJob.dispatch(- {- programId,- discountId,- partnerIds: remainingPartnerIds,- },- {- delay: 1,- label: discountId,- flowControl: {- key: `delete-discount-${discountId}`,- parallelism: 1,- },- },- );- return;- }-- await prisma.discount.deleteMany({- where: {- id: discountId,- },- });-- console.info(`[deleteDiscountJob] Deleted discount ${discountId}.`);- },-});diff --git a/apps/web/lib/jobs/handlers/remap-discount-code-job.ts b/apps/web/lib/jobs/handlers/remap-discount-code-job.tsnew file mode 100644index 0000000000..8a05c191be--- /dev/null+++ b/apps/web/lib/jobs/handlers/remap-discount-code-job.ts@@ -0,0 +1,16 @@+import { remapDiscountCode } from "@/lib/discounts/remap-discount-code";+import * as z from "zod/v4";+import { defineJob } from "../index";++const inputSchema = z.object({+ discountCodeId: z.string(),+});++// Remap a single discount code to the partner's current enrollment/link discount+export const remapDiscountCodeJob = defineJob({+ name: "remap-discount-code-job",+ schema: inputSchema,+ async handle(input) {+ await remapDiscountCode(input);+ },+});diff --git a/apps/web/lib/jobs/handlers/remap-discount-codes-for-partner-job.ts b/apps/web/lib/jobs/handlers/remap-discount-codes-for-partner-job.tsdeleted file mode 100644index 824a0b023f..0000000000--- a/apps/web/lib/jobs/handlers/remap-discount-codes-for-partner-job.ts+++ /dev/null@@ -1,16 +0,0 @@-import { remapDiscountCodes } from "@/lib/discounts/remap-discount-codes";-import * as z from "zod/v4";-import { defineJob } from "../index";--const inputSchema = z.object({- programId: z.string(),- partnerId: z.string(),-});--export const remapDiscountCodesForPartnerJob = defineJob({- name: "remap-discount-codes-for-partner-job",- schema: inputSchema,- async handle(input) {- await remapDiscountCodes(input);- },-});diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.tsindex 6c21044e63..06b8909917 100644--- a/apps/web/lib/jobs/registry.ts+++ b/apps/web/lib/jobs/registry.ts@@ -76,14 +76,11 @@ const jobLoaders = {(m) => m.invalidateLinksForDiscountsJob,),- "remap-discount-codes-for-partner-job": () =>- import("./handlers/remap-discount-codes-for-partner-job").then(- (m) => m.remapDiscountCodesForPartnerJob,+ "remap-discount-code-job": () =>+ import("./handlers/remap-discount-code-job").then(+ (m) => m.remapDiscountCodeJob,),- "delete-discount-job": () =>- import("./handlers/delete-discount-job").then((m) => m.deleteDiscountJob),-"aggregate-clicks-job": () =>import("./handlers/aggregate-clicks-job").then((m) => m.aggregateClicksJob),} as const satisfies Record<string, () => Promise<JobDefinition>>;diff --git a/apps/web/lib/jobs/send-workflows.ts b/apps/web/lib/jobs/send-workflows.tsindex 57374093fd..53b1e3b57b 100644--- a/apps/web/lib/jobs/send-workflows.ts+++ b/apps/web/lib/jobs/send-workflows.ts@@ -30,6 +30,8 @@ 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",} as const;for (const name of Object.keys(workflowPathMap)) {diff --git a/apps/web/prisma/schema/discount.prisma b/apps/web/prisma/schema/discount.prismaindex 4fc449e116..e9f438f2ac 100644--- a/apps/web/prisma/schema/discount.prisma+++ b/apps/web/prisma/schema/discount.prisma@@ -6,7 +6,7 @@ enum DiscountProvider {model Discount {id String @id- programId String+ programId String?groupId String?amount Int @default(0)type RewardStructure @default(percentage)@@ -20,7 +20,7 @@ model Discount {updatedAt DateTime @updatedAtprogramEnrollments ProgramEnrollment[]- program Program @relation("ProgramDiscounts", fields: [programId], references: [id])+ program Program? @relation("ProgramDiscounts", fields: [programId], references: [id])partnerGroup PartnerGroup? @relation("GroupDiscounts", fields: [groupId], references: [id], onDelete: NoAction, onUpdate: NoAction) // Owning groupdefaultForPartnerGroup PartnerGroup? @relation("PartnerGroupDefaultDiscount") // Group that uses this as its defaultdiscountCodes DiscountCode[]