Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: v1 cancel

Marc Seitz50b249a0f602
diff --git a/components/billing/upgrade-plan-container.tsx b/components/billing/upgrade-plan-container.tsx
index 63ec9eab..e220c938 100644
--- a/components/billing/upgrade-plan-container.tsx
+++ b/components/billing/upgrade-plan-container.tsx
@@ -4,6 +4,7 @@ import { useRouter } from "next/router";
import { useState } from "react";
import { useTeam } from "@/context/team-context";
+import { CancellationModal } from "@/ee/features/cancellation/components";
import { PlanEnum } from "@/ee/stripe/constants";
import { usePlan } from "@/lib/swr/use-billing";
@@ -22,6 +23,8 @@ import { UpgradeButton } from "@/components/ui/upgrade-button";
export default function UpgradePlanContainer() {
const router = useRouter();
const [loading, setLoading] = useState<boolean>(false);
+ const [cancellationModalOpen, setCancellationModalOpen] =
+ useState<boolean>(false);
const teamInfo = useTeam();
const { plan, isFree, isDataroomsPlus } = usePlan();
@@ -69,39 +72,55 @@ export default function UpgradePlanContainer() {
);
} else {
return (
- <Button onClick={manageSubscription} loading={loading}>
- Manage Subscription
- </Button>
+ <div className="flex items-center gap-3">
+ <Button
+ variant="outline"
+ onClick={() => setCancellationModalOpen(true)}
+ className="text-muted-foreground hover:text-foreground"
+ >
+ Cancel subscription
+ </Button>
+ <Button onClick={manageSubscription} loading={loading}>
+ Manage Subscription
+ </Button>
+ </div>
);
}
};
return (
- <div className="rounded-lg">
- <Card className="bg-transparent">
- <CardHeader>
- <CardTitle>Billing</CardTitle>
- <CardDescription>
- You are currently on the{" "}
- <span className="mx-0.5 rounded-full bg-background px-2.5 py-1 text-xs font-bold tracking-normal text-foreground ring-1 ring-gray-800 dark:ring-gray-400">
- {isDataroomsPlus
- ? "Datarooms+"
- : plan.charAt(0).toUpperCase() + plan.slice(1)}
- </span>{" "}
- plan.{" "}
- <Link
- href="/settings/upgrade"
- className="text-sm underline underline-offset-4 hover:text-foreground"
- >
- See all plans
- </Link>
- </CardDescription>
- </CardHeader>
- <CardContent></CardContent>
- <CardFooter className="flex items-center justify-end rounded-b-lg border-t px-6 py-3">
- <div className="shrink-0">{ButtonList()}</div>
- </CardFooter>
- </Card>
- </div>
+ <>
+ <div className="rounded-lg">
+ <Card className="bg-transparent">
+ <CardHeader>
+ <CardTitle>Billing</CardTitle>
+ <CardDescription>
+ You are currently on the{" "}
+ <span className="mx-0.5 rounded-full bg-background px-2.5 py-1 text-xs font-bold tracking-normal text-foreground ring-1 ring-gray-800 dark:ring-gray-400">
+ {isDataroomsPlus
+ ? "Datarooms+"
+ : plan.charAt(0).toUpperCase() + plan.slice(1)}
+ </span>{" "}
+ plan.{" "}
+ <Link
+ href="/settings/upgrade"
+ className="text-sm underline underline-offset-4 hover:text-foreground"
+ >
+ See all plans
+ </Link>
+ </CardDescription>
+ </CardHeader>
+ <CardContent></CardContent>
+ <CardFooter className="flex items-center justify-end rounded-b-lg border-t px-6 py-3">
+ <div className="shrink-0">{ButtonList()}</div>
+ </CardFooter>
+ </Card>
+ </div>
+
+ <CancellationModal
+ open={cancellationModalOpen}
+ onOpenChange={setCancellationModalOpen}
+ />
+ </>
);
}
diff --git a/ee/features/cancellation/components/cancellation-modal.tsx b/ee/features/cancellation/components/cancellation-modal.tsx
new file mode 100644
index 00000000..e506c87e
--- /dev/null
+++ b/ee/features/cancellation/components/cancellation-modal.tsx
@@ -0,0 +1,307 @@
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { ArrowLeft } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Modal } from "@/components/ui/modal";
+
+import { ConfirmCancellationModal } from "./confirm-cancellation-modal";
+import { FeedbackModal } from "./feedback-modal";
+import { PauseSubscriptionModal } from "./pause-subscription-modal";
+import { RetentionOfferModal } from "./retention-offer-modal";
+import { ScheduleCallModal } from "./schedule-call-modal";
+
+type CancellationReason =
+ | "too-expensive"
+ | "not-using-enough"
+ | "missing-features"
+ | "technical-issues"
+ | "switching-competitor"
+ | "other";
+
+type CancellationStep =
+ | "reason"
+ | "retention-offer"
+ | "pause-offer"
+ | "feedback"
+ | "confirm"
+ | "schedule-call"
+ | "final-feedback";
+
+interface CancellationModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function CancellationModal({
+ open,
+ onOpenChange,
+}: CancellationModalProps) {
+ // Start with pause offer - this should be the first thing users see
+ const [currentStep, setCurrentStep] =
+ useState<CancellationStep>("pause-offer");
+ const [selectedReason, setSelectedReason] =
+ useState<CancellationReason | null>(null);
+ const [feedback, setFeedback] = useState("");
+ const [loading, setLoading] = useState(false);
+
+ // Absolutely ensure we start with pause offer when component mounts
+ useEffect(() => {
+ setCurrentStep("pause-offer");
+ setSelectedReason(null);
+ setFeedback("");
+ setLoading(false);
+ }, []); // Run once on mount
+
+ // Debug state changes
+ useEffect(() => {
+ console.log("Current step changed to:", currentStep);
+ }, [currentStep]);
+
+ const router = useRouter();
+ const teamInfo = useTeam();
+
+ const reasons: { value: CancellationReason; label: string }[] = [
+ { value: "too-expensive", label: "Too expensive" },
+ { value: "not-using-enough", label: "I'm not using it enough" },
+ { value: "missing-features", label: "Missing features I need" },
+ { value: "technical-issues", label: "Technical issues" },
+ { value: "switching-competitor", label: "Switching to a competitor" },
+ { value: "other", label: "Other reason" },
+ ];
+
+ // Reset state when modal closes
+ useEffect(() => {
+ if (!open) {
+ const timeoutId = setTimeout(() => {
+ console.log("Modal closed, resetting state");
+ setCurrentStep("pause-offer");
+ setSelectedReason(null);
+ setFeedback("");
+ setLoading(false);
+ }, 150);
+ return () => clearTimeout(timeoutId);
+ }
+ }, [open]);
+
+ const handleReasonClick = (reason: CancellationReason) => {
+ setSelectedReason(reason);
+ // Route based on reason - only "other" goes to feedback first
+ switch (reason) {
+ case "too-expensive":
+ setCurrentStep("retention-offer");
+ break;
+ case "not-using-enough":
+ setCurrentStep("pause-offer");
+ break;
+ case "missing-features":
+ setCurrentStep("schedule-call");
+ break;
+ case "technical-issues":
+ setCurrentStep("retention-offer");
+ break;
+ case "switching-competitor":
+ setCurrentStep("retention-offer");
+ break;
+ case "other":
+ setCurrentStep("feedback"); // Only "other" goes to feedback first
+ break;
+ default:
+ setCurrentStep("confirm");
+ }
+ };
+
+ const handleBack = () => {
+ switch (currentStep) {
+ case "reason":
+ // From reason selection, go back to pause offer
+ setCurrentStep("pause-offer");
+ break;
+ case "retention-offer":
+ case "schedule-call":
+ setCurrentStep("reason");
+ break;
+ case "feedback":
+ // From "other" reason feedback, go back to reason selection
+ setCurrentStep("reason");
+ break;
+ case "confirm":
+ // Go back to the appropriate step based on reason
+ if (selectedReason === "missing-features") {
+ setCurrentStep("schedule-call");
+ } else if (selectedReason === "not-using-enough") {
+ setCurrentStep("pause-offer");
+ } else if (selectedReason === "other") {
+ setCurrentStep("feedback"); // Go back to "other" feedback
+ } else {
+ setCurrentStep("retention-offer");
+ }
+ break;
+ case "final-feedback":
+ // From final feedback, close modal
+ onOpenChange(false);
+ break;
+ case "pause-offer":
+ default:
+ onOpenChange(false);
+ }
+ };
+
+ const handleClose = () => {
+ onOpenChange(false);
+ };
+
+ if (!open) {
+ return null;
+ }
+
+ if (currentStep === "pause-offer") {
+ return (
+ <PauseSubscriptionModal
+ open={open}
+ onOpenChange={onOpenChange}
+ onBack={handleBack}
+ onDecline={() => setCurrentStep("reason")} // Declining pause leads to reason selection
+ onClose={handleClose}
+ />
+ );
+ }
+
+ if (currentStep === "reason") {
+ return (
+ <Modal
+ showModal={open}
+ setShowModal={(show: boolean | ((prev: boolean) => boolean)) => {
+ if (typeof show === "function") {
+ onOpenChange(show(open));
+ } else {
+ onOpenChange(show);
+ }
+ }}
+ className="max-w-lg"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <DialogTitle className="text-2xl font-semibold">
+ Why do you want to cancel?
+ </DialogTitle>
+ <DialogDescription className="text-center text-base text-muted-foreground">
+ Help us understand what we could improve
+ </DialogDescription>
+ </div>
+
+ <div className="px-4 py-6 dark:bg-gray-900 sm:px-8">
+ <div className="space-y-3">
+ {reasons.map((reason) => (
+ <button
+ key={reason.value}
+ onClick={() => handleReasonClick(reason.value)}
+ className="w-full rounded-lg border border-gray-200 bg-white p-4 text-left transition-colors hover:ring-1 hover:ring-gray-800 dark:border-gray-700 dark:bg-gray-800 dark:hover:ring-gray-200"
+ >
+ <div className="text-sm font-medium">{reason.label}</div>
+ </button>
+ ))}
+
+ <div className="flex items-center justify-between border-t pt-4">
+ <Button
+ variant="ghost"
+ onClick={handleBack}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+ }
+
+ if (currentStep === "retention-offer") {
+ return (
+ <RetentionOfferModal
+ open={open}
+ onOpenChange={onOpenChange}
+ reason={selectedReason!}
+ onBack={handleBack}
+ onDecline={() => setCurrentStep("confirm")}
+ onClose={handleClose}
+ />
+ );
+ }
+
+ if (currentStep === "schedule-call") {
+ return (
+ <ScheduleCallModal
+ open={open}
+ onOpenChange={onOpenChange}
+ reason={selectedReason!}
+ onBack={handleBack}
+ onDecline={() => setCurrentStep("confirm")}
+ />
+ );
+ }
+
+ if (currentStep === "confirm") {
+ return (
+ <ConfirmCancellationModal
+ open={open}
+ onOpenChange={onOpenChange}
+ onBack={handleBack}
+ onClose={handleClose}
+ reason={selectedReason!}
+ feedback={feedback}
+ onConfirm={() => {
+ console.log(
+ "Confirm cancellation onConfirm called, setting step to final-feedback",
+ );
+ setCurrentStep("final-feedback");
+ }} // After confirming cancellation, show final feedback
+ />
+ );
+ }
+
+ if (currentStep === "feedback") {
+ return (
+ <FeedbackModal
+ open={open}
+ onOpenChange={onOpenChange}
+ reason={selectedReason!}
+ feedback={feedback}
+ onFeedbackChange={setFeedback}
+ onBack={handleBack}
+ onContinue={() => {
+ // For "other" reason, continue to confirmation
+ setCurrentStep("confirm");
+ }}
+ isFinalStep={false} // This is the "other" reason feedback, not final
+ />
+ );
+ }
+
+ if (currentStep === "final-feedback") {
+ console.log("Rendering final-feedback modal");
+ return (
+ <FeedbackModal
+ open={open}
+ onOpenChange={onOpenChange}
+ reason={selectedReason!}
+ feedback={feedback}
+ onFeedbackChange={setFeedback}
+ onBack={handleBack}
+ onContinue={() => {
+ // Final step - close modal after feedback
+ console.log("Final feedback submitted, closing modal");
+ onOpenChange(false);
+ }}
+ isFinalStep={true} // This is the final "Sorry to see you go" feedback
+ />
+ );
+ }
+
+ return null;
+}
diff --git a/ee/features/cancellation/components/confirm-cancellation-modal.tsx b/ee/features/cancellation/components/confirm-cancellation-modal.tsx
new file mode 100644
index 00000000..66d87fde
--- /dev/null
+++ b/ee/features/cancellation/components/confirm-cancellation-modal.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { ArrowLeft } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Modal } from "@/components/ui/modal";
+
+type CancellationReason =
+ | "too-expensive"
+ | "not-using-enough"
+ | "missing-features"
+ | "technical-issues"
+ | "switching-competitor"
+ | "other";
+
+interface ConfirmCancellationModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onBack: () => void;
+ onClose: () => void;
+ reason: CancellationReason;
+ feedback: string;
+ onConfirm?: () => void;
+}
+
+export function ConfirmCancellationModal({
+ open,
+ onOpenChange,
+ onBack,
+ onClose,
+ reason,
+ feedback,
+ onConfirm,
+}: ConfirmCancellationModalProps) {
+ const [loading, setLoading] = useState(false);
+ const teamInfo = useTeam();
+
+ const handleConfirmCancellation = async () => {
+ if (!teamInfo?.currentTeam?.id) {
+ toast.error("Team information not found");
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamInfo.currentTeam.id}/billing/cancel`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ reason,
+ feedback,
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to cancel subscription");
+ }
+
+ const data = await response.json();
+
+ toast.success("Subscription cancelled successfully.");
+
+ // Always show feedback modal after successful cancellation
+ console.log("Cancellation successful, calling onConfirm:", !!onConfirm);
+ if (onConfirm) {
+ onConfirm();
+ } else {
+ // Fallback if onConfirm not provided - should not happen in normal flow
+ console.warn("onConfirm not provided, closing modal");
+ onClose();
+ window.location.reload();
+ }
+ } catch (error) {
+ console.error("Error cancelling subscription:", error);
+ toast.error("Failed to cancel subscription. Please try again.");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={open}
+ setShowModal={(show: boolean | ((prev: boolean) => boolean)) => {
+ if (typeof show === "function") {
+ onOpenChange(show(open));
+ } else {
+ onOpenChange(show);
+ }
+ }}
+ className="max-w-lg"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <DialogTitle className="text-2xl font-semibold">
+ Confirm cancellation
+ </DialogTitle>
+ <DialogDescription className="text-center text-base text-muted-foreground">
+ Your subscription will end on January 15, 2024
+ </DialogDescription>
+ </div>
+
+ <div className="bg-muted px-4 py-8 dark:bg-gray-900 sm:px-8">
+ <div className="space-y-6">
+ <div>
+ <h3 className="mb-4 text-lg font-semibold">
+ After cancellation, you'll lose access to:
+ </h3>
+ <ul className="space-y-2 text-muted-foreground">
+ <li className="flex items-center">
+ <span className="mr-3 h-2 w-2 rounded-full bg-muted-foreground"></span>
+ All premium features
+ </li>
+ <li className="flex items-center">
+ <span className="mr-3 h-2 w-2 rounded-full bg-muted-foreground"></span>
+ Priority customer support
+ </li>
+ <li className="flex items-center">
+ <span className="mr-3 h-2 w-2 rounded-full bg-muted-foreground"></span>
+ Advanced analytics
+ </li>
+ <li className="flex items-center">
+ <span className="mr-3 h-2 w-2 rounded-full bg-muted-foreground"></span>
+ Team collaboration tools
+ </li>
+ </ul>
+ </div>
+
+ <div className="flex items-center justify-between border-t pt-4">
+ <Button
+ variant="ghost"
+ onClick={onBack}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleConfirmCancellation}
+ loading={loading}
+ >
+ Confirm cancellation
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/ee/features/cancellation/components/feedback-modal.tsx b/ee/features/cancellation/components/feedback-modal.tsx
new file mode 100644
index 00000000..d52a553a
--- /dev/null
+++ b/ee/features/cancellation/components/feedback-modal.tsx
@@ -0,0 +1,162 @@
+"use client";
+
+import { ArrowLeft } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Modal } from "@/components/ui/modal";
+import { Textarea } from "@/components/ui/textarea";
+
+type CancellationReason =
+ | "too-expensive"
+ | "not-using-enough"
+ | "missing-features"
+ | "technical-issues"
+ | "switching-competitor"
+ | "other";
+
+interface FeedbackModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ reason: CancellationReason;
+ feedback: string;
+ onFeedbackChange: (feedback: string) => void;
+ onBack: () => void;
+ onContinue: () => void;
+ isFinalStep?: boolean;
+}
+
+export function FeedbackModal({
+ open,
+ onOpenChange,
+ reason,
+ feedback,
+ onFeedbackChange,
+ onBack,
+ onContinue,
+ isFinalStep = false,
+}: FeedbackModalProps) {
+ const getTitle = () => {
+ if (isFinalStep) {
+ return "Sorry to see you go";
+ }
+
+ switch (reason) {
+ case "too-expensive":
+ return "Tell us about pricing";
+ case "not-using-enough":
+ return "Help us understand your usage";
+ case "missing-features":
+ return "What features do you need?";
+ case "technical-issues":
+ return "Tell us about the issues";
+ case "switching-competitor":
+ return "What's driving your decision?";
+ case "other":
+ return "Tell us more";
+ default:
+ return "Help us understand what we could improve";
+ }
+ };
+
+ const getSubtitle = () => {
+ if (isFinalStep) {
+ return "Please share the main reason for your cancellation to help us improve";
+ }
+
+ switch (reason) {
+ case "too-expensive":
+ return "What would make the pricing work better for your budget?";
+ case "not-using-enough":
+ return "Help us understand how we can make Papermark more valuable for your workflow.";
+ case "missing-features":
+ return "What features are you missing? This helps us prioritize our roadmap.";
+ case "technical-issues":
+ return "What technical problems have you encountered? We'd love to help resolve them.";
+ case "switching-competitor":
+ return "What does the competitor offer that we don't? This helps us improve.";
+ case "other":
+ return "We'd love to hear your specific feedback.";
+ default:
+ return "Help us understand what we could improve";
+ }
+ };
+
+ const getPlaceholder = () => {
+ if (isFinalStep) {
+ return "Please tell us the main reason you decided to cancel your subscription...";
+ }
+
+ switch (reason) {
+ case "too-expensive":
+ return "Tell us about your budget constraints or what pricing would work...";
+ case "not-using-enough":
+ return "Share how you use Papermark and what would make it more valuable...";
+ case "missing-features":
+ return "Tell us about the features you need...";
+ case "technical-issues":
+ return "Describe the technical problems you've experienced...";
+ case "switching-competitor":
+ return "Tell us about the competitor and what attracted you to them...";
+ case "other":
+ return "Share your thoughts...";
+ default:
+ return "Help us understand what we could improve...";
+ }
+ };
+
+ return (
+ <Modal
+ showModal={open}
+ setShowModal={(show: boolean | ((prev: boolean) => boolean)) => {
+ if (typeof show === "function") {
+ onOpenChange(show(open));
+ } else {
+ onOpenChange(show);
+ }
+ }}
+ className="max-w-lg"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <DialogTitle className="text-2xl font-semibold">
+ {getTitle()}
+ </DialogTitle>
+ <DialogDescription className="text-center text-base text-muted-foreground">
+ {getSubtitle()}
+ </DialogDescription>
+ </div>
+
+ <div className="bg-muted px-4 py-8 dark:bg-gray-900 sm:px-8">
+ <div className="space-y-6">
+ <Textarea
+ placeholder={getPlaceholder()}
+ value={feedback}
+ onChange={(e) => onFeedbackChange(e.target.value)}
+ rows={6}
+ className="resize-none bg-white dark:bg-gray-800"
+ />
+
+ <div className="flex items-center justify-between border-t pt-4">
+ {!isFinalStep && (
+ <Button
+ variant="ghost"
+ onClick={onBack}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ )}
+ {isFinalStep && <div />} {/* Spacer for final step */}
+ <Button
+ onClick={onContinue}
+ className="bg-gray-900 hover:bg-gray-800"
+ >
+ {isFinalStep ? "Submit" : "Continue"}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/ee/features/cancellation/components/index.ts b/ee/features/cancellation/components/index.ts
new file mode 100644
index 00000000..e7b2e435
--- /dev/null
+++ b/ee/features/cancellation/components/index.ts
@@ -0,0 +1,6 @@
+export { PauseSubscriptionModal } from "./pause-subscription-modal";
+export { RetentionOfferModal } from "./retention-offer-modal";
+export { FeedbackModal } from "./feedback-modal";
+export { ConfirmCancellationModal } from "./confirm-cancellation-modal";
+export { ScheduleCallModal } from "./schedule-call-modal";
+export { CancellationModal } from "./cancellation-modal";
diff --git a/ee/features/cancellation/components/pause-subscription-modal.tsx b/ee/features/cancellation/components/pause-subscription-modal.tsx
new file mode 100644
index 00000000..a423c1d0
--- /dev/null
+++ b/ee/features/cancellation/components/pause-subscription-modal.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { ArrowLeft, CheckCircle2 } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Modal } from "@/components/ui/modal";
+
+interface PauseSubscriptionModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onBack: () => void;
+ onDecline: () => void;
+ onClose: () => void;
+}
+
+export function PauseSubscriptionModal({
+ open,
+ onOpenChange,
+ onBack,
+ onDecline,
+ onClose,
+}: PauseSubscriptionModalProps) {
+ const [loading, setLoading] = useState(false);
+ const teamInfo = useTeam();
+
+ const handlePauseSubscription = async () => {
+ if (!teamInfo?.currentTeam?.id) {
+ toast.error("Team information not found");
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamInfo.currentTeam.id}/billing/pause`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to pause subscription");
+ }
+
+ const data = await response.json();
+
+ toast.success("Subscription paused successfully!");
+ onClose();
+
+ // Refresh the page to show updated billing status
+ window.location.reload();
+ } catch (error) {
+ console.error("Error pausing subscription:", error);
+ toast.error("Failed to pause subscription. Please try again.");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={open}
+ setShowModal={(show: boolean | ((prev: boolean) => boolean)) => {
+ if (typeof show === "function") {
+ onOpenChange(show(open));
+ } else {
+ onOpenChange(show);
+ }
+ }}
+ className="max-w-lg"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <DialogTitle className="text-2xl font-semibold">
+ Pause your subscription
+ </DialogTitle>
+ <DialogDescription className="text-center text-base text-muted-foreground">
+ Take a break for 3 months and resume when you're ready
+ </DialogDescription>
+ </div>
+
+ <div className="px-4 py-4 dark:bg-gray-900 sm:px-8">
+ <div className="space-y-6">
+ <div className="rounded-lg border border-green-200 bg-green-50 p-6 dark:border-green-800 dark:bg-green-900/10">
+ <div className="mb-4 text-base font-medium text-green-800 dark:text-green-700">
+ What pausing means for you?
+ </div>
+ <div className="space-y-3">
+ <div className="flex items-center gap-3">
+ <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-500" />
+ <span className="text-sm font-medium text-green-800 dark:text-green-700">
+ You pay €0 for 3 months
+ </span>
+ </div>
+ <div className="flex items-center gap-3">
+ <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-500" />
+ <span className="text-sm font-medium text-green-800 dark:text-green-700">
+ All your custom links continue to work
+ </span>
+ </div>
+ <div className="flex items-center gap-3">
+ <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-500" />
+ <span className="text-sm font-medium text-green-800 dark:text-green-700">
+ All your datarooms are accessible
+ </span>
+ </div>
+ </div>
+ </div>
+
+ <Button
+ onClick={handlePauseSubscription}
+ className="w-full"
+ size="lg"
+ loading={loading}
+ >
+ Pause for 3 months
+ </Button>
+
+ {/* Timeline information */}
+ <div className="space-y-3 border-t pt-4">
+ <div className="space-y-2 text-sm text-muted-foreground">
+ <div className="flex items-center justify-between">
+ <span>Pause starts:</span>
+ <span className="font-medium">Today</span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span>Reminder email:</span>
+ <span className="font-medium">3 days before resume</span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span>Auto-resume date:</span>
+ <span className="font-medium">
+ {new Date(
+ Date.now() + 90 * 24 * 60 * 60 * 1000,
+ ).toLocaleDateString("en-US", {
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+ })}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-between border-t pt-4">
+ <Button
+ variant="ghost"
+ onClick={onBack}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ <Button variant="outline" onClick={onDecline}>
+ Continue to cancellation
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/ee/features/cancellation/components/retention-offer-modal.tsx b/ee/features/cancellation/components/retention-offer-modal.tsx
new file mode 100644
index 00000000..6d2a836e
--- /dev/null
+++ b/ee/features/cancellation/components/retention-offer-modal.tsx
@@ -0,0 +1,193 @@
+"use client";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { ArrowLeft } from "lucide-react";
+import { toast } from "sonner";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Modal } from "@/components/ui/modal";
+
+type CancellationReason =
+ | "too-expensive"
+ | "not-using-enough"
+ | "missing-features"
+ | "technical-issues"
+ | "switching-competitor"
+ | "other";
+
+interface RetentionOfferModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ reason: CancellationReason;
+ onBack: () => void;
+ onDecline: () => void;
+ onClose: () => void;
+}
+
+export function RetentionOfferModal({
+ open,
+ onOpenChange,
+ reason,
+ onBack,
+ onDecline,
+ onClose,
+}: RetentionOfferModalProps) {
+ const [loading, setLoading] = useState(false);
+ const teamInfo = useTeam();
+
+ const getOfferDetails = () => {
+ switch (reason) {
+ case "too-expensive":
+ case "switching-competitor":
+ return {
+ title: "We hear you on the price",
+ subtitle: "Let us make this work for your budget",
+ discount: "25% off for 3 months",
+ savings: "€63",
+ monthlyDiscount: "€21/month",
+ duration: "over 3 months",
+ };
+ case "technical-issues":
+ return {
+ title: "Let us help you succeed",
+ subtitle: "50% off plus dedicated onboarding support",
+ discount: "50% off for 2 months + onboarding call",
+ savings: "€170",
+ monthlyDiscount: "€85/month",
+ duration: "over 2 months + free onboarding",
+ };
+ default:
+ return {
+ title: "Let's make this work",
+ subtitle: "25% off plus a call to address your specific needs",
+ discount: "25% off for 2 months + consultation call",
+ savings: "€42",
+ monthlyDiscount: "€21/month",
+ duration: "over 2 months + consultation call",
+ };
+ }
+ };
+
+ const offerDetails = getOfferDetails();
+
+ const handleAcceptOffer = async () => {
+ if (!teamInfo?.currentTeam?.id) {
+ toast.error("Team information not found");
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamInfo.currentTeam.id}/billing/retention-offer`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ reason,
+ offerType: "discount",
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to apply retention offer");
+ }
+
+ const data = await response.json();
+
+ toast.success("Offer applied successfully!");
+ onClose();
+
+ // Refresh the page to show updated billing status
+ window.location.reload();
+ } catch (error) {
+ console.error("Error applying retention offer:", error);
+ toast.error("Failed to apply offer. Please try again.");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={open}
+ setShowModal={(show: boolean | ((prev: boolean) => boolean)) => {
+ if (typeof show === "function") {
+ onOpenChange(show(open));
+ } else {
+ onOpenChange(show);
+ }
+ }}
+ className="max-w-lg"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <DialogTitle className="text-2xl font-semibold">
+ {offerDetails.title}
+ </DialogTitle>
+ <DialogDescription className="text-center text-base text-muted-foreground">
+ {offerDetails.subtitle}
+ </DialogDescription>
+ </div>
+
+ <div className="bg-muted px-4 py-8 dark:bg-gray-900 sm:px-8">
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <Badge
+ variant="secondary"
+ className="border-blue-200 bg-blue-50 text-blue-700"
+ >
+ Special offer
+ </Badge>
+ <span className="text-sm text-muted-foreground">Limited time</span>
+ </div>
+
+ <div className="text-center">
+ <h3 className="mb-2 text-xl font-semibold">
+ {offerDetails.discount}
+ </h3>
+ </div>
+
+ <div className="rounded-lg border border-green-200 bg-green-50 p-4">
+ <div className="mb-1 text-lg font-semibold text-green-800">
+ You save {offerDetails.savings}
+ </div>
+ <div className="text-sm text-green-700">
+ Save {offerDetails.monthlyDiscount} • {offerDetails.duration}
+ </div>
+ </div>
+
+ <Button
+ onClick={handleAcceptOffer}
+ className="w-full"
+ size="lg"
+ loading={loading}
+ >
+ Accept this offer
+ </Button>
+
+ <div className="flex items-center justify-between border-t pt-4">
+ <Button
+ variant="ghost"
+ onClick={onBack}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ <Button variant="outline" onClick={onDecline}>
+ Decline offer
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/ee/features/cancellation/components/schedule-call-modal.tsx b/ee/features/cancellation/components/schedule-call-modal.tsx
new file mode 100644
index 00000000..e20434a7
--- /dev/null
+++ b/ee/features/cancellation/components/schedule-call-modal.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+// Cal.com embed imports
+import Cal, { getCalApi } from "@calcom/embed-react";
+import { ArrowLeft } from "lucide-react";
+import { useSession } from "next-auth/react";
+
+import { Button } from "@/components/ui/button";
+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Modal } from "@/components/ui/modal";
+
+type CancellationReason =
+ | "too-expensive"
+ | "not-using-enough"
+ | "missing-features"
+ | "technical-issues"
+ | "switching-competitor"
+ | "other";
+
+interface ScheduleCallModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ reason: CancellationReason;
+ onBack: () => void;
+ onDecline: () => void;
+}
+
+export function ScheduleCallModal({
+ open,
+ onOpenChange,
+ reason,
+ onBack,
+ onDecline,
+}: ScheduleCallModalProps) {
+ const [calLoaded, setCalLoaded] = useState(false);
+ const { data: session } = useSession();
+
+ useEffect(() => {
+ if (open) {
+ (async function () {
+ try {
+ const cal = await getCalApi({ namespace: "papermark-support" });
+ cal("ui", { hideEventTypeDetails: true, layout: "month_view" });
+ setCalLoaded(true);
+ } catch (error) {
+ console.error("Error loading Cal.com:", error);
+ setCalLoaded(true); // Set to true anyway to show fallback
+ }
+ })();
+ }
+ }, [open]);
+
+ const getTitle = () => {
+ switch (reason) {
+ case "missing-features":
+ return "Let's talk about what you need";
+ default:
+ return "Schedule a consultation call";
+ }
+ };
+
+ const getSubtitle = () => {
+ switch (reason) {
+ case "missing-features":
+ return "Our team will reach out to understand your requirements";
+ default:
+ return "We'd love to understand how we can better serve you";
+ }
+ };
+
+ return (
+ <Modal
+ showModal={open}
+ setShowModal={(show: boolean | ((prev: boolean) => boolean)) => {
+ if (typeof show === "function") {
+ onOpenChange(show(open));
+ } else {
+ onOpenChange(show);
+ }
+ }}
+ className="max-w-lg"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <DialogTitle className="text-2xl font-semibold">
+ {getTitle()}
+ </DialogTitle>
+ <DialogDescription className="text-center text-base text-muted-foreground">
+ {getSubtitle()}
+ </DialogDescription>
+ </div>
+
+ <div className="bg-muted px-4 py-8 dark:bg-gray-900 sm:px-8">
+ <div className="space-y-6">
+ <div className="rounded-lg border border-green-200 bg-green-50 p-4">
+ <div className="mb-2 text-lg font-semibold text-green-800">
+ Free consultation
+ </div>
+ <div className="text-sm text-green-700">
+ 30-minute call • within 24 hours
+ </div>
+ </div>
+
+ {/* Cal.com embed container */}
+ <div className="max-h-[540px] rounded-lg border bg-white dark:bg-gray-800">
+ {calLoaded ? (
+ <Cal
+ namespace="papermark-support"
+ calLink={`marcseitz/papermark-support?email=${session?.user?.email}&name=${session?.user?.name}`}
+ style={{
+ width: "100%",
+ height: "540px",
+ overflow: "scroll",
+ }}
+ config={{ layout: "month_view" }}
+ />
+ ) : (
+ <div className="flex h-[500px] items-center justify-center">
+ <div className="text-center">
+ <div className="mb-2 text-lg font-semibold">
+ Loading calendar...
+ </div>
+ <div className="text-sm text-muted-foreground">
+ Please wait while we load the booking calendar
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between border-t pt-4">
+ <Button
+ variant="ghost"
+ onClick={onBack}
+ className="flex items-center gap-2"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </Button>
+ <Button variant="outline" onClick={onDecline}>
+ Decline offer
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/ee/features/conversations/components/conversation-document-context.tsx b/ee/features/conversations/components/conversation-document-context.tsx
new file mode 100644
index 00000000..0df6a421
--- /dev/null
+++ b/ee/features/conversations/components/conversation-document-context.tsx
@@ -0,0 +1,57 @@
+import { BookOpenIcon, FileTextIcon } from "lucide-react";
+
+interface ConversationDocumentContextProps {
+ dataroomDocument?: {
+ document: {
+ name: string;
+ type?: string;
+ };
+ };
+ documentPageNumber?: number | null;
+ documentVersionNumber?: number | null;
+ className?: string;
+ showVersionNumber?: boolean; // Controls whether to show version info
+}
+
+export function ConversationDocumentContext({
+ dataroomDocument,
+ documentPageNumber,
+ documentVersionNumber,
+ className = "",
+ showVersionNumber = false,
+}: ConversationDocumentContextProps) {
+ if (!dataroomDocument) return null;
+
+ const hasPageOrVersion =
+ documentPageNumber || (showVersionNumber && documentVersionNumber);
+
+ return (
+ <div
+ className={`flex items-center gap-2 rounded-lg border bg-muted/50 px-3 py-2 text-sm ${className}`}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <FileTextIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">
+ {dataroomDocument.document.name}
+ </span>
+ </div>
+
+ {hasPageOrVersion && (
+ <div className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
+ {documentPageNumber && (
+ <span className="flex items-center gap-1">
+ <BookOpenIcon className="h-3 w-3" />
+ Page {documentPageNumber}
+ </span>
+ )}
+ {documentPageNumber && showVersionNumber && documentVersionNumber && (
+ <span>•</span>
+ )}
+ {showVersionNumber && documentVersionNumber && (
+ <span>v{documentVersionNumber}</span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/ee/limits/constants.ts b/ee/limits/constants.ts
index 11100c75..549ed48a 100644
--- a/ee/limits/constants.ts
+++ b/ee/limits/constants.ts
@@ -67,3 +67,14 @@ export const DATAROOMS_PLUS_PLAN_LIMITS = {
conversationsInDataroom: true,
advancedLinkControlsOnPro: false,
};
+
+export const PAUSED_PLAN_LIMITS = {
+ // During pause: keep all data accessible but restrict new creations and views
+ canCreateLinks: false,
+ canReceiveViews: false,
+ canCreateDocuments: false,
+ canCreateDatarooms: false,
+ // Keep existing access
+ canViewAnalytics: true,
+ canAccessExistingContent: true,
+};
diff --git a/pages/api/teams/[teamId]/billing/cancel.ts b/pages/api/teams/[teamId]/billing/cancel.ts
new file mode 100644
index 00000000..f1180e80
--- /dev/null
+++ b/pages/api/teams/[teamId]/billing/cancel.ts
@@ -0,0 +1,113 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { stripeInstance } from "@/ee/stripe";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { log } from "@/lib/utils";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // POST /api/teams/:teamId/billing/cancel – cancel a user's subscription
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId } = req.query as { teamId: string };
+ const { reason, feedback } = req.body as {
+ reason: string;
+ feedback?: string;
+ };
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ stripeId: true,
+ subscriptionId: true,
+ plan: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(400).json({ error: "Team does not exist" });
+ }
+
+ if (!team.stripeId) {
+ return res.status(400).json({ error: "No Stripe customer ID" });
+ }
+
+ if (!team.subscriptionId) {
+ return res.status(400).json({ error: "No subscription ID" });
+ }
+
+ const isOldAccount = team.plan.includes("+old");
+ const stripe = stripeInstance(isOldAccount);
+
+ // Cancel the subscription in Stripe (at period end)
+ const cancelledSubscription = await stripe.subscriptions.update(
+ team.subscriptionId,
+ {
+ cancel_at_period_end: true,
+ cancellation_details: {
+ comment:
+ feedback || `Customer cancelled via flow - reason: ${reason}`,
+ feedback: reason,
+ },
+ metadata: {
+ cancelled_at: new Date().toISOString(),
+ cancellation_reason: reason,
+ user_feedback: feedback || "",
+ },
+ },
+ );
+
+ // Log the cancellation with feedback
+ await prisma.team.update({
+ where: { id: teamId },
+ data: {
+ cancellationReason: reason,
+ cancellationFeedback: feedback,
+ cancelledAt: new Date(),
+ },
+ });
+
+ await log({
+ message: `Team ${teamId} cancelled their subscription. Reason: ${reason}. Feedback: ${feedback || "None"}. Subscription will end at period end: ${new Date(cancelledSubscription.current_period_end * 1000).toISOString()}`,
+ type: "info",
+ });
+
+ res.status(200).json({
+ success: true,
+ message: "Subscription cancelled successfully",
+ endsAt: new Date(cancelledSubscription.current_period_end * 1000),
+ });
+ } catch (error) {
+ console.error("Error cancelling subscription:", error);
+ await log({
+ message: `Error cancelling subscription for team ${teamId}: ${error}`,
+ type: "error",
+ });
+ res.status(500).json({ error: "Failed to cancel subscription" });
+ }
+ } else {
+ res.setHeader("Allow", ["POST"]);
+ res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/billing/pause.ts b/pages/api/teams/[teamId]/billing/pause.ts
new file mode 100644
index 00000000..3fd5a275
--- /dev/null
+++ b/pages/api/teams/[teamId]/billing/pause.ts
@@ -0,0 +1,120 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { PAUSED_PLAN_LIMITS } from "@/ee/limits/constants";
+import { stripeInstance } from "@/ee/stripe";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { log } from "@/lib/utils";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // POST /api/teams/:teamId/billing/pause – pause a user's subscription
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId } = req.query as { teamId: string };
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ stripeId: true,
+ subscriptionId: true,
+ plan: true,
+ limits: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(400).json({ error: "Team does not exist" });
+ }
+
+ if (!team.stripeId) {
+ return res.status(400).json({ error: "No Stripe customer ID" });
+ }
+
+ if (!team.subscriptionId) {
+ return res.status(400).json({ error: "No subscription ID" });
+ }
+
+ // Check if already paused
+ if (team.plan.includes("paused")) {
+ return res.status(400).json({ error: "Subscription already paused" });
+ }
+
+ const isOldAccount = team.plan.includes("+old");
+ const stripe = stripeInstance(isOldAccount);
+
+ // Pause the subscription in Stripe
+ await stripe.subscriptions.update(team.subscriptionId, {
+ pause_collection: {
+ behavior: "void",
+ },
+ metadata: {
+ paused_at: new Date().toISOString(),
+ paused_reason: "user_request",
+ original_plan: team.plan,
+ },
+ });
+
+ // Calculate pause end date (3 months from now)
+ const pauseEndDate = new Date();
+ pauseEndDate.setMonth(pauseEndDate.getMonth() + 3);
+
+ // Update team with paused status and limits
+ const pausedPlanLimits = {
+ ...team.limits,
+ ...PAUSED_PLAN_LIMITS,
+ };
+
+ await prisma.team.update({
+ where: { id: teamId },
+ data: {
+ plan: `${team.plan}+paused`,
+ limits: pausedPlanLimits,
+ pausedAt: new Date(),
+ pauseEndsAt: pauseEndDate,
+ },
+ });
+
+ await log({
+ message: `Team ${teamId} paused their subscription for 3 months`,
+ type: "info",
+ });
+
+ res.status(200).json({
+ success: true,
+ message: "Subscription paused successfully",
+ pauseEndsAt: pauseEndDate,
+ });
+ } catch (error) {
+ console.error("Error pausing subscription:", error);
+ await log({
+ message: `Error pausing subscription for team ${teamId}: ${error}`,
+ type: "error",
+ });
+ res.status(500).json({ error: "Failed to pause subscription" });
+ }
+ } else {
+ res.setHeader("Allow", ["POST"]);
+ res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/billing/retention-offer.ts b/pages/api/teams/[teamId]/billing/retention-offer.ts
new file mode 100644
index 00000000..6bdefef9
--- /dev/null
+++ b/pages/api/teams/[teamId]/billing/retention-offer.ts
@@ -0,0 +1,124 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { stripeInstance } from "@/ee/stripe";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { log } from "@/lib/utils";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // POST /api/teams/:teamId/billing/retention-offer – apply retention offer
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId } = req.query as { teamId: string };
+ const { reason, offerType } = req.body as {
+ reason: string;
+ offerType: string;
+ };
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ stripeId: true,
+ subscriptionId: true,
+ plan: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(400).json({ error: "Team does not exist" });
+ }
+
+ if (!team.stripeId) {
+ return res.status(400).json({ error: "No Stripe customer ID" });
+ }
+
+ if (!team.subscriptionId) {
+ return res.status(400).json({ error: "No subscription ID" });
+ }
+
+ const isOldAccount = team.plan.includes("+old");
+ const stripe = stripeInstance(isOldAccount);
+
+ // Determine discount based on reason
+ let discountPercent = 25;
+ let durationMonths = 3;
+
+ if (reason === "technical-issues") {
+ discountPercent = 50;
+ durationMonths = 2;
+ } else if (
+ reason === "too-expensive" ||
+ reason === "switching-competitor"
+ ) {
+ discountPercent = 25;
+ durationMonths = 3;
+ }
+
+ // Create a discount coupon in Stripe
+ const coupon = await stripe.coupons.create({
+ percent_off: discountPercent,
+ duration: "repeating",
+ duration_in_months: durationMonths,
+ name: `Retention Offer - ${discountPercent}% off for ${durationMonths} months`,
+ metadata: {
+ reason,
+ team_id: teamId,
+ applied_at: new Date().toISOString(),
+ },
+ });
+
+ // Apply the coupon to the subscription
+ await stripe.subscriptions.update(team.subscriptionId, {
+ discounts: [{ coupon: coupon.id }],
+ metadata: {
+ retention_offer_applied: new Date().toISOString(),
+ retention_reason: reason,
+ },
+ });
+
+ await log({
+ message: `Retention offer applied to team ${teamId}: ${discountPercent}% off for ${durationMonths} months (reason: ${reason})`,
+ type: "info",
+ });
+
+ res.status(200).json({
+ success: true,
+ message: "Retention offer applied successfully",
+ discount: discountPercent,
+ duration: durationMonths,
+ couponId: coupon.id,
+ });
+ } catch (error) {
+ console.error("Error applying retention offer:", error);
+ await log({
+ message: `Error applying retention offer for team ${teamId}: ${error}`,
+ type: "error",
+ });
+ res.status(500).json({ error: "Failed to apply retention offer" });
+ }
+ } else {
+ res.setHeader("Allow", ["POST"]);
+ res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}