Просмотр исходного кода

cancle subscription uppon account deletion

Bernt Christian Egeland 9 месяцев назад
Родитель
Сommit
ae7ae3de6a
1 измененных файлов с 16 добавлено и 0 удалено
  1. 16 0
      src/features/settings/Actions/deleteAccount.ts

+ 16 - 0
src/features/settings/Actions/deleteAccount.ts

@@ -5,6 +5,7 @@ import { withAuth } from "@/lib/with-auth";
 import { resolveUploadPath } from "@/lib/resolve-upload-path";
 import { unlink, rm } from "fs/promises";
 import path from "path";
+import Stripe from "stripe";
 
 export async function deleteAccount() {
   return withAuth(async ({ userId, organizationId }) => {
@@ -47,6 +48,21 @@ export async function deleteAccount() {
         if (v.imageUrl) filePaths.push(resolveUploadPath(v.imageUrl));
       }
 
+      // Cancel Stripe subscription before deleting org data
+      const subscription = await db.subscription.findUnique({
+        where: { organizationId },
+        select: { stripeSubscriptionId: true },
+      });
+
+      if (subscription?.stripeSubscriptionId && process.env.STRIPE_SECRET_KEY) {
+        try {
+          const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
+          await stripe.subscriptions.cancel(subscription.stripeSubscriptionId);
+        } catch {
+          // Subscription may already be canceled on Stripe's side
+        }
+      }
+
       // Delete membership first (not auto-cascaded from user deletion)
       await db.organizationMember.deleteMany({
         where: { userId },