Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Rebuild the billing plan card with named actions instead of the Stripe portal homepage (#3315)
Luke Vella35ef347c7aec
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex b95ab02bd..724f66215 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -94,8 +94,9 @@"basicPollsDescription": "Create simple scheduling polls","billing": "Billing","billingDescription": "Manage your billing information and subscription.",- "billingIntervalUpdatedAlertDescription": "Your subscription now renews once a year.",- "billingIntervalUpdatedAlertTitle": "Switched to yearly billing",+ "billingDetails": "Billing details",+ "billingDetailsDescription": "The name, address and tax ID on your invoices.",+ "billingDetailsHint": "Stored with Stripe and applied to future invoices.","billingPlanTitle": "Plan","billingSettings": "Billing settings","billingSettingsDescription": "View and manage your space's subscription and billing information.",@@ -124,6 +125,7 @@"cancelEventConfirmDescription": "Are you sure you want to cancel this event?","cancelInvite": "Cancel invite","cancelInviteConfirmation": "Are you sure you want to cancel the invite for {email}?",+ "cancelPlan": "Cancel plan","captchaFailed": "Verification failed. Please try again.","changeEmail": "Change email","changeEmailDescription": "We'll send a verification code to your new email address",@@ -282,6 +284,7 @@"earlySupporterRateEndsNoPrice": "Your early supporter rate ends with your subscription.","earlySupporterRateKept": "You keep this rate for as long as your subscription stays active.","edit": "Edit",+ "editBillingDetails": "Edit billing details","editDetails": "Edit details","editDetailsDescription": "Change the details of your event.","editEventTypeTitle": "Edit event type",@@ -432,6 +435,7 @@"inviteStatusSending": "Sending","inviteStatusSent": "Sent","inviteUpdated": "Invitation updated with new role",+ "invoices": "Invoices","jobTitle": "Your role","jobTitleAdministratorOrCoordinator": "Administrator or coordinator","jobTitleConsultantOrFreelancer": "Consultant or freelancer",@@ -506,9 +510,9 @@"makeAdmin": "Make admin","makeMember": "Make member","manage": "Manage",+ "managePaymentMethods": "Manage payment methods","manageSeats": "Manage seats","manageSeatsDescription": "Adjust the number of seats for your space.",- "manageSubscription": "Manage subscription","maxAttendees": "Max attendees","maxAttendeesInvalid": "Must be a positive integer","member": "Member",@@ -671,6 +675,11 @@"pastDueAlertTitle": "Payment failed","pastEventsEmptyStateDescription": "Past events will show up here.","pastEventsEmptyStateTitle": "No past events",+ "paymentMethodExpires": "Expires {month}/{year}",+ "paymentMethodNone": "No saved payment method.",+ "paymentMethodOthers": "{count, plural, one {# other saved} other {# others saved}}",+ "paymentMethods": "Payment method",+ "paymentMethodsDescription": "The card your subscription is charged to.","paymentMethodUpdatedAlertDescription": "Future invoices will be charged to your new payment method.","paymentMethodUpdatedAlertTitle": "Payment method updated","pending": "Pending",@@ -679,9 +688,17 @@"pendingInvitesAlertDescription": "{count, plural, one {There is # pending invite} other {There are # pending invites}}","perSeatMonth": "/seat/mo","perSeatMonthBilledYearly": "/seat/mo, billed yearly",+ "planCancelScheduledAlertDescription": "Your plan stays active until the end of the current billing period. You can resume it any time before then.",+ "planCancelScheduledAlertTitle": "Cancellation scheduled",+ "planChangedAlertTitle": "Plan changed",+ "planEndsOn": "Ends on {date}","planFree": "Free","planHobbyDescription": "For casual users",+ "planPriceBilledMonthly": "per month · billed monthly",+ "planPriceBilledYearly": "per month · billed yearly","planProDescription": "For professionals and power users",+ "planRenewsOn": "Renews on {date}",+ "planResumedToast": "Your plan will renew","pollAutoClosedBadge": "Automatically closed","pollAutoClosedDescription": "This poll was closed automatically because all of its dates have passed. No more responses are being accepted.","pollAutoClosedTooltip": "This poll was closed automatically because all of its dates have passed. You can reopen it at any time.",@@ -758,6 +775,7 @@"response": "Response","responseOptions": "Response options","responses": "Responses",+ "resumePlan": "Resume plan","revoke": "Revoke","revokeConfirmation": "Are you sure you want to revoke {name}? This will immediately disable the key.","revoked": "Revoked",@@ -872,11 +890,7 @@"startOfWeek": "Start of week","startOfWeekSettingDescription": "The day calendars start the week on.","subscriptionCardAmountDiscount": "{amount} discount applied",- "subscriptionCardEndsOn": "Ends {date}","subscriptionCardPercentDiscount": "{percent}% discount applied",- "subscriptionCardPerMonth": "per month",- "subscriptionCardPerYear": "per year",- "subscriptionCardRenewsOn": "Renews {date}","subscriptionStatusActive": "Active","subscriptionStatusCanceled": "Canceled","subscriptionStatusIncomplete": "Incomplete",@@ -887,6 +901,9 @@"subscriptionStatusUnpaid": "Unpaid","support": "Support","supportDescription": "Need help with anything?",+ "switchToYearly": "Switch to yearly",+ "switchToYearlyDescription": "Save {percent}% when you pay yearly.",+ "switchToYearlyTitle": "Switch to yearly billing","syncCalendar": "Sync calendar","syncCalendarError": "There was an issue syncing your calendar","syncCalendarLoading": "Syncing calendar…",@@ -933,6 +950,8 @@"upcomingEventsEmptyStateTitle": "No upcoming events","updateAvailable": "Update available","updateEventTypeError": "Failed to update event type",+ "updatePaymentMethod": "Update payment method",+ "upgrade": "Upgrade","upgradePromptTitle": "Upgrade to Pro","upgradeToPro": "Upgrade to Pro","uploadImage": "Upload",diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/billing-details-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/billing-details-card.tsxnew file mode 100644index 000000000..012547ab5--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/billing-details-card.tsx@@ -0,0 +1,56 @@+"use client";++import { Button } from "@rallly/ui/button";+import { ArrowUpRightIcon } from "lucide-react";+import { openBillingDetailsAction } from "@/features/billing/actions";+import { Trans } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";+import {+ PlanCard,+ PlanCardContent,+ PlanCardDescription,+ PlanCardFooter,+ PlanCardHeader,+ PlanCardHeading,+ PlanCardHeadingDescription,+ PlanCardHeadingTitle,+} from "./plan-card";++export function BillingDetailsCard({ className }: { className?: string }) {+ const openBillingDetails = useSafeAction(openBillingDetailsAction);++ return (+ <PlanCard className={className}>+ <PlanCardHeading>+ <PlanCardHeadingTitle>+ <Trans i18nKey="billingDetails" defaults="Billing details" />+ </PlanCardHeadingTitle>+ <PlanCardHeadingDescription>+ <Trans+ i18nKey="billingDetailsDescription"+ defaults="The name, address and tax ID on your invoices."+ />+ </PlanCardHeadingDescription>+ </PlanCardHeading>+ <PlanCardHeader>+ <PlanCardContent>+ <PlanCardDescription>+ <Trans+ i18nKey="billingDetailsHint"+ defaults="Stored with Stripe and applied to future invoices."+ />+ </PlanCardDescription>+ </PlanCardContent>+ </PlanCardHeader>+ <PlanCardFooter className="flex-row items-center justify-end">+ <Button+ loading={openBillingDetails.isExecuting}+ onClick={() => openBillingDetails.execute()}+ >+ <Trans i18nKey="editBillingDetails" defaults="Edit billing details" />+ <ArrowUpRightIcon className="text-muted-foreground" />+ </Button>+ </PlanCardFooter>+ </PlanCard>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/contact-support-link.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/contact-support-link.tsxdeleted file mode 100644index 177cbb2ff..000000000--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/contact-support-link.tsx+++ /dev/null@@ -1,36 +0,0 @@-"use client";--import { posthog } from "@rallly/posthog/client";-import { buttonVariants } from "@rallly/ui";-import { SendIcon } from "lucide-react";-import { Trans } from "@/i18n/client";--export function ContactSupportLink() {- return (- <div className="flex flex-col items-start gap-3">- <a- href="mailto:[email protected]"- className={buttonVariants()}- onClick={() => {- posthog?.capture("space_billing:support_button_click");- }}- >- <SendIcon className="text-muted-foreground" />- <Trans i18nKey="contactSupport" defaults="Contact support" />- </a>- <p className="text-muted-foreground text-sm">- <Trans- i18nKey="contactSupportEmail"- defaults="Or email us at <0>[email protected]</0>"- components={[- <a- key="email"- href="mailto:[email protected]"- className="select-all font-medium text-foreground"- />,- ]}- />- </p>- </div>- );-}diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/hobby-plan-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/hobby-plan-card.tsxindex fd5a89a27..b8d99dab5 100644--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/hobby-plan-card.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/hobby-plan-card.tsx@@ -2,58 +2,54 @@import { Button } from "@rallly/ui/button";import { showPayWall } from "@/features/billing/client";-import {- SpaceTierIcon,- SpaceTierLabel,-} from "@/features/space/components/space-tier";+import { SpaceTierLabel } from "@/features/space/components/space-tier";import { Trans } from "@/i18n/client";import {PlanCard,+ PlanCardActions,PlanCardContent,PlanCardDescription,- PlanCardFooter,PlanCardHeader,- PlanCardIcon,- PlanCardPrice,- PlanCardPriceValue,+ PlanCardHeading,+ PlanCardHeadingDescription,+ PlanCardHeadingTitle,PlanCardTitle,} from "./plan-card";export function HobbyPlanCard({ className }: { className?: string }) {return (<PlanCard className={className}>+ <PlanCardHeading>+ <PlanCardHeadingTitle>+ <Trans i18nKey="billingPlanTitle" defaults="Plan" />+ </PlanCardHeadingTitle>+ <PlanCardHeadingDescription>+ <Trans+ i18nKey="billingSubscriptionDescription"+ defaults="Manage your current subscription plan."+ />+ </PlanCardHeadingDescription>+ </PlanCardHeading><PlanCardHeader>- <PlanCardIcon>- <SpaceTierIcon tier="hobby" />- </PlanCardIcon><PlanCardContent><PlanCardTitle><SpaceTierLabel tier="hobby" /></PlanCardTitle><PlanCardDescription>- <Trans- i18nKey="seatCount"- defaults="{count, plural, one {# seat} other {# seats}}"- values={{ count: 1 }}- />+ <Trans i18nKey="priceFree" defaults="Free" /></PlanCardDescription></PlanCardContent>- <PlanCardPrice>- <PlanCardPriceValue>- <Trans i18nKey="priceFree" defaults="Free" />- </PlanCardPriceValue>- </PlanCardPrice>+ <PlanCardActions>+ <Button+ variant="primary"+ onClick={() => {+ showPayWall({ from: "billing-settings" });+ }}+ >+ <Trans i18nKey="upgrade" defaults="Upgrade" />+ </Button>+ </PlanCardActions></PlanCardHeader>- <PlanCardFooter>- <Button- variant="primary"- onClick={() => {- showPayWall({ from: "billing-settings" });- }}- >- <Trans i18nKey="upgradeToPro" defaults="Upgrade to Pro" />- </Button>- </PlanCardFooter></PlanCard>);}diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-methods-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-methods-card.tsxnew file mode 100644index 000000000..8b0eb9e91--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/payment-methods-card.tsx@@ -0,0 +1,118 @@+"use client";++import { Button } from "@rallly/ui/button";+import { ArrowUpRightIcon, CreditCardIcon } from "lucide-react";+import { openBillingDetailsAction } from "@/features/billing/actions";+import type { PaymentMethodCard } from "@/features/billing/schema";+import { Trans } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";+import {+ PlanCard,+ PlanCardContent,+ PlanCardDescription,+ PlanCardFooter,+ PlanCardHeader,+ PlanCardHeading,+ PlanCardHeadingDescription,+ PlanCardHeadingTitle,+} from "./plan-card";++// Stripe's brand ids are lowercase and unpunctuated; only the display form+// differs, so a lookup beats trying to prettify them generically.+const brandNames: Record<string, string> = {+ amex: "American Express",+ diners: "Diners Club",+ discover: "Discover",+ eftpos_au: "Eftpos",+ jcb: "JCB",+ mastercard: "Mastercard",+ unionpay: "UnionPay",+ visa: "Visa",+};++export function PaymentMethodsCard({+ paymentMethods,+ className,+}: {+ paymentMethods: {+ id: string;+ type: string;+ card: PaymentMethodCard | null;+ }[];+ className?: string;+}) {+ const openBillingDetails = useSafeAction(openBillingDetailsAction);+ const [primary] = paymentMethods;++ return (+ <PlanCard className={className}>+ <PlanCardHeading>+ <PlanCardHeadingTitle>+ <Trans i18nKey="paymentMethods" defaults="Payment method" />+ </PlanCardHeadingTitle>+ <PlanCardHeadingDescription>+ <Trans+ i18nKey="paymentMethodsDescription"+ defaults="The card your subscription is charged to."+ />+ </PlanCardHeadingDescription>+ </PlanCardHeading>+ <PlanCardHeader>+ <PlanCardContent>+ {primary?.card ? (+ <div className="flex items-center gap-3">+ <span className="flex h-9 w-12 shrink-0 items-center justify-center rounded-md border border-card-border bg-card">+ <CreditCardIcon className="size-4 text-muted-foreground" />+ </span>+ <div className="min-w-0">+ <p className="text-sm">+ {brandNames[primary.card.brand] ?? primary.card.brand} ••••{" "}+ {primary.card.last4}+ </p>+ <PlanCardDescription>+ <Trans+ i18nKey="paymentMethodExpires"+ defaults="Expires {month}/{year}"+ values={{+ month: String(primary.card.exp_month).padStart(2, "0"),+ year: String(primary.card.exp_year),+ }}+ />+ {paymentMethods.length > 1 ? (+ <>+ {" · "}+ <Trans+ i18nKey="paymentMethodOthers"+ defaults="{count, plural, one {# other saved} other {# others saved}}"+ values={{ count: paymentMethods.length - 1 }}+ />+ </>+ ) : null}+ </PlanCardDescription>+ </div>+ </div>+ ) : (+ <PlanCardDescription>+ <Trans+ i18nKey="paymentMethodNone"+ defaults="No saved payment method."+ />+ </PlanCardDescription>+ )}+ </PlanCardContent>+ </PlanCardHeader>+ <PlanCardFooter className="flex-row items-center justify-end">+ <Button+ loading={openBillingDetails.isExecuting}+ onClick={() => openBillingDetails.execute()}+ >+ <Trans+ i18nKey="managePaymentMethods"+ defaults="Manage payment methods"+ />+ <ArrowUpRightIcon className="text-muted-foreground" />+ </Button>+ </PlanCardFooter>+ </PlanCard>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/plan-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/plan-card.tsxindex 8e5db523e..c63bc8681 100644--- a/apps/web/src/app/[locale]/(space)/settings/billing/components/plan-card.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/plan-card.tsx@@ -3,48 +3,54 @@ import { Card } from "@rallly/ui/card";import type * as React from "react";export function PlanCard({ className, ...props }: React.ComponentProps<"div">) {- return <Card className={cn("@container", className)} {...props} />;+ return (+ <Card className={cn("@container flex flex-col", className)} {...props} />+ );}-export function PlanCardHeader({+export function PlanCardHeading({className,...props}: React.ComponentProps<"div">) {+ return <div className={cn("space-y-0.5 px-4 pt-4", className)} {...props} />;+}++export function PlanCardHeadingTitle({+ className,+ ...props+}: React.ComponentProps<"h2">) {+ return <h2 className={cn("font-semibold text-sm", className)} {...props} />;+}++export function PlanCardHeadingDescription({+ className,+ ...props+}: React.ComponentProps<"p">) {return (- <div- className={cn(- "flex @sm:flex-row flex-col items-start gap-3 p-3",- className,- )}- {...props}- />+ <p className={cn("text-muted-foreground text-sm", className)} {...props} />);}-export function PlanCardFooter({+export function PlanCardHeader({className,...props}: React.ComponentProps<"div">) {return (<div- className={cn("border-card-border border-t p-3", className)}+ className={cn(+ "flex @sm:flex-row flex-col @sm:items-center justify-between gap-4 p-4",+ className,+ )}{...props}/>);}-export function PlanCardIcon({- className,- ...props-}: React.ComponentProps<"div">) {- return <div className={cn("shrink-0", className)} {...props} />;-}-export function PlanCardContent({className,...props}: React.ComponentProps<"div">) {- return <div className={cn("min-w-0 flex-1", className)} {...props} />;+ return <div className={cn("min-w-0 space-y-1", className)} {...props} />;}export function PlanCardTitle({@@ -54,7 +60,7 @@ export function PlanCardTitle({return (<divclassName={cn(- "flex items-center gap-x-2 font-semibold text-sm",+ "flex flex-wrap items-center gap-x-2 gap-y-1 font-semibold text-xl",className,)}{...props}@@ -67,42 +73,36 @@ export function PlanCardDescription({...props}: React.ComponentProps<"p">) {return (- <p- className={cn("truncate text-muted-foreground text-sm", className)}- {...props}- />+ <p className={cn("text-muted-foreground text-sm", className)} {...props} />);}-export function PlanCardPrice({+export function PlanCardActions({className,...props}: React.ComponentProps<"div">) {return (<div- className={cn("@sm:mr-2 shrink-0 @sm:text-right", className)}+ className={cn("flex shrink-0 flex-wrap items-center gap-2", className)}{...props}/>);}-export function PlanCardPriceValue({+export function PlanCardFooter({className,...props}: React.ComponentProps<"div">) {return (<div- className={cn("font-semibold text-sm tabular-nums", className)}+ className={cn(+ // Inset rule rather than a full width border, so the footer reads as+ // part of the card rather than a separate band. mt-auto pins it to the+ // bottom when paired cards have unequal content heights.+ "mx-4 mt-auto flex @sm:flex-row flex-col @sm:items-center justify-between gap-2 border-card-border border-t pt-3 pb-4 text-muted-foreground text-sm",+ className,+ )}{...props}/>);}--export function PlanCardPriceDescription({- className,- ...props-}: React.ComponentProps<"p">) {- return (- <p className={cn("text-muted-foreground text-sm", className)} {...props} />- );-}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.tsxindex 72804a7d8..8839853cd 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@@ -1,16 +1,21 @@+import { Dialog } from "@rallly/ui/dialog";import { describe, expect, it, vi } from "vitest";import { render, screen } from "@/test/test-utils";import { ProPlanCard } from "./pro-plan-card";// The card pulls in server actions and client-only hooks that aren't relevant-// to the price rendering under test, so stub them out.+// to the rendering under test, so stub them out.vi.mock("@rallly/posthog/client", () => ({posthog: { capture: vi.fn() },}));vi.mock("@/features/billing/actions", () => ({- openCustomerPortalAction: vi.fn(),+ switchToYearlyAction: vi.fn(),+ openBillingDetailsAction: vi.fn(),+ openCancelPlanAction: vi.fn(),+ openPaymentMethodUpdateAction: vi.fn(),+ resumePlanAction: vi.fn(),}));vi.mock("@/lib/safe-action/client", () => ({@@ -22,80 +27,137 @@ vi.mock("@/lib/datetime/client", () => ({useDateTime: () => ({ formatDateTime: () => "Jan 1, 2026" }),}));+// The dialogs own a Dialog root around their trigger; stand-ins keep the root+// so the real DialogTrigger inside the card still mounts.vi.mock("./manage-seats-dialog", () => ({- ManageSeatsDialog: () => null,+ ManageSeatsDialog: ({ children }: { children: React.ReactNode }) => (+ <Dialog>{children}</Dialog>+ ),+}));++vi.mock("./switch-to-yearly-dialog", () => ({+ SwitchToYearlyDialog: ({ children }: { children: React.ReactNode }) => (+ <Dialog>{children}</Dialog>+ ),}));const baseProps = {- amount: 800,+ amount: 1000,currency: "usd",interval: "month" as const,- seats: 2,+ seats: 1,usedSeats: 1,status: "active" as const,cancelAtPeriodEnd: false,periodEnd: new Date("2026-01-01T00:00:00Z"),earlySupporter: false,listPrice: null,+ switchToYearly: { monthlyAmount: 1000, yearlyAmount: 7200 },+ canResume: false,};+// ICU interpolation isn't wired up in this render harness, so copy with+// placeholders renders its raw template. Assertions target formatted numbers+// rendered outside Trans, button names, and leading words.describe("ProPlanCard", () => {- // Note: ICU interpolation isn't wired up in this render harness, so the- // discount note renders its raw template rather than an interpolated string.- // The price figures come from Intl.NumberFormat, so those are asserted exactly.-- it("shows the full price when there is no discount", () => {+ it("shows the monthly total and the renewing actions", () => {render(<ProPlanCard {...baseProps} />);- // amount (800) * seats (2) / 100 = $16.00, not struck through- const price = screen.getByText("$16.00");- expect(price).toBeInTheDocument();- expect(price).not.toHaveClass("line-through");- expect(screen.queryByText(/discount applied/)).not.toBeInTheDocument();+ expect(screen.getByText("$10")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /switch to yearly/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /manage seats/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /cancel plan/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /invoices/i }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /resume plan/i }),+ ).not.toBeInTheDocument();});- it("applies a percentage discount and shows the original price struck through", () => {- render(<ProPlanCard {...baseProps} discountPercentOff={50} />);-- // Discounted total is shown as the headline price (16.00 - 50% = 8.00)- expect(screen.getByText("$8.00")).toBeInTheDocument();- // Original price is shown struck through- expect(screen.getByText("$16.00")).toHaveClass("line-through");- expect(screen.getByText(/discount applied/)).toBeInTheDocument();- });-- it("applies a fixed-amount discount", () => {- render(<ProPlanCard {...baseProps} discountAmountOff={400} />);+ it("shows the per month equivalent for yearly billing and no plan switch", () => {+ render(+ <ProPlanCard+ {...baseProps}+ interval="year"+ amount={7200}+ switchToYearly={null}+ />,+ );- // 1600 - 400 = 1200 -> $12.00- expect(screen.getByText("$12.00")).toBeInTheDocument();- expect(screen.getByText("$16.00")).toHaveClass("line-through");- expect(screen.getByText(/discount applied/)).toBeInTheDocument();+ expect(screen.getByText("$6")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /switch to yearly/i }),+ ).not.toBeInTheDocument();});- it("labels early supporters and says the rate is kept", () => {- render(<ProPlanCard {...baseProps} earlySupporter listPrice={null} />);+ it("multiplies by seats and applies a percentage discount", () => {+ render(<ProPlanCard {...baseProps} seats={2} discountPercentOff={30} />);- expect(screen.getByText("Early supporter")).toBeInTheDocument();- expect(document.querySelector(".line-through")).toBeNull();+ // 1000 × 2 = 2000, minus 30% = 1400 → $14+ expect(screen.getByText("$14")).toBeInTheDocument();});- it("shows nothing about early supporters on a current price", () => {- render(<ProPlanCard {...baseProps} />);+ it("offers only resume once cancellation is scheduled", () => {+ render(+ <ProPlanCard+ {...baseProps}+ cancelAtPeriodEnd+ canResume+ switchToYearly={null}+ />,+ );- expect(screen.queryByText("Early supporter")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /resume plan/i }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /switch to yearly/i }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /cancel plan/i }),+ ).not.toBeInTheDocument();+ // Invoices stay reachable after cancellation is scheduled.+ expect(+ screen.getByRole("button", { name: /invoices/i }),+ ).toBeInTheDocument();});- it("keeps the badge when cancellation is scheduled", () => {+ it("hides resume while the account is scheduled for deletion", () => {render(<ProPlanCard{...baseProps}- earlySupportercancelAtPeriodEnd- listPrice={{ monthly: 1000, yearly: 8400 }}+ canResume={false}+ switchToYearly={null}/>,);+ expect(+ screen.queryByRole("button", { name: /resume plan/i }),+ ).not.toBeInTheDocument();+ });++ it("asks for a payment method when past due", () => {+ render(<ProPlanCard {...baseProps} status="past_due" />);++ expect(+ screen.getByRole("button", { name: /update payment method/i }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /switch to yearly/i }),+ ).not.toBeInTheDocument();+ });++ it("labels early supporters", () => {+ render(<ProPlanCard {...baseProps} earlySupporter />);+expect(screen.getByText("Early supporter")).toBeInTheDocument();});});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.tsxindex d154f5018..b98a58747 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@@ -2,9 +2,15 @@import { posthog } from "@rallly/posthog/client";import { Button } from "@rallly/ui/button";-import { DialogTrigger } from "@rallly/ui/dialog";-import { ArmchairIcon, CreditCardIcon, DotIcon } from "lucide-react";-import { openCustomerPortalAction } from "@/features/billing/actions";+import { DialogTrigger, useDialog } from "@rallly/ui/dialog";+import { toast } from "@rallly/ui/sonner";+import { ArrowUpRightIcon, TriangleAlertIcon } from "lucide-react";+import {+ openBillingDetailsAction,+ openCancelPlanAction,+ openPaymentMethodUpdateAction,+ resumePlanAction,+} from "@/features/billing/actions";import { EarlySupporterBadge } from "@/features/billing/components/early-supporter-badge";import { SubscriptionStatusBadge } from "@/features/billing/components/subscription-status-badge";import type {@@ -12,26 +18,24 @@ import type {SubscriptionStatus,} from "@/features/billing/schema";import { formatMinorUnitAmount } from "@/features/billing/utils";-import {- SpaceTierIcon,- SpaceTierLabel,-} from "@/features/space/components/space-tier";-import { Trans } from "@/i18n/client";+import { SpaceTierLabel } from "@/features/space/components/space-tier";+import { Trans, useTranslation } from "@/i18n/client";import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";import { useSafeAction } from "@/lib/safe-action/client";import { ManageSeatsDialog } from "./manage-seats-dialog";import {PlanCard,+ PlanCardActions,PlanCardContent,PlanCardDescription,PlanCardFooter,PlanCardHeader,- PlanCardIcon,- PlanCardPrice,- PlanCardPriceDescription,- PlanCardPriceValue,+ PlanCardHeading,+ PlanCardHeadingDescription,+ PlanCardHeadingTitle,PlanCardTitle,} from "./plan-card";+import { SwitchToYearlyDialog } from "./switch-to-yearly-dialog";export function ProPlanCard({amount,@@ -46,8 +50,11 @@ export function ProPlanCard({periodEnd,earlySupporter,listPrice,+ switchToYearly,+ canResume,className,}: {+ /** Per seat unit amount in the currency's minor unit. */amount: number;discountPercentOff?: number | null;discountAmountOff?: number | null;@@ -59,50 +66,67 @@ export function ProPlanCard({cancelAtPeriodEnd: boolean;periodEnd: Date;earlySupporter: boolean;+ /** Current list prices per seat in this currency, for the early supporter copy. */listPrice: { monthly?: number; yearly?: number } | null;+ /** Set for monthly subscribers who can switch to yearly; null otherwise. */+ switchToYearly: { monthlyAmount: number; yearlyAmount: number } | null;+ canResume: boolean;className?: string;}) {+ const { t } = useTranslation();const { locale } = useDateTimeConfig();const { formatDateTime } = useDateTime();- const openCustomerPortal = useSafeAction(openCustomerPortalAction);+ const switchToYearlyDialog = useDialog();+ const openCancelPlan = useSafeAction(openCancelPlanAction);+ const openPaymentMethodUpdate = useSafeAction(openPaymentMethodUpdateAction);+ const openBillingDetails = useSafeAction(openBillingDetailsAction);+ const resumePlan = useSafeAction(resumePlanAction, {+ onSuccess: () => {+ toast.success(+ t("planResumedToast", { defaultValue: "Your plan will renew" }),+ );+ },+ });const formatCurrency = (minorUnitAmount: number) =>formatMinorUnitAmount({ amount: minorUnitAmount, currency, locale });- // amount is the per-seat unit amount in the currency's minor unit. Coupons- // and promotion codes are applied by Stripe at the invoice level, so we apply- // the stored discount here to reflect what the customer is actually charged.+ // Coupons are applied by Stripe at the invoice level, so the stored+ // discount is applied here to show what the customer is actually charged.const subtotal = amount * seats;- let discountedTotal = subtotal;+ let total = subtotal;if (discountPercentOff) {- discountedTotal = Math.round(- discountedTotal * (1 - discountPercentOff / 100),- );+ total = Math.round(total * (1 - discountPercentOff / 100));}if (discountAmountOff) {- discountedTotal = Math.max(0, discountedTotal - discountAmountOff);+ total = Math.max(0, total - discountAmountOff);}- const hasDiscount = discountedTotal !== subtotal;-- const price = formatCurrency(discountedTotal);- const originalPrice = formatCurrency(subtotal);+ const hasDiscount = total !== subtotal;+ const perMonth = interval === "year" ? Math.round(total / 12) : total;const date = formatDateTime(periodEnd, "date");const endsAtPeriodEnd = status === "canceled" || cancelAtPeriodEnd;+ const needsPayment = status === "past_due" || status === "unpaid";const listPriceForInterval =listPrice?.[interval === "month" ? "monthly" : "yearly"];return (<PlanCard className={className}>+ <PlanCardHeading>+ <PlanCardHeadingTitle>+ <Trans i18nKey="billingPlanTitle" defaults="Plan" />+ </PlanCardHeadingTitle>+ <PlanCardHeadingDescription>+ <Trans+ i18nKey="billingSubscriptionDescription"+ defaults="Manage your current subscription plan."+ />+ </PlanCardHeadingDescription>+ </PlanCardHeading><PlanCardHeader>- <PlanCardIcon>- <SpaceTierIcon tier="pro" />- </PlanCardIcon><PlanCardContent>- <div className="flex items-center gap-x-2">- <PlanCardTitle>- <SpaceTierLabel tier="pro" />- </PlanCardTitle>+ <PlanCardTitle>+ <SpaceTierLabel tier="pro" /><SubscriptionStatusBadge status={status} />{earlySupporter ? (<EarlySupporterBadge>@@ -130,93 +154,149 @@ export function ProPlanCard({)}</EarlySupporterBadge>) : null}- </div>- <PlanCardDescription className="flex items-center">- <Trans- i18nKey="seatCount"- defaults="{count, plural, one {# seat} other {# seats}}"- values={{ count: seats }}- />- <DotIcon className="size-4 shrink-0 text-muted-foreground" />- {endsAtPeriodEnd ? (+ </PlanCardTitle>+ <PlanCardDescription>+ <span className="font-medium text-foreground">+ {formatCurrency(perMonth)}+ </span>{" "}+ {interval === "month" ? (<Trans- i18nKey="subscriptionCardEndsOn"- defaults="Ends {date}"- values={{ date }}+ i18nKey="planPriceBilledMonthly"+ defaults="per month · billed monthly"/>) : (<Trans- i18nKey="subscriptionCardRenewsOn"- defaults="Renews {date}"- values={{ date }}+ i18nKey="planPriceBilledYearly"+ defaults="per month · billed yearly"/>)}- </PlanCardDescription>- </PlanCardContent>- <PlanCardPrice>- <PlanCardPriceValue className="flex items-center @sm:justify-end gap-x-1.5">{hasDiscount ? (- <span className="font-normal text-muted-foreground line-through">- {originalPrice}- </span>+ <>+ {" · "}+ {discountPercentOff ? (+ <Trans+ i18nKey="subscriptionCardPercentDiscount"+ defaults="{percent}% discount applied"+ values={{ percent: discountPercentOff }}+ />+ ) : (+ <Trans+ i18nKey="subscriptionCardAmountDiscount"+ defaults="{amount} discount applied"+ values={{ amount: formatCurrency(discountAmountOff ?? 0) }}+ />+ )}+ </>) : null}- <span>{price}</span>- </PlanCardPriceValue>- <PlanCardPriceDescription>- {interval === "month" ? (- <Trans i18nKey="subscriptionCardPerMonth" defaults="per month" />- ) : (- <Trans i18nKey="subscriptionCardPerYear" defaults="per year" />- )}- </PlanCardPriceDescription>- {hasDiscount ? (- <PlanCardPriceDescription className="text-green-600">- {discountPercentOff ? (- <Trans- i18nKey="subscriptionCardPercentDiscount"- defaults="{percent}% discount applied"- values={{ percent: discountPercentOff }}- />- ) : (- <Trans- i18nKey="subscriptionCardAmountDiscount"- defaults="{amount} discount applied"- values={{ amount: formatCurrency(discountAmountOff ?? 0) }}- />- )}- </PlanCardPriceDescription>- ) : null}- </PlanCardPrice>+ </PlanCardDescription>+ </PlanCardContent>+ <PlanCardActions>+ {endsAtPeriodEnd ? (+ canResume ? (+ <Button+ loading={resumePlan.isExecuting}+ onClick={() => resumePlan.execute()}+ >+ <Trans i18nKey="resumePlan" defaults="Resume plan" />+ </Button>+ ) : null+ ) : (+ <>+ {needsPayment ? (+ <Button+ loading={openPaymentMethodUpdate.isExecuting}+ onClick={() => openPaymentMethodUpdate.execute()}+ >+ <TriangleAlertIcon className="text-amber-500" />+ <Trans+ i18nKey="updatePaymentMethod"+ defaults="Update payment method"+ />+ </Button>+ ) : null}+ {switchToYearly && !needsPayment ? (+ <SwitchToYearlyDialog+ {...switchToYearlyDialog.dialogProps}+ monthlyAmount={switchToYearly.monthlyAmount}+ yearlyAmount={switchToYearly.yearlyAmount}+ >+ <DialogTrigger+ render={+ <Button+ onClick={() => {+ posthog?.capture("space_billing:change_plan_click");+ }}+ />+ }+ >+ <Trans+ i18nKey="switchToYearly"+ defaults="Switch to yearly"+ />+ </DialogTrigger>+ </SwitchToYearlyDialog>+ ) : null}+ <ManageSeatsDialog usedSeats={usedSeats} currentSeats={seats}>+ <DialogTrigger+ render={+ <Button+ onClick={() => {+ posthog?.capture(+ "space_billing:manage_seats_button_click",+ );+ }}+ />+ }+ >+ <Trans i18nKey="manageSeats" defaults="Manage seats" />+ </DialogTrigger>+ </ManageSeatsDialog>+ </>+ )}+ </PlanCardActions></PlanCardHeader><PlanCardFooter>- <div className="flex gap-2">- <Button- loading={openCustomerPortal.isExecuting}- onClick={() => {- posthog?.capture("space_billing:billing_portal_button_click");- openCustomerPortal.execute({});- }}- >- <CreditCardIcon className="text-muted-foreground" />+ <span>+ {endsAtPeriodEnd ? (+ <Trans+ i18nKey="planEndsOn"+ defaults="Ends on {date}"+ values={{ date }}+ />+ ) : (<Trans- i18nKey="manageSubscription"- defaults="Manage subscription"+ i18nKey="planRenewsOn"+ defaults="Renews on {date}"+ values={{ date }}/>+ )}+ {" · "}+ <Trans+ i18nKey="seatCount"+ defaults="{count, plural, one {# seat} other {# seats}}"+ values={{ count: seats }}+ />+ </span>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ className="text-muted-foreground"+ loading={openBillingDetails.isExecuting}+ onClick={() => openBillingDetails.execute()}+ >+ <Trans i18nKey="invoices" defaults="Invoices" />+ <ArrowUpRightIcon className="text-muted-foreground" /></Button>- <ManageSeatsDialog usedSeats={usedSeats} currentSeats={seats}>- <DialogTrigger- render={- <Button- onClick={() => {- posthog?.capture("space_billing:manage_seats_button_click");- }}- />- }+ {endsAtPeriodEnd ? null : (+ <Button+ variant="ghost"+ className="text-muted-foreground"+ loading={openCancelPlan.isExecuting}+ onClick={() => openCancelPlan.execute()}>- <ArmchairIcon className="text-muted-foreground" />- <Trans i18nKey="manageSeats" defaults="Manage seats" />- </DialogTrigger>- </ManageSeatsDialog>+ <Trans i18nKey="cancelPlan" defaults="Cancel plan" />+ </Button>+ )}</div></PlanCardFooter></PlanCard>diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/support-card.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/support-card.tsxnew file mode 100644index 000000000..d44069fd1--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/support-card.tsx@@ -0,0 +1,57 @@+"use client";++import { posthog } from "@rallly/posthog/client";+import { buttonVariants } from "@rallly/ui";+import { SendIcon } from "lucide-react";+import { Trans } from "@/i18n/client";+import {+ PlanCard,+ PlanCardDescription,+ PlanCardFooter,+ PlanCardHeading,+ PlanCardHeadingDescription,+ PlanCardHeadingTitle,+} from "./plan-card";++export function SupportCard({ className }: { className?: string }) {+ return (+ <PlanCard className={className}>+ <PlanCardHeading>+ <PlanCardHeadingTitle>+ <Trans i18nKey="support" defaults="Support" />+ </PlanCardHeadingTitle>+ <PlanCardHeadingDescription>+ <Trans+ i18nKey="supportDescription"+ defaults="Need help with anything?"+ />+ </PlanCardHeadingDescription>+ </PlanCardHeading>+ <PlanCardFooter>+ <PlanCardDescription>+ <Trans+ i18nKey="contactSupportEmail"+ defaults="Or email us at <0>[email protected]</0>"+ components={[+ <a+ key="email"+ href="mailto:[email protected]"+ className="select-all font-medium text-foreground"+ />,+ ]}+ />+ </PlanCardDescription>+ <a+ href="mailto:[email protected]"+ className={buttonVariants()}+ onClick={() => {+ posthog?.capture("space_billing:support_button_click");+ }}+ >+ <SendIcon className="text-muted-foreground" />+ <Trans i18nKey="contactSupport" defaults="Contact support" />+ </a>+ </PlanCardFooter>+ </PlanCard>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsxnew file mode 100644index 000000000..a6ef66f8a--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/billing/components/switch-to-yearly-dialog.tsx@@ -0,0 +1,71 @@+"use client";++import { yearlySavingsPercent } from "@rallly/billing";+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 { switchToYearlyAction } from "@/features/billing/actions";+import { Trans } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";++export function SwitchToYearlyDialog({+ children,+ monthlyAmount,+ yearlyAmount,+ ...dialogProps+}: DialogProps & {+ /** Per seat monthly amount in the currency's minor unit. */+ monthlyAmount: number;+ /** Per seat yearly amount in the currency's minor unit. */+ yearlyAmount: number;+}) {+ const switchToYearly = useSafeAction(switchToYearlyAction);++ return (+ <Dialog {...dialogProps}>+ {children}+ <DialogContent size="sm">+ <DialogHeader>+ <DialogTitle>+ <Trans+ i18nKey="switchToYearlyTitle"+ defaults="Switch to yearly billing"+ />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="switchToYearlyDescription"+ defaults="Save {percent}% when you pay yearly."+ values={{+ percent: yearlySavingsPercent({+ monthly: monthlyAmount,+ yearly: yearlyAmount,+ }),+ }}+ />+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button />}>+ <Trans i18nKey="cancel" defaults="Cancel" />+ </DialogClose>+ <Button+ variant="primary"+ loading={switchToYearly.isExecuting}+ onClick={() => switchToYearly.execute()}+ >+ <Trans i18nKey="switchToYearly" defaults="Switch to yearly" />+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/page.tsxindex c089f911c..7e6e73e18 100644--- a/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx@@ -7,15 +7,6 @@ import {EmptyStateIcon,EmptyStateTitle,} from "@/components/empty-state";-import {- PageSection,- PageSectionContent,- PageSectionDescription,- PageSectionDivider,- PageSectionGroup,- PageSectionHeader,- PageSectionTitle,-} from "@/components/page-layout";import {SettingsPage,SettingsPageContent,@@ -24,16 +15,21 @@ import {SettingsPageTitle,} from "@/components/settings-layout";import { BillingFlashAlert } from "@/features/billing/components/billing-flash-alert";-import { loadSubscriptionOverview } from "@/features/billing/loaders";+import {+ loadPaymentMethods,+ loadSubscriptionOverview,+} from "@/features/billing/loaders";import { getActiveSpace, getSeatUsage } from "@/features/space/loaders";import { defineAbilityForMember } from "@/features/space/member/ability";import { requireUser } from "@/features/user/loaders";import { Trans } from "@/i18n/client";import { getTranslation } from "@/i18n/server";import { isFeatureEnabled } from "@/lib/feature-flags/server";-import { ContactSupportLink } from "./components/contact-support-link";+import { BillingDetailsCard } from "./components/billing-details-card";import { HobbyPlanCard } from "./components/hobby-plan-card";+import { PaymentMethodsCard } from "./components/payment-methods-card";import { ProPlanCard } from "./components/pro-plan-card";+import { SupportCard } from "./components/support-card";export default async function BillingSettingsPage() {if (!isFeatureEnabled("billing")) {@@ -68,9 +64,10 @@ export default async function BillingSettingsPage() {);}- const [overview, seatUsage] = await Promise.all([+ const [overview, seatUsage, paymentMethods] = await Promise.all([loadSubscriptionOverview(),getSeatUsage(),+ loadPaymentMethods(),]);return (@@ -87,59 +84,36 @@ export default async function BillingSettingsPage() {</SettingsPageDescription></SettingsPageHeader><SettingsPageContent>- <PageSectionGroup>- <PageSection>- <PageSectionHeader>- <PageSectionTitle>- <Trans i18nKey="billingPlanTitle" defaults="Plan" />- </PageSectionTitle>- <PageSectionDescription>- <Trans- i18nKey="billingSubscriptionDescription"- defaults="Manage your current subscription plan."- />- </PageSectionDescription>- </PageSectionHeader>- <PageSectionContent>- {overview?.subscription.active ? (- <ProPlanCard- amount={overview.subscription.amount}- discountPercentOff={overview.subscription.discountPercentOff}- discountAmountOff={overview.subscription.discountAmountOff}- currency={overview.subscription.currency}- interval={overview.subscription.interval}- seats={overview.subscription.quantity}- usedSeats={seatUsage.used}- status={overview.subscription.status}- cancelAtPeriodEnd={overview.subscription.cancelAtPeriodEnd}- periodEnd={overview.subscription.periodEnd}- earlySupporter={overview.earlySupporter}- listPrice={overview.listPrice}- />- ) : (- <HobbyPlanCard />- )}- <BillingFlashAlert />- </PageSectionContent>- </PageSection>- <PageSectionDivider />- <PageSection>- <PageSectionHeader>- <PageSectionTitle>- <Trans i18nKey="support" defaults="Support" />- </PageSectionTitle>- <PageSectionDescription>- <Trans- i18nKey="supportDescription"- defaults="Need help with anything?"- />- </PageSectionDescription>- </PageSectionHeader>- <PageSectionContent>- <ContactSupportLink />- </PageSectionContent>- </PageSection>- </PageSectionGroup>+ <div className="space-y-4">+ {overview?.subscription.active ? (+ <ProPlanCard+ amount={overview.subscription.amount}+ discountPercentOff={overview.subscription.discountPercentOff}+ discountAmountOff={overview.subscription.discountAmountOff}+ currency={overview.subscription.currency}+ interval={overview.subscription.interval}+ seats={overview.subscription.quantity}+ usedSeats={seatUsage.used}+ status={overview.subscription.status}+ cancelAtPeriodEnd={overview.subscription.cancelAtPeriodEnd}+ periodEnd={overview.subscription.periodEnd}+ earlySupporter={overview.earlySupporter}+ listPrice={overview.listPrice}+ switchToYearly={overview.switchToYearly}+ canResume={overview.canResume}+ />+ ) : (+ <HobbyPlanCard />+ )}+ <BillingFlashAlert />+ {overview?.subscription.active ? (+ <div className="grid gap-4 lg:grid-cols-2">+ <PaymentMethodsCard paymentMethods={paymentMethods} />+ <BillingDetailsCard />+ </div>+ ) : null}+ <SupportCard />+ </div></SettingsPageContent></SettingsPage>);diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.tsindex 1be3f4c21..5e1e311fe 100644--- a/apps/web/src/features/billing/actions.ts+++ b/apps/web/src/features/billing/actions.ts@@ -4,7 +4,14 @@ import { displayedCurrencies, getProPricing } from "@rallly/billing";import { absoluteUrl } from "@rallly/utils/absolute-url";import { redirect } from "next/navigation";import * as z from "zod";-import { createStripePortalSession } from "@/features/billing/mutations";+import { getProPrices, getSpaceSubscription } from "@/features/billing/data";+import {+ createAccountPortalSession,+ createPaymentMethodUpdateSession,+ createStripeCancelSession,+ createStripeSubscriptionUpdateConfirmation,+ resumeSubscriptionRenewal,+} from "@/features/billing/mutations";import { getNonprofitStatus } from "@/features/billing/nonprofit/data";import { ensureNonprofitCoupon } from "@/features/billing/nonprofit/mutations";import { buildCheckoutDiscountParams } from "@/features/billing/nonprofit/utils";@@ -14,7 +21,13 @@ import type {SubscriptionMetadata,} from "@/features/billing/schema";import { getStripe } from "@/features/billing/service";+import {+ canChangeBillingInterval,+ isEarlySupporter,+ resolvePriceSet,+} from "@/features/billing/utils";import { getActiveSpaceForUser } from "@/features/space/data";+import { defineAbilityForMember } from "@/features/space/member/ability";import { AppError } from "@/lib/errors/app-error";import { track } from "@/lib/posthog";import { authActionClient } from "@/lib/safe-action/server";@@ -64,17 +77,8 @@ export const upgradeToProAction = authActionClient}if (space.tier === "pro") {- // User already has an active subscription. Take them to customer portal- if (!ctx.user.customerId) {- throw new AppError({- code: "NOT_FOUND",- message: "No customer ID found",- });- }-- redirect(- await createStripePortalSession({ customerId: ctx.user.customerId }),- );+ // Already subscribed; the billing page has every plan action.+ redirect("/settings/billing");}const { period, currency, returnPath } = parsedInput;@@ -180,25 +184,160 @@ export const upgradeToProAction = authActionClientredirect(checkoutSession.url);});-export const openCustomerPortalAction = authActionClient- .metadata({ actionName: "open_customer_portal" })- .inputSchema(- z.object({- returnPath: returnPathSchema.optional(),- }),- )- .action(async ({ ctx, parsedInput }) => {- if (!ctx.user.customerId) {+/**+ * The active space's subscription, proven manageable by the caller: the+ * caller must hold `manage Billing` on the space (owner) and the subscription+ * must belong to that space. Every subscription changing action starts here.+ */+async function requireManagedSubscription(user: {+ id: string;+ customerId?: string;+}) {+ const space = await getActiveSpaceForUser(user.id);++ if (!space) {+ throw new AppError({ code: "NOT_FOUND", message: "Space not found" });+ }++ const ability = defineAbilityForMember({+ user: { id: user.id },+ space: { id: space.id, ownerId: space.ownerId, role: space.role },+ });++ if (ability.cannot("manage", "Billing")) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Only the space owner can manage billing",+ });+ }++ const subscription = await getSpaceSubscription(space.id);++ if (!subscription?.active) {+ throw new AppError({+ code: "NOT_FOUND",+ message: "No active subscription for this space",+ });+ }++ if (!user.customerId) {+ throw new AppError({ code: "NOT_FOUND", message: "No customer ID found" });+ }++ return { space, subscription, customerId: user.customerId };+}++export const switchToYearlyAction = authActionClient+ .metadata({ actionName: "switch_to_yearly" })+ .action(async ({ ctx }) => {+ const { space, subscription, customerId } =+ await requireManagedSubscription(ctx.user);++ // The card only offers monthly to yearly, but the action is callable+ // directly, so the same rule is enforced here. Yearly to monthly would+ // need a subscription schedule to let the paid year run out.+ if (!canChangeBillingInterval(subscription)) {throw new AppError({- code: "NOT_FOUND",- message: "No customer ID found",+ code: "FORBIDDEN",+ message: "This subscription cannot switch to yearly billing",});}+ const pricing = await getProPrices();+ const priceSet = resolvePriceSet({+ earlySupporter: isEarlySupporter({+ priceId: subscription.priceId,+ pricing,+ }),+ pricing,+ });++ track(ctx.user, {+ event: "space_billing:switch_to_yearly_submit",+ groups: { space: space.id },+ });++ redirect(+ await createStripeSubscriptionUpdateConfirmation({+ customerId,+ subscriptionId: subscription.id,+ subscriptionItemId: subscription.subscriptionItemId,+ priceIds: [+ priceSet.monthly.id,+ priceSet.yearly.id,+ subscription.priceId,+ ],+ item: { price: priceSet.yearly.id, quantity: subscription.quantity },+ returnFlow: "interval",+ }),+ );+ });++export const openCancelPlanAction = authActionClient+ .metadata({ actionName: "open_cancel_plan" })+ .action(async ({ ctx }) => {+ const { space, subscription, customerId } =+ await requireManagedSubscription(ctx.user);++ track(ctx.user, {+ event: "space_billing:cancel_plan_click",+ properties: { interval: subscription.interval },+ groups: { space: space.id },+ });+redirect(- await createStripePortalSession({- customerId: ctx.user.customerId,- returnPath: parsedInput.returnPath,+ await createStripeCancelSession({+ customerId,+ subscriptionId: subscription.id,}),);});++export const resumePlanAction = authActionClient+ .metadata({ actionName: "resume_plan" })+ .action(async ({ ctx }) => {+ // Resuming inside the deletion recovery window would fight the reaper;+ // cancelling the deletion is the path that restores renewals.+ if (ctx.user.deletedAt) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Cancel the account deletion to resume the subscription",+ });+ }++ const { space, subscription } = await requireManagedSubscription(ctx.user);++ await resumeSubscriptionRenewal({ subscriptionId: subscription.id });++ track(ctx.user, {+ event: "space_billing:resume_plan_click",+ properties: { interval: subscription.interval },+ groups: { space: space.id },+ });+ });++export const openBillingDetailsAction = authActionClient+ .metadata({ actionName: "open_billing_details" })+ .action(async ({ ctx }) => {+ const { space, customerId } = await requireManagedSubscription(ctx.user);++ track(ctx.user, {+ event: "space_billing:billing_details_click",+ groups: { space: space.id },+ });++ redirect(await createAccountPortalSession({ customerId }));+ });++export const openPaymentMethodUpdateAction = authActionClient+ .metadata({ actionName: "open_payment_method_update" })+ .action(async ({ ctx }) => {+ const { space, customerId } = await requireManagedSubscription(ctx.user);++ track(ctx.user, {+ event: "space_billing:payment_method_click",+ groups: { space: space.id },+ });++ redirect(await createPaymentMethodUpdateSession({ customerId }));+ });diff --git a/apps/web/src/features/billing/components/billing-flash-alert.tsx b/apps/web/src/features/billing/components/billing-flash-alert.tsxindex f39bd53b4..6c9f17d03 100644--- a/apps/web/src/features/billing/components/billing-flash-alert.tsx+++ b/apps/web/src/features/billing/components/billing-flash-alert.tsx@@ -22,17 +22,21 @@ export function BillingFlashAlert() {<Trans i18nKey="seatsUpdatedAlertTitle" defaults="Seats updated" /></AlertTitle>) : flow.data === "interval" ? (+ <AlertTitle>+ <Trans i18nKey="planChangedAlertTitle" defaults="Plan changed" />+ </AlertTitle>+ ) : flow.data === "cancel" ? (<><AlertTitle><Trans- i18nKey="billingIntervalUpdatedAlertTitle"- defaults="Switched to yearly billing"+ i18nKey="planCancelScheduledAlertTitle"+ defaults="Cancellation scheduled"/></AlertTitle><AlertDescription><Trans- i18nKey="billingIntervalUpdatedAlertDescription"- defaults="Your subscription now renews once a year."+ i18nKey="planCancelScheduledAlertDescription"+ defaults="Your plan stays active until the end of the current billing period. You can resume it any time before then."/></AlertDescription></>diff --git a/apps/web/src/features/billing/components/subscription-status-badge.tsx b/apps/web/src/features/billing/components/subscription-status-badge.tsxindex 2c956af43..6e767fe42 100644--- a/apps/web/src/features/billing/components/subscription-status-badge.tsx+++ b/apps/web/src/features/billing/components/subscription-status-badge.tsx@@ -12,7 +12,8 @@ export function SubscriptionStatusBadge({switch (status) {case "active":return (- <Badge variant="green">+ <Badge variant="green" className="gap-1.5">+ <span className="size-1.5 rounded-full bg-current" /><Trans i18nKey="subscriptionStatusActive" defaults="Active" /></Badge>);@@ -30,7 +31,7 @@ export function SubscriptionStatusBadge({);case "past_due":return (- <Badge variant="destructive">+ <Badge variant="amber"><Trans i18nKey="subscriptionStatusPastDue" defaults="Past due" /></Badge>);diff --git a/apps/web/src/features/billing/data.ts b/apps/web/src/features/billing/data.tsindex 902e58ebd..38f379fad 100644--- a/apps/web/src/features/billing/data.ts+++ b/apps/web/src/features/billing/data.ts@@ -3,6 +3,7 @@ import "server-only";import { getProPricing } from "@rallly/billing";import { prisma } from "@rallly/database";import { unstable_cache } from "next/cache";+import { paymentMethodCardSchema } from "@/features/billing/schema";import { getStripe } from "@/features/billing/service";import type { SpaceTier } from "@/features/space/schema";@@ -53,3 +54,24 @@ export const getProPrices = unstable_cache(["pro-prices-v2"],{ revalidate: 60 * 60 },);++/**+ * The customer's stored payment methods, written by the payment_method.*+ * webhooks. `data` holds the type specific object Stripe sends, so a card+ * carries brand, last4 and expiry.+ */+export async function getPaymentMethods(userId: string) {+ const paymentMethods = await prisma.paymentMethod.findMany({+ where: { userId },+ orderBy: { createdAt: "desc" },+ });++ return paymentMethods.map((paymentMethod) => {+ const card = paymentMethodCardSchema.safeParse(paymentMethod.data);+ return {+ id: paymentMethod.id,+ type: paymentMethod.type,+ card: card.success ? card.data : null,+ };+ });+}diff --git a/apps/web/src/features/billing/loaders.ts b/apps/web/src/features/billing/loaders.tsindex 115fd62c6..166f0fea0 100644--- a/apps/web/src/features/billing/loaders.ts+++ b/apps/web/src/features/billing/loaders.ts@@ -5,8 +5,17 @@ import { CURRENCY_COOKIE_NAME, getCountryCurrency } from "@rallly/billing";import { cookies, headers } from "next/headers";import { cache } from "react";import { isBillingEnabled } from "@/features/billing/constants";-import { getProPrices, getSpaceSubscription } from "@/features/billing/data";-import { isEarlySupporter } from "@/features/billing/utils";+import {+ getPaymentMethods,+ getProPrices,+ getSpaceSubscription,+} from "@/features/billing/data";+import type { BillingInterval } from "@/features/billing/schema";+import {+ canChangeBillingInterval,+ isEarlySupporter,+ resolvePriceSet,+} from "@/features/billing/utils";import { getActiveSpace } from "@/features/space/loaders";import { defineAbilityForMember } from "@/features/space/member/ability";import { getCurrentUser, requireUser } from "@/features/user/loaders";@@ -79,6 +88,30 @@ export const loadSubscriptionOverview = cache(async () => {});const currency = subscription.currency;+ // The other interval from the subscriber's own price set, so an early+ // supporter switches between the early supporter prices, never onto list.+ const priceSet = pricing+ ? resolvePriceSet({ earlySupporter, pricing })+ : null;+ const otherInterval: BillingInterval =+ subscription.interval === "month" ? "year" : "month";+ const otherPrice =+ otherInterval === "month" ? priceSet?.monthly : priceSet?.yearly;+ const otherAmount = otherPrice?.amounts[currency];+ const otherListAmount =+ otherInterval === "month"+ ? pricing?.monthly.amounts[currency]+ : pricing?.yearly.amounts[currency];++ // Yearly is the upgrade, so only monthly subscribers are offered a switch.+ // Downgrading would need a subscription schedule to let the paid year run+ // out; until anyone asks for it, yearly subscribers go through support.+ // The yearly price comes from the subscriber's own price set, so an early+ // supporter switches onto the early supporter yearly, never onto list.+ const yearlyAmount = pricing+ ? resolvePriceSet({ earlySupporter, pricing }).yearly.amounts[currency]+ : undefined;+return {subscription,earlySupporter,@@ -88,6 +121,23 @@ export const loadSubscriptionOverview = cache(async () => {yearly: pricing.yearly.amounts[currency],}: null,+ switchToYearly:+ canChangeBillingInterval(subscription) && yearlyAmount !== undefined+ ? { monthlyAmount: subscription.amount, yearlyAmount }+ : null,+ changePlan:+ subscription.active &&+ !subscription.cancelAtPeriodEnd &&+ otherAmount !== undefined+ ? {+ interval: otherInterval,+ amount: otherAmount,+ listAmount:+ earlySupporter && otherListAmount !== otherAmount+ ? otherListAmount+ : undefined,+ }+ : null,// The deletion recovery window reaps the space regardless of renewal;// resuming there would fight the reaper, so cancelling the deletion is// the only way to restore renewals.@@ -95,6 +145,21 @@ export const loadSubscriptionOverview = cache(async () => {};});+/**+ * The signed in user's saved payment methods, written by the payment_method.*+ * webhooks. Keyed by user rather than customer id, which can be absent on+ * rows written before the customer.created webhook landed.+ */+export const loadPaymentMethods = cache(async () => {+ const user = await getCurrentUser();++ if (!user) {+ return [];+ }++ return getPaymentMethods(user.id);+});+/*** Whether to warn the active space about a failed payment. Gated on the same* ability as the billing page so the warning never links a member to a pagediff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.tsindex 007525db0..cff027941 100644--- a/apps/web/src/features/billing/mutations.ts+++ b/apps/web/src/features/billing/mutations.ts@@ -233,6 +233,88 @@ 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,+ subscriptionId,+}: {+ customerId: string;+ subscriptionId: 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") },+ },+ },+ });+ return session.url;+}++/**+ * The account portal: invoices, payment methods, billing address and tax id.+ * Its configuration disables every subscription control, so the plan can only+ * be changed from our own card.+ */+export async function createAccountPortalSession({+ customerId,+}: {+ customerId: string;+}) {+ const session = await getStripe().billingPortal.sessions.create({+ customer: customerId,+ configuration: await getAccountPortalConfigurationId(),+ return_url: absoluteUrl("/settings/billing"),+ });+ return session.url;+}++export async function createPaymentMethodUpdateSession({+ customerId,+}: {+ customerId: string;+}) {+ const session = await getStripe().billingPortal.sessions.create({+ customer: customerId,+ configuration: await getAccountPortalConfigurationId(),+ return_url: absoluteUrl("/settings/billing"),+ flow_data: {+ type: "payment_method_update",+ after_completion: {+ type: "redirect",+ redirect: { return_url: billingReturnUrl("payment_method") },+ },+ },+ });+ return session.url;+}++// Stripe is the source of truth and the webhook writes the same value, but+// the page re-renders as soon as the action returns, so the row is updated+// here too rather than showing "Ends" for a few seconds after resuming.+export async function resumeSubscriptionRenewal({+ subscriptionId,+}: {+ subscriptionId: string;+}) {+ await getStripe().subscriptions.update(subscriptionId, {+ cancel_at_period_end: false,+ });+ await prisma.subscription.update({+ where: { id: subscriptionId },+ data: { cancelAtPeriodEnd: false },+ });+}+// Scheduling an account deletion must guarantee no further charges without// destroying anything: cancel_at_period_end stops the renewal while keeping// the paid-for time, and is reversible if the deletion is cancelled.diff --git a/apps/web/src/features/billing/schema.ts b/apps/web/src/features/billing/schema.tsindex bf4e2c1e4..767a30ed2 100644--- a/apps/web/src/features/billing/schema.ts+++ b/apps/web/src/features/billing/schema.ts@@ -40,5 +40,16 @@ export const billingReturnFlowSchema = z.enum(["seats","interval","payment_method",+ "cancel",]);export type BillingReturnFlow = z.infer<typeof billingReturnFlowSchema>;++// 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({+ brand: z.string(),+ last4: z.string(),+ exp_month: z.number(),+ exp_year: z.number(),+});+export type PaymentMethodCard = z.infer<typeof paymentMethodCardSchema>;diff --git a/apps/web/src/features/billing/utils.test.ts b/apps/web/src/features/billing/utils.test.tsindex e4702a507..a3b15963b 100644--- a/apps/web/src/features/billing/utils.test.ts+++ b/apps/web/src/features/billing/utils.test.ts@@ -106,7 +106,13 @@ describe("formatMinorUnitAmount", () => {it("formats minor units as a localized currency string", () => {expect(formatMinorUnitAmount({ amount: 5600, currency: "usd", locale: "en" }),- ).toBe("$56.00");+ ).toBe("$56");+ });++ it("keeps cents when the amount needs them", () => {+ expect(+ formatMinorUnitAmount({ amount: 467, currency: "usd", locale: "en" }),+ ).toBe("$4.67");});it("does not scale zero decimal currencies", () => {diff --git a/apps/web/src/features/billing/utils.ts b/apps/web/src/features/billing/utils.tsindex 31edca66e..699174846 100644--- a/apps/web/src/features/billing/utils.ts+++ b/apps/web/src/features/billing/utils.ts@@ -1,5 +1,9 @@import type { PricingData, ProPrice } from "@rallly/billing";import { isBillingEnabled } from "@/features/billing/constants";+import type {+ BillingInterval,+ SubscriptionStatus,+} from "@/features/billing/schema";import type { SpaceTier } from "@/features/space/schema";/**@@ -67,13 +71,39 @@ export function formatMinorUnitAmount({currency: string;locale: string;}) {- const formatter = new Intl.NumberFormat(locale, {- style: "currency",- currency: currency.toUpperCase(),- });+ const code = currency.toUpperCase();// Stripe amounts are in the currency's minor unit, which Intl knows: two// fraction digits for most currencies, none for JPY and friends.const minorUnitDigits =- formatter.resolvedOptions().maximumFractionDigits ?? 2;- return formatter.format(amount / 10 ** minorUnitDigits);+ new Intl.NumberFormat(locale, {+ style: "currency",+ currency: code,+ }).resolvedOptions().maximumFractionDigits ?? 2;+ // Whole amounts render without trailing zeros ("$10", not "$10.00").+ return new Intl.NumberFormat(locale, {+ style: "currency",+ currency: code,+ minimumFractionDigits: 0,+ maximumFractionDigits: minorUnitDigits,+ }).format(amount / 10 ** minorUnitDigits);+}++/**+ * A subscription that renews and can therefore change billing interval.+ * `past_due` is stored as active (Stripe keeps retrying), but its next+ * invoice is unpaid, so a plan change there would compound the problem.+ */+export function canChangeBillingInterval(subscription: {+ active: boolean;+ status: SubscriptionStatus;+ cancelAtPeriodEnd: boolean;+ interval: BillingInterval;+}) {+ return (+ subscription.active &&+ (subscription.status === "active" || subscription.status === "trialing") &&+ !subscription.cancelAtPeriodEnd &&+ // Yearly to monthly would need a schedule to let the paid year run out.+ subscription.interval === "month"+ );}diff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsxindex 1cf66eb05..04dbfa743 100644--- a/packages/ui/src/badge.tsx+++ b/packages/ui/src/badge.tsx@@ -5,7 +5,7 @@ import type * as React from "react";import { cn } from "./lib/utils";const badgeVariants = cva(- "group inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-lg transition-colors focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2",+ "group inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-lg font-normal transition-colors focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants: {variant: {@@ -17,6 +17,8 @@ const badgeVariants = cva(green:"bg-green-400/10 text-green-600 dark:bg-green-500/10 dark:text-green-500",pink: "bg-pink-400/10 text-pink-600 dark:bg-pink-500/10 dark:text-pink-400",+ amber:+ "bg-amber-400/10 text-amber-700 dark:bg-amber-500/10 dark:text-amber-500",secondary: "bg-primary/10 text-primary",pill: "rounded-full bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-200",},