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.

fix the "coupon.deleted" webhook

Kiran K1a0f2795dc70
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
index 253207de71..d20e3230fb 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
@@ -1,7 +1,8 @@
-import { deleteDiscount } from "@/lib/api/partners/delete-discount";
+import { qstash } from "@/lib/cron";
import { sendEmail } from "@dub/email";
import DiscountDeleted from "@dub/email/templates/discount-deleted";
import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
@@ -30,68 +31,116 @@ export async function couponDeleted(event: Stripe.Event) {
return `Workspace ${workspace.id} for stripe account ${stripeAccountId} has no programs.`;
}
- const discount = await prisma.discount.findUnique({
+ const discounts = await prisma.discount.findMany({
where: {
- programId_couponId: {
- programId: workspace.defaultProgramId,
- couponId: coupon.id,
+ programId: workspace.defaultProgramId,
+ OR: [{ couponId: coupon.id }, { couponTestId: coupon.id }],
+ },
+ include: {
+ partnerGroup: {
+ select: {
+ id: true,
+ },
},
},
});
- if (!discount) {
+ if (!discounts.length) {
return `Discount not found for Stripe coupon ${coupon.id}.`;
}
- const deletedDiscountId = await deleteDiscount({
- workspace,
- discount,
+ const discountIds = discounts.map((d) => d.id);
+ const groupIds = discounts
+ .map((d) => d.partnerGroup?.id)
+ .filter(Boolean) as string[];
+
+ await prisma.$transaction(async (tx) => {
+ if (groupIds.length > 0) {
+ await tx.partnerGroup.updateMany({
+ where: {
+ id: {
+ in: groupIds,
+ },
+ },
+ data: {
+ discountId: null,
+ },
+ });
+ }
+
+ if (discountIds.length > 0) {
+ await tx.programEnrollment.updateMany({
+ where: {
+ discountId: {
+ in: discountIds,
+ },
+ },
+ data: {
+ discountId: null,
+ },
+ });
+
+ await tx.discount.deleteMany({
+ where: {
+ id: {
+ in: discountIds,
+ },
+ },
+ });
+ }
});
- if (deletedDiscountId) {
- waitUntil(
- (async () => {
- const workspaceUsers = await prisma.projectUsers.findFirst({
- where: {
- projectId: workspace.id,
- role: "owner",
- user: {
- email: {
- not: null,
- },
+ waitUntil(
+ (async () => {
+ const workspaceUsers = await prisma.projectUsers.findFirst({
+ where: {
+ projectId: workspace.id,
+ role: "owner",
+ user: {
+ email: {
+ not: null,
},
},
- include: {
- user: {
- select: {
- email: true,
- },
+ },
+ include: {
+ user: {
+ select: {
+ email: true,
},
},
- });
+ },
+ });
- if (workspaceUsers) {
- const { user } = workspaceUsers;
+ if (workspaceUsers) {
+ const { user } = workspaceUsers;
- await sendEmail({
- subject: `${process.env.NEXT_PUBLIC_APP_NAME}: Discount has been deleted`,
+ await sendEmail({
+ subject: `${process.env.NEXT_PUBLIC_APP_NAME}: Discount has been deleted`,
+ email: user.email!,
+ react: DiscountDeleted({
email: user.email!,
- react: DiscountDeleted({
- email: user.email!,
- workspace: {
- slug: workspace.slug,
- },
- coupon: {
- id: coupon.id,
- },
- }),
- });
- }
- })(),
- );
+ workspace: {
+ slug: workspace.slug,
+ },
+ coupon: {
+ id: coupon.id,
+ },
+ }),
+ });
+ }
- return `Discount ${deletedDiscountId} deleted.`;
- }
+ Promise.allSettled([
+ ...groupIds.map((groupId) =>
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
+ body: {
+ groupId,
+ },
+ }),
+ ),
+ ]);
+ })(),
+ );
- return `Failed to delete discount ${discount.id}.`;
+ return `Stripe coupon ${coupon.id} deleted.`;
}
diff --git a/apps/web/lib/api/partners/delete-discount.ts b/apps/web/lib/api/partners/delete-discount.ts
deleted file mode 100644
index 7425e06831..0000000000
--- a/apps/web/lib/api/partners/delete-discount.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { qstash } from "@/lib/cron";
-import { deleteStripeCoupon } from "@/lib/stripe/delete-stripe-coupon";
-import { redis } from "@/lib/upstash";
-import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { Discount, Project, User } from "@prisma/client";
-import { waitUntil } from "@vercel/functions";
-import { recordAuditLog } from "../audit-logs/record-audit-log";
-
-export async function deleteDiscount({
- workspace,
- discount,
- user,
-}: {
- workspace: Pick<Project, "id" | "stripeConnectId" | "defaultProgramId">;
- discount: Omit<
- Discount,
- "createdAt" | "updatedAt" | "description" | "programId"
- >;
- user?: Pick<User, "id" | "email">; // the user who deleted the discount
-}) {
- const programId = workspace.defaultProgramId!;
-
- if (!discount.default) {
- let offset = 0;
-
- while (true) {
- const partners = await prisma.programEnrollment.findMany({
- where: {
- programId,
- discountId: discount.id,
- },
- select: {
- partnerId: true,
- },
- skip: offset,
- take: 1000,
- });
-
- if (partners.length === 0) {
- break;
- }
-
- await redis.lpush(
- `discount-partners:${discount.id}`,
- ...partners.map((partner) => partner.partnerId),
- );
-
- offset += 1000;
- }
- }
-
- const deletedDiscountId = await prisma.$transaction(async (tx) => {
- // 1. Find the default discount (if it exists)
- const defaultDiscount = await tx.discount.findFirst({
- where: {
- programId,
- default: true,
- },
- });
-
- // 2. Update current associations
- await tx.programEnrollment.updateMany({
- where: {
- programId,
- discountId: discount.id,
- },
- data: {
- // Replace the current discount with the default discount if it exists
- // and the discount we're deleting is not the default discount
- discountId: discount.default
- ? null
- : defaultDiscount
- ? defaultDiscount.id
- : null,
- },
- });
-
- // 3. Finally, delete the current discount
- await tx.discount.delete({
- where: {
- id: discount.id,
- },
- });
-
- return discount.id;
- });
-
- if (deletedDiscountId) {
- waitUntil(
- Promise.allSettled([
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- programId,
- discountId: discount.id,
- isDefault: discount.default,
- action: "discount-deleted",
- },
- }),
-
- user &&
- recordAuditLog({
- workspaceId: workspace.id,
- programId,
- action: "discount.deleted",
- description: `Discount ${discount.id} deleted`,
- actor: user,
- targets: [
- {
- type: "discount",
- id: discount.id,
- metadata: discount,
- },
- ],
- }),
-
- // Question:
- // Would this be a problem if the coupon is used in their application?
- discount.couponId &&
- deleteStripeCoupon({
- couponId: discount.couponId,
- stripeConnectId: workspace.stripeConnectId,
- }),
- ]),
- );
- }
-
- return deletedDiscountId;
-}
diff --git a/packages/prisma/schema/discount.prisma b/packages/prisma/schema/discount.prisma
index d5a50cfe5f..f363b84e3d 100644
--- a/packages/prisma/schema/discount.prisma
+++ b/packages/prisma/schema/discount.prisma
@@ -15,5 +15,5 @@ model Discount {
program Program @relation("ProgramDiscounts", fields: [programId], references: [id], onDelete: Cascade, onUpdate: Cascade)
partnerGroup PartnerGroup?
- @@unique([programId, couponId])
+ @@unique(programId)
}