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.

Add coupon deleted webhook handler and integrate with route

Kiran K23c0be95970a
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
new file mode 100644
index 0000000000..5524d387e7
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
@@ -0,0 +1,50 @@
+import { deleteDiscount } from "@/lib/api/partners/delete-discount";
+import { prisma } from "@dub/prisma";
+import type Stripe from "stripe";
+
+// Handle event "coupon.deleted"
+export async function couponDeleted(event: Stripe.Event) {
+ const coupon = event.data.object as Stripe.Coupon;
+ const stripeAccountId = event.account as string;
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ stripeConnectId: stripeAccountId,
+ },
+ select: {
+ id: true,
+ defaultProgramId: true,
+ stripeConnectId: true,
+ },
+ });
+
+ if (!workspace) {
+ return `Workspace not found for Stripe account ${stripeAccountId}.`;
+ }
+
+ if (!workspace.defaultProgramId) {
+ return `Workspace ${workspace.id} for stripe account ${stripeAccountId} has no programs.`;
+ }
+
+ const discount = await prisma.discount.findFirst({
+ where: {
+ programId: workspace.defaultProgramId,
+ couponId: coupon.id,
+ },
+ });
+
+ if (!discount) {
+ return `Discount not found for Stripe coupon ${coupon.id}.`;
+ }
+
+ const deletedDiscountId = await deleteDiscount({
+ workspace,
+ discount,
+ });
+
+ if (deletedDiscountId) {
+ return `Discount ${deletedDiscountId} deleted.`;
+ }
+
+ return `Failed to delete discount ${discount.id}.`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
index 0d094e8aec..0decbb9897 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
@@ -4,6 +4,7 @@ import Stripe from "stripe";
import { accountApplicationDeauthorized } from "./account-application-deauthorized";
import { chargeRefunded } from "./charge-refunded";
import { checkoutSessionCompleted } from "./checkout-session-completed";
+import { couponDeleted } from "./coupon-deleted";
import { customerCreated } from "./customer-created";
import { customerUpdated } from "./customer-updated";
import { invoicePaid } from "./invoice-paid";
@@ -15,6 +16,7 @@ const relevantEvents = new Set([
"invoice.paid",
"charge.refunded",
"account.application.deauthorized",
+ "coupon.deleted",
]);
// POST /api/stripe/integration/webhook – listen to Stripe webhooks (for Stripe Integration)
@@ -74,6 +76,9 @@ export const POST = withAxiom(async (req: Request) => {
case "account.application.deauthorized":
response = await accountApplicationDeauthorized(event);
break;
+ case "coupon.deleted":
+ response = await couponDeleted(event);
+ break;
}
return new Response(response, {
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index 386939b623..118cc76b8e 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -1,14 +1,8 @@
"use server";
-import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { deleteDiscount } from "@/lib/api/partners/delete-discount";
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { qstash } from "@/lib/cron";
-import { deleteStripeCoupon } from "@/lib/stripe/delete-coupon";
-import { redis } from "@/lib/upstash";
-import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
import { z } from "zod";
import { authActionClient } from "../safe-action";
@@ -30,106 +24,9 @@ export const deleteDiscountAction = authActionClient
discountId,
});
- if (!discount.default) {
- let offset = 0;
-
- while (true) {
- const partners = await prisma.programEnrollment.findMany({
- where: {
- programId,
- discountId,
- },
- select: {
- partnerId: true,
- },
- skip: offset,
- take: 1000,
- });
-
- if (partners.length === 0) {
- break;
- }
-
- await redis.lpush(
- `discount-partners:${discountId}`,
- 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 discountId;
+ await deleteDiscount({
+ workspace,
+ discount,
+ user,
});
-
- if (deletedDiscountId) {
- waitUntil(
- Promise.allSettled([
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
- body: {
- programId,
- discountId,
- isDefault: discount.default,
- action: "discount-deleted",
- },
- }),
-
- recordAuditLog({
- workspaceId: workspace.id,
- programId,
- action: "discount.deleted",
- description: `Discount ${discountId} deleted`,
- actor: user,
- targets: [
- {
- type: "discount",
- id: discountId,
- metadata: discount,
- },
- ],
- }),
-
- // Remove the Stripe coupon if it exists
- discount.couponId &&
- deleteStripeCoupon({
- couponId: discount.couponId,
- stripeConnectId: workspace.stripeConnectId,
- }),
- ]),
- );
- }
});
diff --git a/apps/web/lib/api/partners/delete-discount.ts b/apps/web/lib/api/partners/delete-discount.ts
new file mode 100644
index 0000000000..74ddba713b
--- /dev/null
+++ b/apps/web/lib/api/partners/delete-discount.ts
@@ -0,0 +1,129 @@
+import { qstash } from "@/lib/cron";
+import { deleteStripeCoupon } from "@/lib/stripe/delete-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">;
+}) {
+ 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,
+ },
+ ],
+ })
+ : Promise.resolve(),
+
+ discount.couponId &&
+ deleteStripeCoupon({
+ couponId: discount.couponId,
+ stripeConnectId: workspace.stripeConnectId,
+ }),
+ ]),
+ );
+ }
+
+ return deletedDiscountId;
+}