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.

collect cancellation feedback

Steven Teyf3664e33ab58
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.ts
index e2035e6db5..ec113188f1 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.ts
@@ -1,20 +1,11 @@
import { isBlacklistedEmail } from "@/lib/edge-config";
import { prisma } from "@/lib/prisma";
+import { STRIPE_CANCELLATION_FEEDBACK_EMAIL_COPY } from "@/lib/stripe/cancellation-feedback";
import { sendEmail } from "@dub/email";
import Stripe from "stripe";
export const CANCELLATION_FEEDBACK_EMAIL_TYPE = "cancellationFeedbackEmail";
-const cancellationReasonMap = {
- customer_service: "you had a bad experience with our customer service",
- low_quality: "the product didn't meet your expectations",
- missing_features: "you were expecting more features",
- switched_service: "you switched to a different service",
- too_complex: "the product was too complex",
- too_expensive: "the product was too expensive",
- unused: "you didn't use the product",
-};
-
export async function sendCancellationFeedback({
workspace,
owners,
@@ -59,7 +50,10 @@ export async function sendCancellationFeedback({
},
});
- const reasonText = reason ? cancellationReasonMap[reason] : "";
+ const reasonText =
+ reason && reason in STRIPE_CANCELLATION_FEEDBACK_EMAIL_COPY
+ ? STRIPE_CANCELLATION_FEEDBACK_EMAIL_COPY[reason]
+ : "";
return await Promise.all(
owners.map(
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts
index 973929ced0..910678e051 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts
@@ -1,12 +1,15 @@
import { DubApiError } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
+import { cancelSubscriptionSchema } from "@/lib/stripe/cancellation-feedback";
import { NextResponse } from "next/server";
import Stripe from "stripe";
+import * as z from "zod/v4";
// POST /api/workspaces/[idOrSlug]/billing/cancel — toggle cancel-at-period-end on the workspace subscription (Stripe API)
export const POST = withWorkspace(
- async ({ workspace }) => {
+ async ({ workspace, req }) => {
if (!workspace.stripeId) {
throw new DubApiError({
code: "bad_request",
@@ -37,15 +40,31 @@ export const POST = withWorkspace(
});
}
- const cancelAtPeriodEnd = subscription.cancel_at_period_end ?? false;
+ const subscriptionAlreadyCancelling =
+ subscription.cancel_at_period_end ?? false;
- await stripe.subscriptions.update(subscription.id, {
- cancel_at_period_end: !cancelAtPeriodEnd,
- });
+ // If the subscription is already cancelling, we need to resume it
+ if (subscriptionAlreadyCancelling) {
+ await stripe.subscriptions.update(subscription.id, {
+ cancel_at_period_end: false,
+ });
+ } else {
+ const { feedback, comment } = cancelSubscriptionSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ await stripe.subscriptions.update(subscription.id, {
+ cancel_at_period_end: true,
+ cancellation_details: {
+ comment,
+ feedback,
+ },
+ });
+ }
return NextResponse.json({ success: true });
} catch (error) {
- if (error instanceof DubApiError) {
+ if (error instanceof DubApiError || error instanceof z.ZodError) {
throw error;
}
throw new DubApiError({
diff --git a/apps/web/lib/stripe/cancellation-feedback.ts b/apps/web/lib/stripe/cancellation-feedback.ts
new file mode 100644
index 0000000000..a8fb1ac095
--- /dev/null
+++ b/apps/web/lib/stripe/cancellation-feedback.ts
@@ -0,0 +1,56 @@
+import * as z from "zod/v4";
+
+// Stripe `cancellation_details.feedback` enum:
+// https://docs.stripe.com/api/subscriptions/cancel
+export const STRIPE_CANCELLATION_FEEDBACK = [
+ "too_expensive",
+ "missing_features",
+ "switched_service",
+ "unused",
+ "too_complex",
+ "low_quality",
+ "customer_service",
+ "other",
+] as const;
+
+export type StripeCancellationFeedback =
+ (typeof STRIPE_CANCELLATION_FEEDBACK)[number];
+
+export const STRIPE_CANCELLATION_FEEDBACK_LABELS: Record<
+ StripeCancellationFeedback,
+ string
+> = {
+ too_expensive: "It's too expensive",
+ missing_features: "Some features are missing",
+ switched_service: "I'm switching to a different service",
+ unused: "I don't use this service enough",
+ too_complex: "Ease of use was less than expected",
+ low_quality: "Quality was less than expected",
+ customer_service: "Customer service was less than expected",
+ other: "Other reason",
+};
+
+export const STRIPE_CANCELLATION_FEEDBACK_EMAIL_COPY: Record<
+ StripeCancellationFeedback,
+ string
+> = {
+ customer_service: "you had a bad experience with our customer service",
+ low_quality: "the product didn't meet your expectations",
+ missing_features: "you were expecting more features",
+ other: "you had another reason",
+ switched_service: "you switched to a different service",
+ too_complex: "the product was too complex",
+ too_expensive: "the product was too expensive",
+ unused: "you didn't use the product",
+};
+
+export const STRIPE_CANCELLATION_COMMENT_MAX_LENGTH = 1000;
+
+export const cancelSubscriptionSchema = z.object({
+ feedback: z.enum(STRIPE_CANCELLATION_FEEDBACK),
+ comment: z
+ .string()
+ .trim()
+ .min(1, "Comment is required.")
+ .max(STRIPE_CANCELLATION_COMMENT_MAX_LENGTH),
+});
diff --git a/apps/web/ui/modals/cancel-subscription-modal.tsx b/apps/web/ui/modals/cancel-subscription-modal.tsx
new file mode 100644
index 0000000000..d470a37277
--- /dev/null
+++ b/apps/web/ui/modals/cancel-subscription-modal.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import {
+ STRIPE_CANCELLATION_COMMENT_MAX_LENGTH,
+ STRIPE_CANCELLATION_FEEDBACK,
+ STRIPE_CANCELLATION_FEEDBACK_LABELS,
+ type StripeCancellationFeedback,
+} from "@/lib/stripe/cancellation-feedback";
+import { Button, Modal } from "@dub/ui";
+import { cn } from "@dub/utils";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+function CancelSubscriptionModal({
+ showCancelSubscriptionModal,
+ setShowCancelSubscriptionModal,
+ billingCycleEndsAt,
+ onConfirm,
+}: {
+ showCancelSubscriptionModal: boolean;
+ setShowCancelSubscriptionModal: Dispatch<SetStateAction<boolean>>;
+ billingCycleEndsAt?: Date | string | null;
+ onConfirm: (data: {
+ feedback: StripeCancellationFeedback;
+ comment: string;
+ }) => Promise<void>;
+}) {
+ const [isLoading, setIsLoading] = useState(false);
+ const [feedback, setFeedback] = useState<StripeCancellationFeedback | "">(
+ "",
+ );
+ const [comment, setComment] = useState("");
+
+ useEffect(() => {
+ if (!showCancelSubscriptionModal) {
+ setFeedback("");
+ setComment("");
+ setIsLoading(false);
+ }
+ }, [showCancelSubscriptionModal]);
+
+ const canSubmit = Boolean(feedback) && comment.trim().length > 0;
+
+ const handleConfirm = async () => {
+ if (isLoading || !feedback || !comment.trim()) {
+ return;
+ }
+
+ setIsLoading(true);
+ try {
+ await onConfirm({
+ feedback,
+ comment: comment.trim(),
+ });
+ setShowCancelSubscriptionModal(false);
+ } catch {
+ // Error toast is handled by the caller
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={showCancelSubscriptionModal}
+ setShowModal={setShowCancelSubscriptionModal}
+ className="max-w-md"
+ >
+ <div className="divide-y divide-neutral-200">
+ <div className="p-4 sm:px-6">
+ <h3 className="text-content-emphasis text-lg font-medium">
+ Cancel subscription
+ </h3>
+ </div>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleConfirm();
+ }}
+ >
+ <div className="flex flex-col gap-4 px-4 py-6 sm:px-6">
+ <p className="text-sm text-neutral-600">
+ Your subscription will be scheduled for cancellation at the end of
+ your current billing period
+ {billingCycleEndsAt ? (
+ <span className="font-medium text-neutral-900">
+ {" "}
+ (
+ {new Date(billingCycleEndsAt).toLocaleDateString("en-US", {
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+ })}
+ )
+ </span>
+ ) : null}
+ . You will keep access until then.
+ </p>
+
+ <div>
+ <label
+ htmlFor="cancellation-feedback"
+ className="block text-sm font-medium text-neutral-900"
+ >
+ Reason for canceling
+ </label>
+ <div className="relative mt-1.5 rounded-md shadow-sm">
+ <select
+ id="cancellation-feedback"
+ name="feedback"
+ required
+ value={feedback}
+ disabled={isLoading}
+ onChange={(e) =>
+ setFeedback(e.target.value as StripeCancellationFeedback)
+ }
+ className="block w-full rounded-md border-neutral-300 text-neutral-900 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ >
+ <option value="" disabled>
+ Select a reason
+ </option>
+ {STRIPE_CANCELLATION_FEEDBACK.map((value) => (
+ <option value={value} key={value}>
+ {STRIPE_CANCELLATION_FEEDBACK_LABELS[value]}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between">
+ <label
+ htmlFor="cancellation-comment"
+ className="block text-sm font-medium text-neutral-900"
+ >
+ Additional details
+ </label>
+ <span className="text-xs tabular-nums text-neutral-400">
+ {comment.length}/{STRIPE_CANCELLATION_COMMENT_MAX_LENGTH}
+ </span>
+ </div>
+ <textarea
+ id="cancellation-comment"
+ name="comment"
+ required
+ rows={4}
+ maxLength={STRIPE_CANCELLATION_COMMENT_MAX_LENGTH}
+ placeholder="Tell us more about why you're canceling..."
+ value={comment}
+ disabled={isLoading}
+ onChange={(e) => setComment(e.target.value)}
+ className={cn(
+ "mt-1.5 block w-full resize-y rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400",
+ "focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ )}
+ />
+ </div>
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <Button
+ type="button"
+ variant="secondary"
+ className="h-8 w-fit"
+ text="Not now"
+ disabled={isLoading}
+ onClick={() => setShowCancelSubscriptionModal(false)}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ className="h-8 w-fit"
+ text="Cancel subscription"
+ loading={isLoading}
+ disabled={!canSubmit}
+ />
+ </div>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useCancelSubscriptionModal({
+ billingCycleEndsAt,
+ onConfirm,
+}: {
+ billingCycleEndsAt?: Date | string | null;
+ onConfirm: (data: {
+ feedback: StripeCancellationFeedback;
+ comment: string;
+ }) => Promise<void>;
+}) {
+ const [showCancelSubscriptionModal, setShowCancelSubscriptionModal] =
+ useState(false);
+
+ const onConfirmRef = useRef(onConfirm);
+ onConfirmRef.current = onConfirm;
+
+ const billingCycleEndsAtRef = useRef(billingCycleEndsAt);
+ billingCycleEndsAtRef.current = billingCycleEndsAt;
+
+ const CancelSubscriptionModalCallback = useCallback(() => {
+ return (
+ <CancelSubscriptionModal
+ showCancelSubscriptionModal={showCancelSubscriptionModal}
+ setShowCancelSubscriptionModal={setShowCancelSubscriptionModal}
+ billingCycleEndsAt={billingCycleEndsAtRef.current}
+ onConfirm={(data) => onConfirmRef.current(data)}
+ />
+ );
+ }, [showCancelSubscriptionModal]);
+
+ return useMemo(
+ () => ({
+ setShowCancelSubscriptionModal,
+ CancelSubscriptionModal: CancelSubscriptionModalCallback,
+ }),
+ [setShowCancelSubscriptionModal, CancelSubscriptionModalCallback],
+ );
+}
diff --git a/apps/web/ui/modals/plan-change-confirmation-modal.tsx b/apps/web/ui/modals/plan-change-confirmation-modal.tsx
index 5e3463725d..beedac3008 100644
--- a/apps/web/ui/modals/plan-change-confirmation-modal.tsx
+++ b/apps/web/ui/modals/plan-change-confirmation-modal.tsx
@@ -239,7 +239,11 @@ function PlanChangeConfirmationModal({
onClick={async () => {
if (isSubmitting) return;
setIsSubmitting(true);
- await onConfirm();
+ try {
+ await onConfirm();
+ } finally {
+ setIsSubmitting(false);
+ }
}}
/>
</div>
diff --git a/apps/web/ui/workspaces/subscription-menu.tsx b/apps/web/ui/workspaces/subscription-menu.tsx
index 1e8d3fbd82..2333b37c21 100644
--- a/apps/web/ui/workspaces/subscription-menu.tsx
+++ b/apps/web/ui/workspaces/subscription-menu.tsx
@@ -2,6 +2,7 @@
import { clientAccessCheck } from "@/lib/client-access-check";
import { wouldLosePartnerAccess } from "@/lib/plans/has-partner-access";
+import type { StripeCancellationFeedback } from "@/lib/stripe/cancellation-feedback";
import useWorkspace from "@/lib/swr/use-workspace";
import {
Button,
@@ -16,7 +17,7 @@ import { Command } from "cmdk";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
-import { useConfirmModal } from "../modals/confirm-modal";
+import { useCancelSubscriptionModal } from "../modals/cancel-subscription-modal";
import { usePlanChangeConfirmationModal } from "../modals/plan-change-confirmation-modal";
import { ThreeDots } from "../shared/icons";
@@ -60,11 +61,19 @@ export default function SubscriptionMenu() {
});
};
- const handleCancellation = async () => {
+ const handleCancellation = async ({
+ feedback,
+ comment,
+ }: {
+ feedback: StripeCancellationFeedback;
+ comment: string;
+ }) => {
setIsOpen(false);
setClicked(true);
return fetch(`/api/workspaces/${workspaceId}/billing/cancel`, {
method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ feedback, comment }),
})
.then(async (res) => {
if (res.ok) {
@@ -77,6 +86,7 @@ export default function SubscriptionMenu() {
} else {
const { error } = await res.json();
toast.error(error.message);
+ throw new Error(error.message);
}
})
.finally(() => {
@@ -90,52 +100,29 @@ export default function SubscriptionMenu() {
defaultProgramId &&
wouldLosePartnerAccess({ currentPlan: plan, newPlan: null });
+ const { setShowCancelSubscriptionModal, CancelSubscriptionModal } =
+ useCancelSubscriptionModal({
+ billingCycleEndsAt,
+ onConfirm: handleCancellation,
+ });
+
const { setShowPlanChangeConfirmationModal, PlanChangeConfirmationModal } =
usePlanChangeConfirmationModal({
newPlan: "free",
newPeriod: "monthly",
newTier: 1,
onConfirm: async () => {
- await handleCancellation();
setShowPlanChangeConfirmationModal(false);
+ setShowCancelSubscriptionModal(true);
},
});
- const { setShowConfirmModal, confirmModal } = useConfirmModal({
- title: "Cancel subscription",
- description: (
- <p>
- Your subscription will be scheduled for cancellation at the end of your
- current billing period
- {billingCycleEndsAt ? (
- <span className="font-medium text-neutral-900">
- {" "}
- (
- {new Date(billingCycleEndsAt).toLocaleDateString("en-US", {
- month: "long",
- day: "numeric",
- year: "numeric",
- })}
- )
- </span>
- ) : (
- ""
- )}
- . You will keep access until then.
- </p>
- ),
- cancelText: "Not now",
- confirmText: "Cancel subscription",
- onConfirm: async () => {
- await handleCancellation();
- },
- });
- const handlehandleCancellation = () => {
+ const handleCancelSubscription = () => {
setIsOpen(false);
if (losesPartnerAccess) {
setShowPlanChangeConfirmationModal(true);
} else {
- setShowConfirmModal(true);
+ setShowCancelSubscriptionModal(true);
}
};
@@ -146,7 +133,7 @@ export default function SubscriptionMenu() {
return (
<>
<PlanChangeConfirmationModal />
- {confirmModal}
+ <CancelSubscriptionModal />
<Popover
openPopover={isOpen}
setOpenPopover={setIsOpen}
@@ -162,7 +149,7 @@ export default function SubscriptionMenu() {
<MenuItem
icon={SquareXmark}
label="Cancel subscription"
- onSelect={handlehandleCancellation}
+ onSelect={handleCancelSubscription}
disabledTooltip={
subscriptionCanceledAt
? "Your subscription has already been scheduled for cancellation."