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.

Filter orphan deletes to unreferenced rows and namespace group-change QStash keys.

Kiran Kba026ca045aa
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.ts
index 13291f220c..c5c5f077a4 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,7 +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 { deleteEmptyLinkRewards } from "@/lib/rewards/delete-empty-link-rewards";
import { deleteOrphanedRewards } from "@/lib/rewards/delete-orphaned-rewards";
import { subMinutes } from "date-fns";
import { logAndRespond } from "../../utils";
@@ -43,27 +42,3 @@ export const POST = withCron(async () => {
`Finished cleanup (${deletedRewardsCount} rewards, ${deletedDiscountsCount} discounts, ${deletedLinkRewardsCount} empty link rewards deleted).`,
);
});
-
-async function deleteEmptyLinkRewards() {
- let deletedCount = 0;
-
- while (true) {
- const { count } = await prisma.linkReward.deleteMany({
- where: {
- clickRewardId: null,
- leadRewardId: null,
- saleRewardId: null,
- discountId: null,
- },
- limit: PRISMA_UPDATEMANY_LIMIT,
- });
-
- if (count === 0) {
- break;
- }
-
- deletedCount += count;
- }
-
- return deletedCount;
-}
diff --git a/apps/web/lib/discounts/attach-discount.ts b/apps/web/lib/discounts/attach-discount.ts
index d4df6f86e0..9e2554ce92 100644
--- a/apps/web/lib/discounts/attach-discount.ts
+++ b/apps/web/lib/discounts/attach-discount.ts
@@ -41,10 +41,26 @@ export async function attachDiscount({
const groupId = discount.defaultForPartnerGroup.id;
+ // Inheritors only: no discount yet, or still on a soft-deleted discount
+ // owned by this group. Live partner-level overrides stay put.
+ const inheritingEnrollmentWhere = {
+ OR: [
+ { discountId: null },
+ {
+ discount: {
+ is: {
+ programId: null,
+ groupId,
+ },
+ },
+ },
+ ],
+ };
+
const enrollments = await prisma.programEnrollment.findMany({
where: {
groupId,
- discountId: null,
+ ...inheritingEnrollmentWhere,
},
select: {
id: true,
@@ -88,7 +104,7 @@ export async function attachDiscount({
in: enrollmentIds,
},
groupId,
- discountId: null,
+ ...inheritingEnrollmentWhere,
partnerGroup: {
discountId: discount.id,
},
diff --git a/apps/web/lib/discounts/delete-orphaned-discounts.ts b/apps/web/lib/discounts/delete-orphaned-discounts.ts
index 5f35af2bcc..93aa1a51e1 100644
--- a/apps/web/lib/discounts/delete-orphaned-discounts.ts
+++ b/apps/web/lib/discounts/delete-orphaned-discounts.ts
@@ -11,6 +11,10 @@ export async function deleteOrphanedDiscounts(cutoff: Date) {
updatedAt: {
lt: cutoff,
},
+ programEnrollments: { none: {} },
+ defaultForPartnerGroup: { is: null },
+ linkDiscounts: { none: {} },
+ discountCodes: { none: {} },
},
select: {
id: true,
@@ -25,71 +29,10 @@ export async function deleteOrphanedDiscounts(cutoff: Date) {
return 0;
}
- const discountIds = pluck(discounts, "id");
-
- const [enrollments, groups, linkRewards, discountCodes] = await Promise.all([
- prisma.programEnrollment.groupBy({
- by: ["discountId"],
- where: {
- discountId: {
- in: discountIds,
- },
- },
- }),
-
- prisma.partnerGroup.groupBy({
- by: ["discountId"],
- where: {
- discountId: {
- in: discountIds,
- },
- },
- }),
-
- prisma.linkReward.groupBy({
- by: ["discountId"],
- where: {
- discountId: {
- in: discountIds,
- },
- },
- }),
-
- prisma.discountCode.groupBy({
- by: ["discountId"],
- where: {
- discountId: {
- in: discountIds,
- },
- },
- }),
- ]);
-
- 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,
+ in: pluck(discounts, "id"),
},
},
});
diff --git a/apps/web/lib/discounts/detach-discount.ts b/apps/web/lib/discounts/detach-discount.ts
index 85c3c61686..723754f354 100644
--- a/apps/web/lib/discounts/detach-discount.ts
+++ b/apps/web/lib/discounts/detach-discount.ts
@@ -104,6 +104,7 @@ export async function detachDiscountFromProgramEnrollments({
// Detach discount from link rewards
export async function detachDiscountFromLinkRewards({
+ programId,
discountId,
}: DetachDiscountParams) {
let startAfterId: string | null = null;
@@ -122,6 +123,11 @@ export async function detachDiscountFromLinkRewards({
where,
select: {
id: true,
+ link: {
+ select: {
+ partnerId: true,
+ },
+ },
},
orderBy: {
id: "asc",
@@ -145,6 +151,22 @@ export async function detachDiscountFromLinkRewards({
},
});
+ const partnerIds = [
+ ...new Set(
+ linkRewards
+ .map(({ link }) => link.partnerId)
+ .filter((id): id is string => Boolean(id)),
+ ),
+ ];
+
+ if (partnerIds.length > 0) {
+ await invalidateLinksForDiscountsJob.dispatch({
+ type: "partners",
+ programId,
+ partnerIds,
+ });
+ }
+
startAfterId = linkRewards[linkRewards.length - 1].id;
if (linkRewards.length < BATCH_SIZE) {
diff --git a/apps/web/lib/jobs/handlers/process-partner-group-change-job.ts b/apps/web/lib/jobs/handlers/process-partner-group-change-job.ts
index b1919abc12..d14c7bd3ad 100644
--- a/apps/web/lib/jobs/handlers/process-partner-group-change-job.ts
+++ b/apps/web/lib/jobs/handlers/process-partner-group-change-job.ts
@@ -94,7 +94,7 @@ export const processPartnerGroupChangeJob = defineJob({
partnerIds: pluck(activeProgramEnrollments, "partnerId"),
userId: workspaceUserId,
},
- deduplicationId: idempotencyKey,
+ deduplicationId: `remap-default-links-${idempotencyKey}`,
}),
triggerDraftBountySubmissionCreation({
@@ -110,7 +110,7 @@ export const processPartnerGroupChangeJob = defineJob({
programId,
groupId,
partnerIds: movedPartnerIds,
- idempotencyKey,
+ idempotencyKey: `notify-partners-${idempotencyKey}`,
});
},
});
diff --git a/apps/web/lib/rewards/delete-empty-link-rewards.ts b/apps/web/lib/rewards/delete-empty-link-rewards.ts
new file mode 100644
index 0000000000..b91d3d82f5
--- /dev/null
+++ b/apps/web/lib/rewards/delete-empty-link-rewards.ts
@@ -0,0 +1,29 @@
+import { PRISMA_UPDATEMANY_LIMIT } from "@/lib/cron";
+import { prisma } from "../prisma";
+
+// Hard-delete LinkReward rows whose override IDs were all cleared.
+// update-partner-link nulls those IDs instead of deleting the row, and
+// discount deletes SetNull LinkReward.discountId the same way.
+export async function deleteEmptyLinkRewards() {
+ let deletedCount = 0;
+
+ while (true) {
+ const { count } = await prisma.linkReward.deleteMany({
+ where: {
+ clickRewardId: null,
+ leadRewardId: null,
+ saleRewardId: null,
+ discountId: null,
+ },
+ limit: PRISMA_UPDATEMANY_LIMIT,
+ });
+
+ if (count === 0) {
+ break;
+ }
+
+ deletedCount += count;
+ }
+
+ return deletedCount;
+}
diff --git a/apps/web/lib/rewards/delete-orphaned-rewards.ts b/apps/web/lib/rewards/delete-orphaned-rewards.ts
index 4ab23cbd5e..a2bfe6e4a0 100644
--- a/apps/web/lib/rewards/delete-orphaned-rewards.ts
+++ b/apps/web/lib/rewards/delete-orphaned-rewards.ts
@@ -1,12 +1,5 @@
import { pluck } from "@dub/utils";
import { prisma } from "../prisma";
-import { REWARD_EVENT_COLUMN_MAPPING } from "../zod/schemas/rewards";
-
-const LINK_REWARD_EVENT_COLUMNS = new Set([
- "clickRewardId",
- "leadRewardId",
- "saleRewardId",
-]);
// Delete rewards that are orphaned (not associated with a program or partner group or commissions)
export async function deleteOrphanedRewards(cutoff: Date) {
@@ -16,6 +9,44 @@ export async function deleteOrphanedRewards(cutoff: Date) {
updatedAt: {
lt: cutoff,
},
+ OR: [
+ {
+ event: "click",
+ clickEnrollments: { none: {} },
+ clickPartnerGroup: { is: null },
+ clickLinkRewards: { none: {} },
+ commissions: { none: {} },
+ },
+ {
+ event: "lead",
+ leadEnrollments: { none: {} },
+ leadPartnerGroup: { is: null },
+ leadLinkRewards: { none: {} },
+ commissions: { none: {} },
+ },
+ {
+ event: "sale",
+ saleEnrollments: { none: {} },
+ salePartnerGroup: { is: null },
+ saleLinkRewards: { none: {} },
+ commissions: { none: {} },
+ },
+ {
+ event: "referral",
+ referralEnrollments: { none: {} },
+ referralPartnerGroup: { is: null },
+ commissions: { none: {} },
+ },
+ {
+ event: "custom",
+ customEnrollments: { none: {} },
+ customPartnerGroup: { is: null },
+ commissions: { none: {} },
+ },
+ ],
+ },
+ select: {
+ id: true,
},
orderBy: {
updatedAt: "desc",
@@ -27,93 +58,11 @@ export async function deleteOrphanedRewards(cutoff: Date) {
return 0;
}
- const rewardsByEvent = Object.groupBy(rewards, (reward) => reward.event);
- const rewardIdsToHardDelete: string[] = [];
-
- for (const [event, eventRewards] of Object.entries(rewardsByEvent)) {
- if (!eventRewards?.length) {
- continue;
- }
-
- const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
- const rewardIds = pluck(eventRewards, "id");
-
- // Not all reward type support link rewards
- const canReferenceLinkReward =
- LINK_REWARD_EVENT_COLUMNS.has(rewardIdColumn);
-
- const [enrollments, groups, linkRewards, commissions] = await Promise.all([
- prisma.programEnrollment.groupBy({
- by: [rewardIdColumn],
- where: {
- [rewardIdColumn]: {
- in: rewardIds,
- },
- },
- }),
-
- prisma.partnerGroup.groupBy({
- by: [rewardIdColumn],
- where: {
- [rewardIdColumn]: {
- in: rewardIds,
- },
- },
- }),
-
- canReferenceLinkReward
- ? prisma.linkReward.groupBy({
- by: [rewardIdColumn],
- where: {
- [rewardIdColumn]: {
- in: rewardIds,
- },
- },
- })
- : Promise.resolve([]),
-
- prisma.commission.groupBy({
- by: ["rewardId"],
- where: {
- rewardId: {
- in: rewardIds,
- },
- },
- }),
- ]);
-
- // Collect all reward IDs that are referenced by enrollments, groups, link rewards, or commissions
- const referencedRewardIds = new Set<string>();
-
- for (const row of [...enrollments, ...groups, ...linkRewards]) {
- const rewardId = row[rewardIdColumn];
- if (typeof rewardId === "string") {
- referencedRewardIds.add(rewardId);
- }
- }
-
- for (const { rewardId } of commissions) {
- if (rewardId) {
- referencedRewardIds.add(rewardId);
- }
- }
-
- // If the reward is not referenced by any enrollments, groups, link rewards, or commissions, it can be hard deleted
- for (const reward of eventRewards) {
- if (!referencedRewardIds.has(reward.id)) {
- rewardIdsToHardDelete.push(reward.id);
- }
- }
- }
-
- if (rewardIdsToHardDelete.length === 0) {
- return 0;
- }
-
+ // If the reward is not referenced by any enrollments, groups, link rewards, or commissions, it can be hard deleted
const { count } = await prisma.reward.deleteMany({
where: {
id: {
- in: rewardIdsToHardDelete,
+ in: pluck(rewards, "id"),
},
},
});