Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Add cancellation feedback feature for subscription management (#938)

Goldflag57808baefa11
diff --git a/client/package-lock.json b/client/package-lock.json
index aa1c93ea5..aa2b15d9c 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -8,6 +8,7 @@
"name": "client",
"version": "2.4.0",
"dependencies": {
+ "@calcom/embed-react": "^1.5.3",
"@hookform/resolvers": "5.0.1",
"@icons-pack/react-simple-icons": "^13.6.0",
"@marsidev/react-turnstile": "^1.3.1",
@@ -414,6 +415,35 @@
"resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.1.21.tgz",
"integrity": "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="
},
+ "node_modules/@calcom/embed-core": {
+ "version": "1.5.3",
+ "resolved": "https://registry.npmjs.org/@calcom/embed-core/-/embed-core-1.5.3.tgz",
+ "integrity": "sha512-GeId9gaByJ5EWiPmuvelZOvFWPOTWkcWZr5vGTCbIUTX125oE5yn0n8lDF1MJk5Xj1WO+/dk9jKIE08Ad9ytiQ==",
+ "license": "SEE LICENSE IN LICENSE"
+ },
+ "node_modules/@calcom/embed-react": {
+ "version": "1.5.3",
+ "resolved": "https://registry.npmjs.org/@calcom/embed-react/-/embed-react-1.5.3.tgz",
+ "integrity": "sha512-JCgge04pc8fhdvUmPNVLhW8/lCWK+AAziKecKWWPfv1nn2s+qKP2BwsEAnxhxK9yPOBgE1EIEgmYkrrNB1iajA==",
+ "license": "SEE LICENSE IN LICENSE",
+ "dependencies": {
+ "@calcom/embed-core": "1.5.3",
+ "@calcom/embed-snippet": "1.3.3"
+ },
+ "peerDependencies": {
+ "react": "^18.2.0 || ^19.0.0",
+ "react-dom": "^18.2.0 || ^19.0.0"
+ }
+ },
+ "node_modules/@calcom/embed-snippet": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@calcom/embed-snippet/-/embed-snippet-1.3.3.tgz",
+ "integrity": "sha512-pqqKaeLB8R6BvyegcpI9gAyY6Xyx1bKYfWvIGOvIbTpguWyM1BBBVcT9DCeGe8Zw7Ujp5K56ci7isRUrT2Uadg==",
+ "license": "SEE LICENSE IN LICENSE",
+ "dependencies": {
+ "@calcom/embed-core": "1.5.3"
+ }
+ },
"node_modules/@date-fns/tz": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.4.1.tgz",
diff --git a/client/package.json b/client/package.json
index 1b6e296dc..2c23b05ed 100644
--- a/client/package.json
+++ b/client/package.json
@@ -13,6 +13,7 @@
"format:check": "prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,scss,md}\""
},
"dependencies": {
+ "@calcom/embed-react": "^1.5.3",
"@hookform/resolvers": "5.0.1",
"@icons-pack/react-simple-icons": "^13.6.0",
"@marsidev/react-turnstile": "^1.3.1",
diff --git a/client/src/components/subscription/PaidPlain/CancellationDialog.tsx b/client/src/components/subscription/PaidPlain/CancellationDialog.tsx
new file mode 100644
index 000000000..265de4ffc
--- /dev/null
+++ b/client/src/components/subscription/PaidPlain/CancellationDialog.tsx
@@ -0,0 +1,424 @@
+"use client";
+
+import { useState } from "react";
+import Cal from "@calcom/embed-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { Textarea } from "@/components/ui/textarea";
+import { Label } from "@/components/ui/label";
+import { Loader2, AlertTriangle, BarChart3, ArrowRight } from "lucide-react";
+import { SubscriptionData } from "@/lib/subscription/useStripeSubscription";
+import {
+ useSubmitCancellationFeedback,
+} from "@/lib/subscription/useCancellationFeedback";
+import { getPlanType, getStripePrices } from "@/lib/stripe";
+import { toast } from "@/components/ui/sonner";
+
+type CancellationReason =
+ | "too_expensive"
+ | "missing_features"
+ | "not_using"
+ | "too_complex"
+ | "switching_competitor"
+ | "other";
+
+const REASONS: { value: CancellationReason; label: string }[] = [
+ { value: "too_expensive", label: "It's too expensive" },
+ { value: "missing_features", label: "Missing features I need" },
+ { value: "not_using", label: "I'm not using it enough" },
+ { value: "too_complex", label: "It's too hard to set up or use" },
+ { value: "switching_competitor", label: "Switching to another tool" },
+ { value: "other", label: "Other reason" },
+];
+
+const DETAIL_REASONS: CancellationReason[] = [
+ "missing_features",
+ "switching_competitor",
+ "other",
+];
+
+interface CancellationDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ subscription: SubscriptionData;
+ organizationId: string;
+ onProceedToStripe: () => void;
+ onChangePlan: () => void;
+}
+
+export function CancellationDialog({
+ open,
+ onOpenChange,
+ subscription,
+ organizationId,
+ onProceedToStripe,
+ onChangePlan,
+}: CancellationDialogProps) {
+ const [step, setStep] = useState<1 | 2 | 3>(1);
+ const [reason, setReason] = useState<CancellationReason | "">("");
+ const [reasonDetails, setReasonDetails] = useState("");
+ const submitFeedback = useSubmitCancellationFeedback();
+
+ const isTrial = !!subscription.isTrial;
+ const isMonthly = subscription.interval === "month";
+ const stripePlan = getStripePrices().find(
+ (p) => p.name === subscription.planName
+ );
+ const planType = getPlanType(subscription.planName);
+
+ const resetAndClose = () => {
+ setStep(1);
+ setReason("");
+ setReasonDetails("");
+ onOpenChange(false);
+ };
+
+ const feedbackPayload = (offerShown: string, accepted: boolean, outcome: string) => ({
+ organizationId,
+ reason: reason as string,
+ reasonDetails: reasonDetails || undefined,
+ retentionOfferShown: offerShown,
+ retentionOfferAccepted: accepted,
+ outcome,
+ planNameAtCancellation: subscription.planName,
+ monthlyEventCountAtCancellation: subscription.monthlyEventCount,
+ });
+
+ const handleKeepPlan = (offerShown: string) => {
+ submitFeedback.mutate(feedbackPayload(offerShown, true, "retained"), {
+ onSettled: () => {
+ toast.success("Great, we're glad you're staying!");
+ resetAndClose();
+ },
+ });
+ };
+
+ const handleSwitchToAnnual = () => {
+ submitFeedback.mutate(feedbackPayload("switch_annual", true, "retained"), {
+ onSettled: () => {
+ resetAndClose();
+ onChangePlan();
+ },
+ });
+ };
+
+ const handleDowngrade = () => {
+ submitFeedback.mutate(feedbackPayload("downgrade", true, "retained"), {
+ onSettled: () => {
+ resetAndClose();
+ onChangePlan();
+ },
+ });
+ };
+
+ const handleFinalCancel = () => {
+ submitFeedback.mutate(feedbackPayload(getRetentionOfferType(), false, "cancelled"));
+ onProceedToStripe();
+ };
+
+ const getRetentionOfferType = (): string => {
+ if (!reason) return "none";
+ if (reason === "too_expensive" && isMonthly && !isTrial) return "switch_annual";
+ if (reason === "too_expensive") return "downgrade";
+ if (reason === "missing_features") return "feature_request";
+ if (reason === "not_using") return "setup_help";
+ if (reason === "too_complex") return "setup_help";
+ return "general";
+ };
+
+ const renderStep1 = () => (
+ <div className="space-y-4">
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">
+ We'd love to understand why you're leaving so we can improve.
+ </p>
+ <RadioGroup
+ value={reason}
+ onValueChange={(v) => setReason(v as CancellationReason)}
+ >
+ {REASONS.map((r) => (
+ <div key={r.value} className="flex items-center space-x-3">
+ <RadioGroupItem value={r.value} id={r.value} />
+ <Label
+ htmlFor={r.value}
+ className="text-sm font-normal cursor-pointer"
+ >
+ {r.label}
+ </Label>
+ </div>
+ ))}
+ </RadioGroup>
+
+ {reason && DETAIL_REASONS.includes(reason) && (
+ <Textarea
+ placeholder={
+ reason === "missing_features"
+ ? "What features are you looking for?"
+ : reason === "switching_competitor"
+ ? "Which tool are you switching to?"
+ : "Tell us more..."
+ }
+ value={reasonDetails}
+ onChange={(e) => setReasonDetails(e.target.value)}
+ className="mt-2"
+ rows={3}
+ />
+ )}
+
+ <div className="flex justify-end gap-3 pt-2">
+ <Button variant="outline" onClick={resetAndClose}>
+ Never mind
+ </Button>
+ <Button
+ variant="default"
+ disabled={!reason}
+ onClick={() => setStep(2)}
+ >
+ Continue
+ </Button>
+ </div>
+ </div>
+ );
+
+ const renderStep2 = () => {
+ const renderTooExpensiveOffer = () => {
+ if (isMonthly && !isTrial) {
+ return (
+ <div className="space-y-4">
+ <div className="p-4 rounded-lg bg-neutral-50 dark:bg-neutral-800/50 border border-neutral-200 dark:border-neutral-700">
+ <h4 className="font-medium text-neutral-800 dark:text-neutral-200 mb-1">
+ Switch to annual and save 33%
+ </h4>
+ <p className="text-sm text-neutral-600 dark:text-neutral-400">
+ Pay for 8 months and get 12. That's 4 months free with annual
+ billing.
+ </p>
+ <Button
+ variant="success"
+ className="mt-3"
+ onClick={handleSwitchToAnnual}
+ >
+ Switch to Annual Billing
+ </Button>
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div className="space-y-4">
+ <div className="p-4 rounded-lg bg-neutral-50 dark:bg-neutral-800/50 border border-neutral-200 dark:border-neutral-700">
+ <h4 className="font-medium text-neutral-800 dark:text-neutral-200 mb-1">
+ Downgrade to a smaller plan
+ </h4>
+ <p className="text-sm text-neutral-600 dark:text-neutral-400">
+ You can switch to a more affordable plan that better fits your
+ needs.
+ </p>
+ <Button variant="default" className="mt-3" onClick={handleDowngrade}>
+ View Plans
+ </Button>
+ </div>
+ </div>
+ );
+ };
+
+ const renderMissingFeaturesOffer = () => (
+ <div className="space-y-4">
+ <div className="p-4 rounded-lg bg-neutral-50 dark:bg-neutral-800/50 border border-neutral-200 dark:border-neutral-700">
+ <h4 className="font-medium text-neutral-800 dark:text-neutral-200 mb-1">
+ We hear you
+ </h4>
+ <p className="text-sm text-neutral-600 dark:text-neutral-400">
+ Your feedback has been recorded and will help us prioritize our
+ roadmap. We'd love for you to stay and see the improvements.
+ </p>
+ <Button
+ variant="default"
+ className="mt-3"
+ onClick={() => handleKeepPlan("feature_request")}
+ >
+ Keep My Plan
+ </Button>
+ </div>
+ </div>
+ );
+
+ const renderTooComplexOffer = () => (
+ <div className="space-y-4">
+ <div className="p-4 rounded-lg bg-neutral-50 dark:bg-neutral-800/50 border border-neutral-200 dark:border-neutral-700">
+ <h4 className="font-medium text-neutral-800 dark:text-neutral-200 mb-1">
+ Book a free setup session
+ </h4>
+ <p className="text-sm text-neutral-600 dark:text-neutral-400 mb-3">
+ We'd love to help you get the most out of Rybbit. Book a free
+ 30-minute call and our team will help you get set up.
+ </p>
+ <Cal
+ namespace="cancellation-setup"
+ calLink="rybbit/30min"
+ style={{ width: "100%", height: "400px", overflow: "auto" }}
+ config={{
+ layout: "month_view",
+ theme: "dark",
+ }}
+ />
+ <Button
+ variant="default"
+ className="mt-3"
+ onClick={() => handleKeepPlan("setup_help")}
+ >
+ Keep My Plan
+ </Button>
+ </div>
+ </div>
+ );
+
+ const renderGenericOffer = () => (
+ <div className="space-y-4">
+ <div className="p-4 rounded-lg bg-neutral-50 dark:bg-neutral-800/50 border border-neutral-200 dark:border-neutral-700">
+ <h4 className="font-medium text-neutral-800 dark:text-neutral-200 mb-1">
+ Is there anything we can do?
+ </h4>
+ <p className="text-sm text-neutral-600 dark:text-neutral-400">
+ We're sorry to see you go. If there's anything we can do to improve
+ your experience, we'd love to hear about it.
+ </p>
+ <Button
+ variant="default"
+ className="mt-3"
+ onClick={() => handleKeepPlan("general")}
+ >
+ Keep My Plan
+ </Button>
+ </div>
+ </div>
+ );
+
+ const renderOffer = () => {
+ switch (reason) {
+ case "too_expensive":
+ return renderTooExpensiveOffer();
+ case "missing_features":
+ return renderMissingFeaturesOffer();
+ case "not_using":
+ case "too_complex":
+ return renderTooComplexOffer();
+ case "switching_competitor":
+ case "other":
+ default:
+ return renderGenericOffer();
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">
+ Before you go, we'd like to offer an alternative:
+ </p>
+ {renderOffer()}
+ <div className="flex justify-end pt-2">
+ <button
+ className="text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 underline underline-offset-2"
+ onClick={() => setStep(3)}
+ >
+ No thanks, continue cancelling
+ </button>
+ </div>
+ </div>
+ );
+ };
+
+ const renderStep3 = () => {
+ const price = stripePlan
+ ? `$${stripePlan.price}/${stripePlan.interval === "year" ? "yr" : "mo"}`
+ : null;
+
+ return (
+ <div className="space-y-4">
+ <div className="p-4 rounded-lg bg-red-50 dark:bg-red-900/10 border border-red-200 dark:border-red-800/50">
+ <div className="flex items-start gap-3">
+ <AlertTriangle className="h-5 w-5 text-red-500 dark:text-red-400 mt-0.5 shrink-0" />
+ <div className="space-y-2">
+ <h4 className="font-medium text-red-800 dark:text-red-300">
+ Here's what you'll lose
+ </h4>
+ <ul className="text-sm text-red-700 dark:text-red-400 space-y-1.5">
+ <li className="flex items-center gap-2">
+ <BarChart3 className="h-3.5 w-3.5 shrink-0" />
+ {subscription.eventLimit.toLocaleString()} events/
+ {subscription.interval === "year" ? "year" : "month"} on the{" "}
+ {planType} plan
+ {price && <span className="text-neutral-500">({price})</span>}
+ </li>
+ <li className="flex items-center gap-2">
+ <ArrowRight className="h-3.5 w-3.5 shrink-0" />
+ {subscription.monthlyEventCount.toLocaleString()} events
+ tracked this month
+ </li>
+ </ul>
+ <p className="text-sm text-red-700 dark:text-red-400 pt-1">
+ Your analytics data will no longer be collected after
+ cancellation.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-end gap-3 pt-2">
+ <Button variant="success" onClick={resetAndClose}>
+ Keep My Plan
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleFinalCancel}
+ disabled={submitFeedback.isPending}
+ >
+ {submitFeedback.isPending ? (
+ <span className="flex items-center gap-2">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Processing...
+ </span>
+ ) : isTrial ? (
+ "Cancel Trial"
+ ) : (
+ "Cancel My Subscription"
+ )}
+ </Button>
+ </div>
+ </div>
+ );
+ };
+
+ const getTitle = () => {
+ if (step === 1)
+ return isTrial
+ ? "Why are you cancelling your trial?"
+ : "Why are you leaving?";
+ if (step === 2) return "Before you go...";
+ return "Are you sure?";
+ };
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(o) => {
+ if (!o) resetAndClose();
+ else onOpenChange(o);
+ }}
+ >
+ <DialogContent className={step === 2 && reason === "too_complex" ? "max-w-2xl" : "max-w-lg"}>
+ <DialogHeader>
+ <DialogTitle>{getTitle()}</DialogTitle>
+ </DialogHeader>
+ {step === 1 && renderStep1()}
+ {step === 2 && renderStep2()}
+ {step === 3 && renderStep3()}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/client/src/components/subscription/PaidPlain/PaidPlan.tsx b/client/src/components/subscription/PaidPlain/PaidPlan.tsx
index 5368c12e5..3b02b5f53 100644
--- a/client/src/components/subscription/PaidPlain/PaidPlan.tsx
+++ b/client/src/components/subscription/PaidPlain/PaidPlan.tsx
@@ -12,6 +12,7 @@ import { useStripeSubscription } from "../../../lib/subscription/useStripeSubscr
import { UsageChart } from "../../UsageChart";
import { authClient } from "@/lib/auth";
import { InvoicesCard } from "../components/InvoicesCard";
+import { CancellationDialog } from "./CancellationDialog";
import { PlanDialog } from "./PlanDialog";
export function PaidPlan() {
@@ -23,6 +24,7 @@ export function PaidPlan() {
const [isProcessing, setIsProcessing] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
const [showPlanDialog, setShowPlanDialog] = useState(false);
+ const [showCancellationDialog, setShowCancellationDialog] = useState(false);
const isTrial = !!activeSubscription?.isTrial;
const trialDaysRemaining = activeSubscription?.trialDaysRemaining || 0;
@@ -88,7 +90,7 @@ export function PaidPlan() {
};
const handleChangePlan = () => setShowPlanDialog(true);
- const handleCancelSubscription = () => createPortalSession("subscription_cancel");
+ const handleCancelSubscription = () => setShowCancellationDialog(true);
const getFormattedPrice = () => {
if (!currentPlanDetails) return "$0/month";
@@ -124,6 +126,16 @@ export function PaidPlan() {
currentPlanName={activeSubscription?.planName}
hasActiveSubscription={!!activeSubscription}
/>
+ {activeSubscription && organizationId && (
+ <CancellationDialog
+ open={showCancellationDialog}
+ onOpenChange={setShowCancellationDialog}
+ subscription={activeSubscription}
+ organizationId={organizationId}
+ onProceedToStripe={() => createPortalSession("subscription_cancel")}
+ onChangePlan={handleChangePlan}
+ />
+ )}
<Card>
<CardContent>
<div className="space-y-6 mt-3 p-2">
diff --git a/client/src/lib/subscription/useCancellationFeedback.ts b/client/src/lib/subscription/useCancellationFeedback.ts
new file mode 100644
index 000000000..5978bf8bb
--- /dev/null
+++ b/client/src/lib/subscription/useCancellationFeedback.ts
@@ -0,0 +1,34 @@
+import { useMutation } from "@tanstack/react-query";
+import { BACKEND_URL } from "../const";
+
+interface SubmitCancellationFeedbackParams {
+ organizationId: string;
+ reason: string;
+ reasonDetails?: string;
+ retentionOfferShown?: string;
+ retentionOfferAccepted?: boolean;
+ outcome: string;
+ planNameAtCancellation?: string;
+ monthlyEventCountAtCancellation?: number;
+}
+
+export function useSubmitCancellationFeedback() {
+ return useMutation<{ success: boolean }, Error, SubmitCancellationFeedbackParams>({
+ mutationFn: async (params) => {
+ const response = await fetch(`${BACKEND_URL}/stripe/cancellation-feedback`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify(params),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to submit cancellation feedback");
+ }
+
+ return data;
+ },
+ });
+}
diff --git a/server/src/api/stripe/index.ts b/server/src/api/stripe/index.ts
index 0c48597d1..ae73c5f30 100644
--- a/server/src/api/stripe/index.ts
+++ b/server/src/api/stripe/index.ts
@@ -4,5 +4,6 @@ export { createPortalSession } from "./createPortalSession.js";
export { getInvoices } from "./getInvoices.js";
export { getSubscription } from "./getSubscription.js";
export { previewSubscriptionUpdate } from "./previewSubscriptionUpdate.js";
+export { submitCancellationFeedback } from "./submitCancellationFeedback.js";
export { updateSubscription } from "./updateSubscription.js";
export { handleWebhook } from "./webhook.js";
diff --git a/server/src/api/stripe/submitCancellationFeedback.ts b/server/src/api/stripe/submitCancellationFeedback.ts
new file mode 100644
index 000000000..23d9115ff
--- /dev/null
+++ b/server/src/api/stripe/submitCancellationFeedback.ts
@@ -0,0 +1,77 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { cancellationFeedback, member } from "../../db/postgres/schema.js";
+import { eq, and } from "drizzle-orm";
+
+interface CancellationFeedbackBody {
+ organizationId: string;
+ reason: string;
+ reasonDetails?: string;
+ retentionOfferShown?: string;
+ retentionOfferAccepted?: boolean;
+ outcome: string;
+ planNameAtCancellation?: string;
+ monthlyEventCountAtCancellation?: number;
+}
+
+export async function submitCancellationFeedback(
+ request: FastifyRequest<{ Body: CancellationFeedbackBody }>,
+ reply: FastifyReply
+) {
+ const userId = request.user?.id;
+
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const {
+ organizationId,
+ reason,
+ reasonDetails,
+ retentionOfferShown,
+ retentionOfferAccepted,
+ outcome,
+ planNameAtCancellation,
+ monthlyEventCountAtCancellation,
+ } = request.body;
+
+ if (!organizationId || !reason || !outcome) {
+ return reply.status(400).send({
+ error: "Missing required parameters: organizationId, reason, outcome",
+ });
+ }
+
+ try {
+ // Verify user has permission (owner only)
+ const memberResult = await db
+ .select({ role: member.role })
+ .from(member)
+ .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))
+ .limit(1);
+
+ if (!memberResult.length || memberResult[0].role !== "owner") {
+ return reply.status(403).send({
+ error: "Only organization owners can submit cancellation feedback",
+ });
+ }
+
+ await db.insert(cancellationFeedback).values({
+ organizationId,
+ userId,
+ reason,
+ reasonDetails: reasonDetails ?? null,
+ retentionOfferShown: retentionOfferShown ?? null,
+ retentionOfferAccepted: retentionOfferAccepted ?? false,
+ outcome,
+ planNameAtCancellation: planNameAtCancellation ?? null,
+ monthlyEventCountAtCancellation: monthlyEventCountAtCancellation ?? null,
+ });
+
+ return reply.send({ success: true });
+ } catch (error: any) {
+ console.error("Cancellation Feedback Error:", error);
+ return reply.status(500).send({
+ error: "Failed to submit cancellation feedback",
+ });
+ }
+}
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 1fe092648..671fd5c94 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -607,6 +607,21 @@ export const userAliases = pgTable(
]
);
+// Cancellation feedback for churn reduction
+export const cancellationFeedback = pgTable("cancellation_feedback", {
+ id: serial("id").primaryKey().notNull(),
+ organizationId: text("organization_id").notNull(),
+ userId: text("user_id").notNull(),
+ reason: text("reason").notNull(),
+ reasonDetails: text("reason_details"),
+ retentionOfferShown: text("retention_offer_shown"),
+ retentionOfferAccepted: boolean("retention_offer_accepted").default(false),
+ outcome: text("outcome").notNull(),
+ planNameAtCancellation: text("plan_name_at_cancellation"),
+ monthlyEventCountAtCancellation: integer("monthly_event_count_at_cancellation"),
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),
+});
+
export const importPlatforms = ["umami", "simple_analytics"] as const;
export const importPlatformEnum = pgEnum("import_platform_enum", importPlatforms);
diff --git a/server/src/index.ts b/server/src/index.ts
index b1cdb5541..cf57e68ef 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -95,6 +95,7 @@ import {
getSubscription,
handleWebhook,
previewSubscriptionUpdate,
+ submitCancellationFeedback,
updateSubscription,
} from "./api/stripe/index.js";
import {
@@ -356,6 +357,7 @@ async function stripeAdminRoutes(fastify: FastifyInstance) {
fastify.post("/stripe/update-subscription", authOnly, updateSubscription);
fastify.get("/stripe/subscription", authOnly, getSubscription);
fastify.get("/stripe/invoices", authOnly, getInvoices);
+ fastify.post("/stripe/cancellation-feedback", authOnly, submitCancellationFeedback);
fastify.post("/stripe/webhook", { config: { rawBody: true } }, handleWebhook); // Public - Stripe webhook
// Admin Routes