Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Ask the cancellation reason in app instead of the Stripe portal (#3477)

Luke Vella3831e980bca4
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index fe0045dcf..eefaaed61 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -139,6 +139,15 @@
"cancelInvite": "Cancel invite",
"cancelInviteConfirmation": "Are you sure you want to cancel the invite for {email}?",
"cancelPlan": "Cancel plan",
+ "cancelPlanCommentLabel": "Anything else we should know? (optional)",
+ "cancelPlanDialogDescription": "Your plan stays active until {date}. Before you go, what's the main reason you're cancelling?",
+ "cancelPlanReasonLabel": "Reason for cancelling",
+ "cancelReasonMissingFeatures": "It's missing something I need",
+ "cancelReasonNotUsing": "I'm not using it enough",
+ "cancelReasonOneOffEvent": "I only needed it for one event",
+ "cancelReasonOther": "Something else",
+ "cancelReasonSwitchedService": "I'm switching to another tool",
+ "cancelReasonTooExpensive": "It's too expensive",
"captchaFailed": "Verification failed. Please try again.",
"changeEmail": "Change email",
"changeEmailDescription": "We'll send a verification code to your new email address",
@@ -501,6 +510,7 @@
"jobTitleTeacherOrLecturer": "Teacher or lecturer",
"joinMeeting": "Join",
"joinSpace": "Join {spaceName}",
+ "keepPlan": "Keep plan",
"keyBenefits": "Key benefits",
"language": "Language",
"languageAndRegion": "Language & region",
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/cancel-plan-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/cancel-plan-dialog.tsx
new file mode 100644
index 000000000..18991fabd
--- /dev/null
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/cancel-plan-dialog.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
+import { Button } from "@rallly/ui/button";
+import type { DialogProps } from "@rallly/ui/dialog";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@rallly/ui/dialog";
+import { Field, FieldLabel } from "@rallly/ui/field";
+import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
+import { toast } from "@rallly/ui/sonner";
+import { Textarea } from "@rallly/ui/textarea";
+import { useMutation } from "@tanstack/react-query";
+import React from "react";
+import { cancelPlanAction } from "@/features/billing/actions";
+import { CANCELLATION_COMMENT_MAX_LENGTH } from "@/features/billing/constants";
+import type { CancellationReason } from "@/features/billing/schema";
+import { cancellationReasonSchema } from "@/features/billing/schema";
+import { Trans, useTranslation } from "@/i18n/client";
+
+function ReasonOption({
+ value,
+ children,
+}: {
+ value: CancellationReason;
+ children: React.ReactNode;
+}) {
+ const id = `cancel-plan-reason-${value}`;
+ return (
+ <Field orientation="horizontal">
+ <RadioGroupItem value={value} id={id} />
+ <FieldLabel htmlFor={id} className="font-normal">
+ {children}
+ </FieldLabel>
+ </Field>
+ );
+}
+
+export function CancelPlanDialog({
+ children,
+ periodEnd,
+ ...dialogProps
+}: DialogProps & {
+ /** Formatted date the plan stays active until. */
+ periodEnd: string;
+}) {
+ const { t } = useTranslation();
+ const [reason, setReason] = React.useState<CancellationReason | null>(null);
+ const [comment, setComment] = React.useState("");
+ const cancelPlan = useMutation(
+ mutationOptions(cancelPlanAction, {
+ onSuccess: () => {
+ dialogProps.onOpenChange?.(false);
+ toast.success(
+ t("planCancelScheduledAlertTitle", {
+ defaultValue: "Cancellation scheduled",
+ }),
+ {
+ description: t("planCancelScheduledAlertDescription", {
+ defaultValue:
+ "Your plan stays active until the end of the current billing period. You can resume it any time before then.",
+ }),
+ },
+ );
+ },
+ }),
+ );
+
+ return (
+ <Dialog {...dialogProps}>
+ {children}
+ <DialogContent size="md">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="cancelPlan" defaults="Cancel plan" />
+ </DialogTitle>
+ <DialogDescription>
+ <Trans
+ i18nKey="cancelPlanDialogDescription"
+ defaults="Your plan stays active until {date}. Before you go, what's the main reason you're cancelling?"
+ values={{ date: periodEnd }}
+ />
+ </DialogDescription>
+ </DialogHeader>
+ <RadioGroup
+ aria-label={t("cancelPlanReasonLabel", {
+ defaultValue: "Reason for cancelling",
+ })}
+ value={reason}
+ onValueChange={(value) => {
+ const parsed = cancellationReasonSchema.safeParse(value);
+ if (parsed.success) {
+ setReason(parsed.data);
+ }
+ }}
+ >
+ <ReasonOption value="one_off_event">
+ <Trans
+ i18nKey="cancelReasonOneOffEvent"
+ defaults="I only needed it for one event"
+ />
+ </ReasonOption>
+ <ReasonOption value="not_using">
+ <Trans
+ i18nKey="cancelReasonNotUsing"
+ defaults="I'm not using it enough"
+ />
+ </ReasonOption>
+ <ReasonOption value="too_expensive">
+ <Trans
+ i18nKey="cancelReasonTooExpensive"
+ defaults="It's too expensive"
+ />
+ </ReasonOption>
+ <ReasonOption value="missing_features">
+ <Trans
+ i18nKey="cancelReasonMissingFeatures"
+ defaults="It's missing something I need"
+ />
+ </ReasonOption>
+ <ReasonOption value="switched_service">
+ <Trans
+ i18nKey="cancelReasonSwitchedService"
+ defaults="I'm switching to another tool"
+ />
+ </ReasonOption>
+ <ReasonOption value="other">
+ <Trans i18nKey="cancelReasonOther" defaults="Something else" />
+ </ReasonOption>
+ </RadioGroup>
+ <Field>
+ <FieldLabel htmlFor="cancel-plan-comment">
+ <Trans
+ i18nKey="cancelPlanCommentLabel"
+ defaults="Anything else we should know? (optional)"
+ />
+ </FieldLabel>
+ <Textarea
+ id="cancel-plan-comment"
+ className="min-h-16"
+ maxLength={CANCELLATION_COMMENT_MAX_LENGTH}
+ value={comment}
+ onChange={(e) => setComment(e.target.value)}
+ />
+ </Field>
+ <DialogFooter>
+ <Button
+ variant="destructive"
+ disabled={!reason}
+ loading={cancelPlan.isPending}
+ onClick={() => {
+ if (reason) {
+ cancelPlan.mutate({ reason, comment });
+ }
+ }}
+ >
+ <Trans i18nKey="cancelPlan" defaults="Cancel plan" />
+ </Button>
+ <DialogClose render={<Button />}>
+ <Trans i18nKey="keepPlan" defaults="Keep plan" />
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx
index 9abe6bc19..adca3833e 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.test.tsx
@@ -13,7 +13,7 @@ vi.mock("@rallly/posthog/client", () => ({
vi.mock("@/features/billing/actions", () => ({
switchToYearlyAction: vi.fn(),
openBillingDetailsAction: vi.fn(),
- openCancelPlanAction: vi.fn(),
+ cancelPlanAction: vi.fn(),
openPaymentMethodUpdateAction: vi.fn(),
resumePlanAction: vi.fn(),
}));
@@ -36,6 +36,12 @@ vi.mock("./manage-seats-dialog", () => ({
),
}));
+vi.mock("./cancel-plan-dialog", () => ({
+ CancelPlanDialog: ({ children }: { children: React.ReactNode }) => (
+ <Dialog>{children}</Dialog>
+ ),
+}));
+
vi.mock("./switch-to-yearly-dialog", () => ({
SwitchToYearlyDialog: ({ children }: { children: React.ReactNode }) => (
<Dialog>{children}</Dialog>
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx
index 8c4c4082a..8fb0d8291 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/pro-plan-card.tsx
@@ -8,7 +8,6 @@ import { toast } from "@rallly/ui/sonner";
import { useMutation } from "@tanstack/react-query";
import { TriangleAlertIcon } from "lucide-react";
import {
- openCancelPlanAction,
openPaymentMethodUpdateAction,
resumePlanAction,
} from "@/features/billing/actions";
@@ -22,6 +21,7 @@ import { formatMinorUnitAmount } from "@/features/billing/utils";
import { SpaceTierLabel } from "@/features/space/components/space-tier";
import { Trans, useTranslation } from "@/i18n/client";
import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";
+import { CancelPlanDialog } from "./cancel-plan-dialog";
import { ManageSeatsDialog } from "./manage-seats-dialog";
import {
PlanCard,
@@ -74,7 +74,7 @@ export function ProPlanCard({
const { locale } = useDateTimeConfig();
const { formatDateTime } = useDateTime();
const switchToYearlyDialog = useDialog();
- const openCancelPlan = useMutation(mutationOptions(openCancelPlanAction));
+ const cancelPlanDialog = useDialog();
const openPaymentMethodUpdate = useMutation(
mutationOptions(openPaymentMethodUpdateAction),
);
@@ -267,14 +267,23 @@ export function ProPlanCard({
/>
</span>
{endsAtPeriodEnd ? null : (
- <Button
- variant="ghost"
- className="text-muted-foreground"
- loading={openCancelPlan.isPending}
- onClick={() => openCancelPlan.mutate()}
- >
- <Trans i18nKey="cancelPlan" defaults="Cancel plan" />
- </Button>
+ <CancelPlanDialog {...cancelPlanDialog.dialogProps} periodEnd={date}>
+ <DialogTrigger
+ render={
+ <Button
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={() => {
+ posthog?.capture("space_billing:cancel_plan_click", {
+ interval,
+ });
+ }}
+ />
+ }
+ >
+ <Trans i18nKey="cancelPlan" defaults="Cancel plan" />
+ </DialogTrigger>
+ </CancelPlanDialog>
)}
</PlanCardFooter>
</PlanCard>
diff --git a/apps/web/src/app/api/stripe/portal/route.ts b/apps/web/src/app/api/stripe/portal/route.ts
deleted file mode 100644
index 0475c257f..000000000
--- a/apps/web/src/app/api/stripe/portal/route.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import * as Sentry from "@sentry/nextjs";
-import type { NextRequest } from "next/server";
-import { NextResponse } from "next/server";
-
-import { createStripePortalSession } from "@/features/billing/mutations";
-import { subscriptionCheckoutMetadataSchema } from "@/features/billing/schema";
-import { getStripe } from "@/features/billing/service";
-import { getSession } from "@/lib/auth";
-
-/**
- * Checkout return endpoint. Stripe redirects the browser here after payment
- * (success_url) with a session_id, which lets us resolve the customer before
- * the webhook has written customerId to the user. UI-initiated portal opens
- * go through openCustomerPortalAction instead.
- */
-export async function GET(request: NextRequest) {
- const sessionId = request.nextUrl.searchParams.get("session_id");
-
- if (!sessionId) {
- return NextResponse.json({ error: "Missing session_id" }, { status: 400 });
- }
-
- const userSession = await getSession();
-
- if (!userSession?.user || userSession.user.isGuest) {
- return NextResponse.redirect(
- new URL("/login", request.nextUrl.origin).toString(),
- );
- }
-
- let customerId: string;
-
- try {
- const session = await getStripe().checkout.sessions.retrieve(sessionId);
-
- const metadata = subscriptionCheckoutMetadataSchema.safeParse(
- session.metadata,
- );
-
- if (!metadata.success || metadata.data.userId !== userSession.user.id) {
- return NextResponse.json({ error: "Not found" }, { status: 404 });
- }
-
- if (typeof session.customer !== "string") {
- Sentry.captureException(new Error("Invalid customer ID in session"));
- return NextResponse.json(
- { error: "Invalid customer ID in session" },
- { status: 400 },
- );
- }
- customerId = session.customer;
- } catch (error) {
- Sentry.captureException(error);
- return NextResponse.json(
- { error: "Failed to retrieve session" },
- { status: 500 },
- );
- }
-
- try {
- return NextResponse.redirect(
- await createStripePortalSession({ customerId }),
- );
- } catch (error) {
- Sentry.captureException(error);
- return NextResponse.json(
- { error: "Failed to create portal session" },
- { status: 500 },
- );
- }
-}
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.ts
index 0a4b94b9a..8aecbcf61 100644
--- a/apps/web/src/features/billing/actions.ts
+++ b/apps/web/src/features/billing/actions.ts
@@ -5,13 +5,14 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";
import { refresh } from "next/cache";
import { redirect } from "next/navigation";
import * as z from "zod";
+import { CANCELLATION_COMMENT_MAX_LENGTH } from "@/features/billing/constants";
import { getProPrices, getSpaceSubscription } from "@/features/billing/data";
import {
createAccountPortalSession,
createPaymentMethodUpdateSession,
- createStripeCancelSession,
createStripeSubscriptionUpdateConfirmation,
resumeSubscriptionRenewal,
+ scheduleSubscriptionCancellation,
} from "@/features/billing/mutations";
import { getNonprofitDiscountGrantedAt } from "@/features/billing/nonprofit/data";
import { ensureNonprofitCoupon } from "@/features/billing/nonprofit/mutations";
@@ -21,6 +22,7 @@ import type {
SubscriptionCheckoutMetadata,
SubscriptionMetadata,
} from "@/features/billing/schema";
+import { cancellationReasonSchema } from "@/features/billing/schema";
import { getStripe } from "@/features/billing/service";
import {
canChangeBillingInterval,
@@ -114,10 +116,8 @@ export const upgradeToProAction = authActionClient
);
const checkoutSession = await stripe.checkout.sessions.create({
- success_url: absoluteUrl(
- returnPath ?? "/api/stripe/portal?session_id={CHECKOUT_SESSION_ID}",
- ),
- cancel_url: absoluteUrl(returnPath),
+ success_url: absoluteUrl(returnPath ?? "/settings/billing"),
+ cancel_url: absoluteUrl(returnPath ?? "/settings/billing"),
customer: customerId,
customer_update: {
name: "auto",
@@ -281,24 +281,38 @@ export const switchToYearlyAction = authActionClient
);
});
-export const openCancelPlanAction = authActionClient
- .metadata({ actionName: "open_cancel_plan" })
- .action(async ({ ctx }) => {
- const { space, subscription, customerId } =
- await requireManagedSubscription(ctx.user);
+export const cancelPlanAction = authActionClient
+ .metadata({ actionName: "cancel_plan" })
+ .inputSchema(
+ z.object({
+ reason: cancellationReasonSchema,
+ comment: z
+ .string()
+ .trim()
+ .max(CANCELLATION_COMMENT_MAX_LENGTH)
+ .optional(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const { space, subscription } = await requireManagedSubscription(ctx.user);
+
+ await scheduleSubscriptionCancellation({
+ subscriptionId: subscription.id,
+ reason: parsedInput.reason,
+ comment: parsedInput.comment || undefined,
+ });
track(ctx.user, {
- event: "space_billing:cancel_plan_click",
- properties: { interval: subscription.interval },
+ event: "space_billing:cancel_plan_submit",
+ properties: {
+ interval: subscription.interval,
+ reason: parsedInput.reason,
+ has_comment: Boolean(parsedInput.comment),
+ },
groups: { space: space.id },
});
- redirect(
- await createStripeCancelSession({
- customerId,
- subscriptionId: subscription.id,
- }),
- );
+ refresh();
});
export const resumePlanAction = authActionClient
diff --git a/apps/web/src/features/billing/components/billing-flash-alert.tsx b/apps/web/src/features/billing/components/billing-flash-alert.tsx
index 6c9f17d03..b45b066eb 100644
--- a/apps/web/src/features/billing/components/billing-flash-alert.tsx
+++ b/apps/web/src/features/billing/components/billing-flash-alert.tsx
@@ -25,21 +25,6 @@ export function BillingFlashAlert() {
<AlertTitle>
<Trans i18nKey="planChangedAlertTitle" defaults="Plan changed" />
</AlertTitle>
- ) : flow.data === "cancel" ? (
- <>
- <AlertTitle>
- <Trans
- i18nKey="planCancelScheduledAlertTitle"
- defaults="Cancellation scheduled"
- />
- </AlertTitle>
- <AlertDescription>
- <Trans
- i18nKey="planCancelScheduledAlertDescription"
- defaults="Your plan stays active until the end of the current billing period. You can resume it any time before then."
- />
- </AlertDescription>
- </>
) : (
<>
<AlertTitle>
diff --git a/apps/web/src/features/billing/constants.ts b/apps/web/src/features/billing/constants.ts
index 0ba430800..62db82d58 100644
--- a/apps/web/src/features/billing/constants.ts
+++ b/apps/web/src/features/billing/constants.ts
@@ -9,3 +9,5 @@ export { PLAN_NAMES } from "@rallly/billing/pricing";
// Flash set by /api/stripe/return after a portal flow; value is the flow name.
export const BILLING_FLASH_KEY = "billing";
+
+export const CANCELLATION_COMMENT_MAX_LENGTH = 500;
diff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.ts
index cff027941..153796307 100644
--- a/apps/web/src/features/billing/mutations.ts
+++ b/apps/web/src/features/billing/mutations.ts
@@ -1,5 +1,6 @@
import "server-only";
+import type { Stripe } from "@rallly/billing";
import {
ACCOUNT_PORTAL_CONFIG_VERSION,
PORTAL_CONFIG_PURPOSE,
@@ -8,24 +9,13 @@ import {
import { prisma } from "@rallly/database";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import { isBillingEnabled } from "@/features/billing/constants";
-import type { BillingReturnFlow } from "@/features/billing/schema";
+import type {
+ BillingReturnFlow,
+ CancellationReason,
+} from "@/features/billing/schema";
import { getStripe } from "@/features/billing/service";
import { isStripeResourceMissingError } from "@/features/billing/utils";
-export async function createStripePortalSession({
- customerId,
- returnPath = "/settings/billing",
-}: {
- customerId: string;
- returnPath?: string;
-}) {
- const portalSession = await getStripe().billingPortal.sessions.create({
- customer: customerId,
- return_url: absoluteUrl(returnPath),
- });
- return portalSession.url;
-}
-
async function findConfigurationByMetadata(
match: Record<string, string>,
): Promise<string | undefined> {
@@ -233,31 +223,43 @@ export async function createStripeSubscriptionUpdateConfirmation({
return portalSession.url;
}
-/**
- * Stripe's cancellation screen (reasons, period end confirmation) as a deep
- * link. Uses the account's default portal configuration, the one that has
- * cancellation enabled; the code defined configurations disable it.
- */
-export async function createStripeCancelSession({
- customerId,
+const cancellationFeedback = {
+ one_off_event: "unused",
+ not_using: "unused",
+ too_expensive: "too_expensive",
+ missing_features: "missing_features",
+ switched_service: "switched_service",
+ other: "other",
+} satisfies Record<
+ CancellationReason,
+ Stripe.SubscriptionUpdateParams.CancellationDetails.Feedback
+>;
+
+// The reason goes to Stripe's feedback so ChartMogul keeps reporting it; the
+// finer reason rides in metadata, which Stripe's fixed list cannot carry.
+// Stripe is the source of truth; the row is written too so the page shows
+// "Ends" as soon as the action returns.
+export async function scheduleSubscriptionCancellation({
subscriptionId,
+ reason,
+ comment,
}: {
- customerId: string;
subscriptionId: string;
+ reason: CancellationReason;
+ comment?: string;
}) {
- const session = await getStripe().billingPortal.sessions.create({
- customer: customerId,
- return_url: absoluteUrl("/settings/billing"),
- flow_data: {
- type: "subscription_cancel",
- subscription_cancel: { subscription: subscriptionId },
- after_completion: {
- type: "redirect",
- redirect: { return_url: billingReturnUrl("cancel") },
- },
+ await getStripe().subscriptions.update(subscriptionId, {
+ cancel_at_period_end: true,
+ cancellation_details: {
+ feedback: cancellationFeedback[reason],
+ comment: comment ?? "",
},
+ metadata: { cancelReason: reason },
+ });
+ await prisma.subscription.update({
+ where: { id: subscriptionId },
+ data: { cancelAtPeriodEnd: true },
});
- return session.url;
}
/**
@@ -308,6 +310,8 @@ export async function resumeSubscriptionRenewal({
}) {
await getStripe().subscriptions.update(subscriptionId, {
cancel_at_period_end: false,
+ cancellation_details: { feedback: "", comment: "" },
+ metadata: { cancelReason: "" },
});
await prisma.subscription.update({
where: { id: subscriptionId },
diff --git a/apps/web/src/features/billing/schema.ts b/apps/web/src/features/billing/schema.ts
index 767a30ed2..5bdb8d6cb 100644
--- a/apps/web/src/features/billing/schema.ts
+++ b/apps/web/src/features/billing/schema.ts
@@ -40,10 +40,21 @@ export const billingReturnFlowSchema = z.enum([
"seats",
"interval",
"payment_method",
- "cancel",
]);
export type BillingReturnFlow = z.infer<typeof billingReturnFlowSchema>;
+// Finer than Stripe's fixed feedback list: Stripe has one "unused" bucket for
+// both a finished one-off event and a subscriber who never got value.
+export const cancellationReasonSchema = z.enum([
+ "one_off_event",
+ "not_using",
+ "too_expensive",
+ "missing_features",
+ "switched_service",
+ "other",
+]);
+export type CancellationReason = z.infer<typeof cancellationReasonSchema>;
+
// Stripe's `card` object as stored on PaymentMethod.data. Parsed rather than
// cast: the row is written from whatever Stripe sent at the time.
export const paymentMethodCardSchema = z.object({
diff --git a/apps/web/src/features/billing/webhook/mutations.ts b/apps/web/src/features/billing/webhook/mutations.ts
index cf7266def..da5494d5d 100644
--- a/apps/web/src/features/billing/webhook/mutations.ts
+++ b/apps/web/src/features/billing/webhook/mutations.ts
@@ -10,6 +10,7 @@ import { after } from "next/server";
import { getInstanceBranding } from "@/emails/branding";
import { env } from "@/env";
import {
+ cancellationReasonSchema,
customerMetadataSchema,
subscriptionMetadataSchema,
} from "@/features/billing/schema";
@@ -354,7 +355,7 @@ async function onCustomerSubscriptionCreated(event: Stripe.Event) {
async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
const stripe = getStripe();
- const subscription = await stripe.subscriptions.retrieve(
+ const subscription = await getExpandedSubscription(
(event.data.object as Stripe.Subscription).id,
);
@@ -406,10 +407,39 @@ async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
},
});
+ // Analytics only: malformed price data must not make Stripe retry an event
+ // whose cleanup has already run.
+ let details: {
+ interval: string | null;
+ amount: number | null;
+ currency: string | null;
+ };
+ try {
+ details = getSubscriptionDetails(subscription);
+ } catch {
+ details = { interval: null, amount: null, currency: null };
+ }
+ const cancelReason = cancellationReasonSchema.safeParse(
+ subscription.metadata.cancelReason,
+ );
+ const endedAt = subscription.ended_at ?? event.created;
+
posthog()?.capture({
distinctId: userId,
event: "subscription_cancel",
properties: {
+ // null when cancelled outside the app: dunning, the account deletion
+ // reaper, or the Stripe dashboard.
+ reason: cancelReason.success ? cancelReason.data : null,
+ comment: subscription.cancellation_details?.comment ?? null,
+ stripe_feedback: subscription.cancellation_details?.feedback ?? null,
+ // cancellation_requested, payment_failed or payment_disputed
+ stripe_reason: subscription.cancellation_details?.reason ?? null,
+ tenure_days: Math.floor((endedAt - subscription.start_date) / 86400),
+ interval: details.interval,
+ amount: details.amount,
+ currency: details.currency,
+ seats: subscription.items.data[0]?.quantity ?? null,
$set: {
tier,
},
diff --git a/apps/web/tests/stripe-portal-auth.spec.ts b/apps/web/tests/stripe-portal-auth.spec.ts
deleted file mode 100644
index c5d8bb6fb..000000000
--- a/apps/web/tests/stripe-portal-auth.spec.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { expect, test } from "@playwright/test";
-
-test("the checkout return endpoint rejects an anonymous caller", async ({
- request,
-}) => {
- const res = await request.get(
- "/api/stripe/portal?session_id=cs_test_someone_elses_session",
- { maxRedirects: 0 },
- );
-
- expect(res.status()).toBe(307);
- expect(res.headers().location).toContain("/login");
- expect(res.headers().location).not.toContain("stripe.com");
-});
-
-test("the checkout return endpoint still requires a session id", async ({
- request,
-}) => {
- const res = await request.get("/api/stripe/portal", { maxRedirects: 0 });
- expect(res.status()).toBe(400);
-});