Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Team checkout from a single /team link (#8800)

Reece Browne046f1a0e7163
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index c044ee6aa9..e6d7885739 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7126,6 +7126,7 @@ resetsTomorrow = "Resets tomorrow"
thisPeriod = "This billing period"
[payment]
+annually = "Annually"
billingPeriod = "Billing period"
cancelTeamChange = "Keep current plan"
canCloseWindow = "You can now close this window."
@@ -7144,7 +7145,7 @@ manageSubscription = "Manage subscription"
monthly = "Monthly"
paymentCanceled = "Payment was canceled. No charges were made."
perMonth = "/month"
-perUserBlock = "per 100 users"
+perUserBlock = "per {{users}} users"
planPeriodUnavailable = "Selected plan period is not available"
preparing = "Preparing your checkout..."
redirecting = "Redirecting to secure checkout..."
@@ -7175,11 +7176,14 @@ title = "Adjust Team plan"
[payment.capacityStage]
adjustmentNote = "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available."
+billingLabel = "Billing"
continue = "Continue to payment"
currencyAtCheckout = "Stripe confirms the final amount and payment currency at checkout."
+custom = "Custom"
customLabel = "Number of users"
dueToday = "Due today"
enterpriseQuote = "Get an enterprise quote"
+enterUsers = "Enter a number of users."
estimatedTotal = "Estimated total"
lineItem = "Team · {{price}}{{period}} per {{block}} users"
minimumForCurrentUsers = "You have {{users}} users, so the plan must cover at least {{minimum}}."
@@ -7191,12 +7195,16 @@ overCapacityConsequence = "Existing accounts stay in place. Adding or inviting u
overCapacityTitle = "Your server has more users than your plan covers"
perMonth = "/mo"
perYear = "/yr"
+planName = "Stirling Team"
reductionNote = "The lower capacity starts at your next renewal. Until then, you can use your current allowance. Existing users stay; new users are blocked if you are over capacity when the change takes effect."
renewalNote = "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing."
reviewChange = "Review change in Stripe"
-roundsTo = "rounds to {{users}}"
+roundsUp = "Rounds up to {{users}} users."
+selfServeLimit = "Up to {{users}} users here."
subheading = "Covers everyone you invite, in blocks of {{users}} users."
subheadingAdd = "Your plan covers {{current}} users today. Choose the new total."
+talkToEnterprise = "For more, talk to us about Enterprise."
+usersCovered = "users covered"
usersLabel = "Users"
userTotal = "{{users}} users"
@@ -7228,7 +7236,7 @@ totalSeats_one = "Total ({{count}} seat)"
totalSeats_other = "Total ({{count}} seats)"
[payment.upgradeTeam]
-title = "Upgrade to Team"
+title = "Get Stirling Team"
[pdfOrganiser]
placeholder = "(e.g. 1,3,2 or 4-8,2,10-12 or 2n-1)"
@@ -7883,7 +7891,7 @@ sso = "SSO (OAuth2/OIDC)"
upToFiveUsers = "Up to 5 users"
upToFiveUsersLowercase = "up to 5 users"
usageTracking = "Usage tracking"
-usersIncluded = "100 users included"
+usersIncluded = "{{users}} users included"
usersLimitedToSeats = "Users limited to seats"
[plan.free]
@@ -7914,7 +7922,7 @@ selfHostedOnInfrastructure = "Self-hosted on your infrastructure"
ssoOAuth = "SSO (OAuth2/OIDC)"
upToFiveUsers = "Up to 5 users"
usageTrackingPrometheus = "Usage tracking & Prometheus"
-usersIncluded = "100 users included"
+usersIncluded = "{{users}} users included"
[plan.period]
month = "month"
@@ -7957,7 +7965,7 @@ success = "License Activated!"
successMessage = "Your license has been successfully activated. You can now close this window."
[plan.team]
-maxUsers = "100 users"
+maxUsers = "{{users}} users"
name = "Team"
[policies.activity]
@@ -8338,7 +8346,7 @@ rowUsers = "Users"
rowWhere = "Where it runs"
teamData = "Google Drive, your own database"
teamName = "Team"
-teamPrice = "$99/mo per 100 users"
+teamPrice = "$99/mo per {{users}} users"
teamProcessing = "{{allowance}} a month, then metered"
teamProcessingUnknown = "A larger allowance, then metered"
teamSignIn = "The same"
@@ -8609,11 +8617,11 @@ title = "Couldn't open Stripe portal"
addCapacity = "Add capacity"
fact = "{{users}} of {{licensed}} users"
factNoLimit = "{{users}} users"
-midFree = "The Team plan covers 100 users"
+midFree = "The Team plan covers {{users}} users"
midFreeSelfHosted = "The free tier covers your first users"
midIncluded = "Included with your Team base"
midLocalCapacity = "Capacity available to this server"
-midPrice = "$99/mo per 100 users"
+midPrice = "$99/mo per {{users}} users"
rowName = "Users"
[portal.components.billingUnit]
@@ -13473,6 +13481,11 @@ remove = "Remove"
roleColumn = "Role"
title = "Team Members"
+[teamWelcome]
+invite = "Invite people"
+message = "Invite your team so they can start working with you."
+title = "Your Team plan is active."
+
[textAlign]
center = "Center"
left = "Left"
@@ -13675,7 +13688,7 @@ urgent = "Urgent"
attentionBody = "Your admin needs to sign in to see more info. Please contact them immediately."
attentionBodyAdmin = "Review the license requirements to keep this server compliant."
attentionTitle = "This server needs admin attention"
-message = "Get the most out of Stirling PDF with 100 users, PDF text editing, and advanced features"
+message = "Get the most out of Stirling PDF with {{users}} users, PDF text editing, and advanced features"
seeInfo = "See info"
title = "Upgrade to the Team plan"
upgradeButton = "Upgrade Now"
diff --git a/frontend/src/editor/core/components/onboarding/Onboarding.tsx b/frontend/src/editor/core/components/onboarding/Onboarding.tsx
index 09895c1d04..029d521983 100644
--- a/frontend/src/editor/core/components/onboarding/Onboarding.tsx
+++ b/frontend/src/editor/core/components/onboarding/Onboarding.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useCallback, useState, useRef } from "react";
import { type StepType } from "@reactour/tour";
import { useTranslation } from "react-i18next";
import { useNavigate, useLocation } from "react-router-dom";
+import { TEAM_CHECKOUT_PATH } from "@editor/routes/teamCheckoutLink";
import { isAuthRoute } from "@editor/constants/routes";
import { dispatchTourState } from "@editor/constants/events";
import { useOnboardingOrchestrator } from "@editor/components/onboarding/orchestrator/useOnboardingOrchestrator";
@@ -266,7 +267,7 @@ export default function Onboarding() {
!serverExperience.hasPaidLicense &&
serverExperience.overFreeTierLimit === true
) {
- navigate("/settings/billing?upgrade=team");
+ navigate(TEAM_CHECKOUT_PATH);
}
}, [
showLicenseSlide,
diff --git a/frontend/src/editor/core/routes/teamCheckoutLink.ts b/frontend/src/editor/core/routes/teamCheckoutLink.ts
new file mode 100644
index 0000000000..3b4eb8e41d
--- /dev/null
+++ b/frontend/src/editor/core/routes/teamCheckoutLink.ts
@@ -0,0 +1,9 @@
+/** Query flag asking Usage & Billing to open the Team checkout on arrival. */
+export const TEAM_CHECKOUT_PARAM = "upgrade";
+const TEAM_CHECKOUT_VALUE = "team";
+
+export const TEAM_CHECKOUT_PATH = `/settings/billing?${TEAM_CHECKOUT_PARAM}=${TEAM_CHECKOUT_VALUE}`;
+
+export function requestsTeamCheckout(params: URLSearchParams): boolean {
+ return params.get(TEAM_CHECKOUT_PARAM) === TEAM_CHECKOUT_VALUE;
+}
diff --git a/frontend/src/editor/proprietary/billing/ComparePlansModal.tsx b/frontend/src/editor/proprietary/billing/ComparePlansModal.tsx
index 26f1530d77..728a2b1df4 100644
--- a/frontend/src/editor/proprietary/billing/ComparePlansModal.tsx
+++ b/frontend/src/editor/proprietary/billing/ComparePlansModal.tsx
@@ -1,5 +1,6 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
+import { USERS_PER_BLOCK } from "@editor/components/shared/stripeCheckout/utils/capacity";
import { Button, Modal } from "@editor/ui";
export type ComparePlan = "free" | "team" | "enterprise";
@@ -73,7 +74,13 @@ export function ComparePlansModal({
{
plan: "team",
name: t("portal.billing.compare.teamName", "Team"),
- price: t("portal.billing.compare.teamPrice", "$99/mo per 100 users"),
+ price: t(
+ "portal.billing.compare.teamPrice",
+ "$99/mo per {{users}} users",
+ {
+ users: USERS_PER_BLOCK,
+ },
+ ),
},
{
plan: "enterprise",
diff --git a/frontend/src/editor/proprietary/billing/TeamPlanRow.tsx b/frontend/src/editor/proprietary/billing/TeamPlanRow.tsx
index 809749d4d5..a02549ae90 100644
--- a/frontend/src/editor/proprietary/billing/TeamPlanRow.tsx
+++ b/frontend/src/editor/proprietary/billing/TeamPlanRow.tsx
@@ -1,4 +1,5 @@
import { useTranslation } from "react-i18next";
+import { USERS_PER_BLOCK } from "@editor/components/shared/stripeCheckout/utils/capacity";
import { MeterRow } from "@editor/billing/MeterRow";
import type { ServerPlan } from "@editor/billing/serverPlan";
import type { Wallet } from "@editor/billing/types";
@@ -157,10 +158,18 @@ export function TeamPlanRow({
"portal.billing.team.midFreeSelfHosted",
"The free tier covers your first users",
)
- : t("portal.billing.team.midFree", "The Team plan covers 100 users")
+ : t(
+ "portal.billing.team.midFree",
+ "The Team plan covers {{users}} users",
+ {
+ users: USERS_PER_BLOCK,
+ },
+ )
: processorActive
? t("portal.billing.team.midIncluded", "Included with your Team base")
- : t("portal.billing.team.midPrice", "$99/mo per 100 users");
+ : t("portal.billing.team.midPrice", "$99/mo per {{users}} users", {
+ users: USERS_PER_BLOCK,
+ });
const door = onAddCapacity
? t("portal.billing.team.addCapacity", "Add capacity")
diff --git a/frontend/src/editor/proprietary/billing/teamWelcome.ts b/frontend/src/editor/proprietary/billing/teamWelcome.ts
new file mode 100644
index 0000000000..b50eda353b
--- /dev/null
+++ b/frontend/src/editor/proprietary/billing/teamWelcome.ts
@@ -0,0 +1,13 @@
+/**
+ * Router state for the navigation into the editor after buying Team, so the editor offers to
+ * invite the buyer's team once.
+ */
+export const TEAM_WELCOME_STATE = { teamWelcome: true } as const;
+
+export function isTeamWelcome(state: unknown): boolean {
+ return (
+ typeof state === "object" &&
+ state !== null &&
+ (state as { teamWelcome?: unknown }).teamWelcome === true
+ );
+}
diff --git a/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.stories.tsx b/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.stories.tsx
new file mode 100644
index 0000000000..dcc8fe4ca9
--- /dev/null
+++ b/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.stories.tsx
@@ -0,0 +1,31 @@
+import { useEffect } from "react";
+import { useNavigate } from "react-router-dom";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { TeamWelcomeBanner } from "@editor/components/shared/TeamWelcomeBanner";
+import { TEAM_WELCOME_STATE } from "@editor/billing/teamWelcome";
+
+/** Arrives at the editor the way billing sends a buyer after a Team purchase. */
+function ArriveFromPurchase() {
+ const navigate = useNavigate();
+ useEffect(() => {
+ navigate("/editor", { state: TEAM_WELCOME_STATE });
+ }, [navigate]);
+ return null;
+}
+
+/** Shown once in the editor after a Team purchase. */
+const meta = {
+ title: "Shared/TeamWelcomeBanner",
+ component: TeamWelcomeBanner,
+ parameters: { layout: "fullscreen" },
+ render: () => (
+ <>
+ <ArriveFromPurchase />
+ <TeamWelcomeBanner />
+ </>
+ ),
+} satisfies Meta<typeof TeamWelcomeBanner>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const JustBoughtTeam: Story = {};
diff --git a/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.test.tsx b/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.test.tsx
new file mode 100644
index 0000000000..b5355d89fb
--- /dev/null
+++ b/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.test.tsx
@@ -0,0 +1,87 @@
+import { describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { StrictMode } from "react";
+import {
+ MemoryRouter,
+ Route,
+ Routes,
+ useLocation,
+ useNavigate,
+} from "react-router-dom";
+import { TeamWelcomeBanner } from "@editor/components/shared/TeamWelcomeBanner";
+import { TEAM_WELCOME_STATE } from "@editor/billing/teamWelcome";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),
+}));
+
+const TITLE = "Your Team plan is active.";
+
+let navigateTo: ReturnType<typeof useNavigate> = () => {};
+
+function Shell() {
+ navigateTo = useNavigate();
+ const { pathname, state } = useLocation();
+ return (
+ <>
+ <output data-testid="location">{pathname}</output>
+ <output data-testid="state">{JSON.stringify(state)}</output>
+ </>
+ );
+}
+
+// The banner sits in a slot that outlives navigation, as AppLayout's does.
+function renderApp(entry: string) {
+ render(
+ <StrictMode>
+ <MantineProvider>
+ <MemoryRouter initialEntries={[entry]}>
+ <TeamWelcomeBanner />
+ <Routes>
+ <Route path="*" element={<Shell />} />
+ </Routes>
+ </MemoryRouter>
+ </MantineProvider>
+ </StrictMode>,
+ );
+}
+
+const arriveFromPurchase = () =>
+ act(() => {
+ navigateTo("/editor", { state: TEAM_WELCOME_STATE });
+ });
+
+describe("TeamWelcomeBanner", () => {
+ it("shows nothing on an ordinary visit", () => {
+ renderApp("/editor");
+ expect(screen.queryByText(TITLE)).toBeNull();
+ });
+
+ it("appears when billing sends the buyer to the editor, and clears the state", () => {
+ renderApp("/settings/billing");
+ expect(screen.queryByText(TITLE)).toBeNull();
+
+ arriveFromPurchase();
+
+ expect(screen.getByText(TITLE)).toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/editor");
+ expect(screen.getByTestId("state")).toHaveTextContent("null");
+ });
+
+ it("sends the buyer to the invite screen and does not come back", () => {
+ renderApp("/settings/billing");
+ arriveFromPurchase();
+
+ fireEvent.click(screen.getByRole("button", { name: /Invite people/ }));
+
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/settings/people",
+ );
+ expect(screen.queryByText(TITLE)).toBeNull();
+ act(() => {
+ navigateTo("/editor");
+ });
+ expect(screen.queryByText(TITLE)).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.tsx b/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.tsx
new file mode 100644
index 0000000000..fede167b75
--- /dev/null
+++ b/frontend/src/editor/proprietary/components/shared/TeamWelcomeBanner.tsx
@@ -0,0 +1,45 @@
+import { useEffect, useState } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+import { AppBanner } from "@editor/components/shared/AppBanner";
+import { isTeamWelcome } from "@editor/billing/teamWelcome";
+
+/** One-time prompt after buying Team: the editor is where the buyer lands, and inviting is the next step. */
+export function TeamWelcomeBanner() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { pathname, search, hash, state } = useLocation();
+ const [show, setShow] = useState(false);
+ const welcomed = isTeamWelcome(state);
+
+ // The banner slot outlives navigation, so the state is checked on every arrival. Clearing it
+ // keeps a reload or a return to this history entry from showing the banner again.
+ useEffect(() => {
+ if (!welcomed) return;
+ setShow(true);
+ navigate({ pathname, search, hash }, { replace: true, state: null });
+ }, [welcomed, navigate, pathname, search, hash]);
+
+ if (!show) return null;
+
+ const close = () => setShow(false);
+
+ return (
+ <AppBanner
+ tone="promo"
+ icon="users"
+ title={t("teamWelcome.title", "Your Team plan is active.")}
+ message={t(
+ "teamWelcome.message",
+ "Invite your team so they can start working with you.",
+ )}
+ buttonText={t("teamWelcome.invite", "Invite people")}
+ buttonIcon="user-plus"
+ onButtonClick={() => {
+ close();
+ navigate("/settings/people");
+ }}
+ onDismiss={close}
+ />
+ );
+}
diff --git a/frontend/src/editor/proprietary/components/shared/UpgradeBanner.tsx b/frontend/src/editor/proprietary/components/shared/UpgradeBanner.tsx
index c819f76704..b987db9819 100644
--- a/frontend/src/editor/proprietary/components/shared/UpgradeBanner.tsx
+++ b/frontend/src/editor/proprietary/components/shared/UpgradeBanner.tsx
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
+import { USERS_PER_BLOCK } from "@editor/components/shared/stripeCheckout/utils/capacity";
import { useNavigate, useLocation } from "react-router-dom";
import { isAuthRoute } from "@editor-core/constants/routes";
import { useCheckout } from "@editor/contexts/CheckoutContext";
@@ -333,7 +334,8 @@ const UpgradeBanner: React.FC = () => {
title={t("upgradeBanner.title", "Upgrade to the Team plan")}
message={t(
"upgradeBanner.message",
- "Get the most out of Stirling PDF with 100 users, PDF text editing, and advanced features.",
+ "Get the most out of Stirling PDF with {{users}} users, PDF text editing, and advanced features",
+ { users: USERS_PER_BLOCK },
)}
buttonText={t("upgradeBanner.upgradeButton", "Upgrade Now")}
buttonIcon="circle-arrow-up"
diff --git a/frontend/src/editor/proprietary/components/shared/UpgradeBannerInitializer.tsx b/frontend/src/editor/proprietary/components/shared/UpgradeBannerInitializer.tsx
index 8981d3bbdb..b6b415b939 100644
--- a/frontend/src/editor/proprietary/components/shared/UpgradeBannerInitializer.tsx
+++ b/frontend/src/editor/proprietary/components/shared/UpgradeBannerInitializer.tsx
@@ -1,12 +1,18 @@
import { useEffect } from "react";
import { useBanner } from "@editor/contexts/BannerContext";
import UpgradeBanner from "@editor/components/shared/UpgradeBanner";
+import { TeamWelcomeBanner } from "@editor/components/shared/TeamWelcomeBanner";
export function UpgradeBannerInitializer() {
const { setBanner } = useBanner();
useEffect(() => {
- setBanner(<UpgradeBanner />);
+ setBanner(
+ <>
+ <TeamWelcomeBanner />
+ <UpgradeBanner />
+ </>,
+ );
return () => {
setBanner(null);
};
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/plan/StaticPlanSection.tsx b/frontend/src/editor/proprietary/components/shared/config/configSections/plan/StaticPlanSection.tsx
index 7d35699efa..f578ceda96 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/plan/StaticPlanSection.tsx
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/plan/StaticPlanSection.tsx
@@ -2,6 +2,7 @@ import React, { useState } from "react";
import { Card, Text, Stack, Collapse, Divider, Tooltip } from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { useTranslation } from "react-i18next";
+import { USERS_PER_BLOCK } from "@editor/components/shared/stripeCheckout/utils/capacity";
import { alert } from "@editor/components/toast";
import { LicenseInfo, mapLicenseToTier } from "@editor/services/licenseService";
import {
@@ -99,7 +100,9 @@ const StaticPlanSection: React.FC<StaticPlanSectionProps> = ({
popular: false,
highlights: planHighlights.SERVER_MONTHLY,
features: planFeatures.SERVER,
- maxUsers: t("plan.team.maxUsers", "100 users"),
+ maxUsers: t("plan.team.maxUsers", "{{users}} users", {
+ users: USERS_PER_BLOCK,
+ }),
},
{
id: "enterprise",
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx b/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx
index f6b6931422..872da8231a 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx
@@ -58,7 +58,7 @@ export const HostedCheckoutSuccess: Story = {
};
export const TeamPurchase: Story = {
- args: { combinedChoose: true },
+ args: { combinedChoose: true, onContactSales: () => {} },
};
export const TeamAdjustment: Story = {
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx b/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx
index a72b13b8bb..6c6d68dfd9 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx
@@ -46,6 +46,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({
combinedChoose: requestedCombinedChoose = false,
currentLimit = null,
capacityNotice,
+ onContactSales,
onSuccess,
onError,
onLicenseActivated,
@@ -237,6 +238,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({
/>
}
onContinue={() => navigation.goToStage("payment")}
+ onContactSales={onContactSales}
/>
);
@@ -260,6 +262,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({
currentLimit={currentLimit}
capacityNotice={capacityNotice}
onContinue={() => navigation.goToStage("payment")}
+ onContactSales={onContactSales}
/>
);
@@ -322,7 +325,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({
{combinedChoose
? currentLimit != null
? t("payment.adjustTeam.title", "Adjust Team plan")
- : t("payment.upgradeTeam.title", "Upgrade to Team")
+ : t("payment.upgradeTeam.title", "Get Stirling Team")
: getModalTitle(
checkoutState.state.currentStage,
planGroup.name,
@@ -331,7 +334,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({
</Text>
</Group>
}
- size={isMobile ? "100%" : combinedChoose ? 500 : 980}
+ size={isMobile ? "100%" : combinedChoose ? 860 : 980}
centered
radius="lg"
withCloseButton
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx b/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx
index 1fc915df99..420b76a9f5 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx
@@ -84,7 +84,7 @@ it("lets a custom user count be typed without replacing it with rounded blocks",
<Picker />
</MantineProvider>,
);
- await user.click(screen.getByRole("button", { name: "Other" }));
+ await user.click(screen.getByRole("button", { name: "Custom" }));
const input = screen.getByRole("textbox", { name: "Number of users" });
await user.clear(input);
expect(
@@ -121,3 +121,72 @@ it.each([
expect(!!screen.queryByText(/Existing accounts stay in place/)).toBe(shown);
},
);
+
+function CustomPicker({ onContactSales }: { onContactSales?: () => void }) {
+ const [quantity, setQuantity] = useState(1);
+ return (
+ <CapacityStage
+ selectedPlan={null}
+ serverQuantity={quantity}
+ setServerQuantity={setQuantity}
+ onContinue={() => {}}
+ onContactSales={onContactSales}
+ />
+ );
+}
+
+it("turns Custom into a focused input in place of the button", async () => {
+ const user = userEvent.setup();
+ render(
+ <MantineProvider>
+ <CustomPicker />
+ </MantineProvider>,
+ );
+ await user.click(screen.getByRole("button", { name: "Custom" }));
+ expect(screen.queryByRole("button", { name: "Custom" })).toBeNull();
+ const input = screen.getByRole("textbox", { name: "Number of users" });
+ expect(input).toHaveFocus();
+ await user.clear(input);
+ await user.type(input, "250");
+ expect(screen.getByText(/Rounds up to/)).toBeInTheDocument();
+ expect(document.querySelector(".team-capacity__covered")).toHaveTextContent(
+ "300",
+ );
+});
+
+it("asks for a number when the custom entry is empty, without pointing to Enterprise", async () => {
+ const user = userEvent.setup();
+ render(
+ <MantineProvider>
+ <CustomPicker onContactSales={() => {}} />
+ </MantineProvider>,
+ );
+ await user.click(screen.getByRole("button", { name: "Custom" }));
+ await user.clear(screen.getByRole("textbox", { name: "Number of users" }));
+ expect(screen.getByText("Enter a number of users.")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /talk to us about Enterprise/ }),
+ ).toBeNull();
+});
+
+it("points a buyer above the self-serve maximum to Enterprise", async () => {
+ const user = userEvent.setup();
+ const onContactSales = vi.fn();
+ render(
+ <MantineProvider>
+ <CustomPicker onContactSales={onContactSales} />
+ </MantineProvider>,
+ );
+ await user.click(screen.getByRole("button", { name: "Custom" }));
+ const input = screen.getByRole("textbox", { name: "Number of users" });
+ await user.clear(input);
+ await user.type(input, "900");
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ expect(
+ screen.getByRole("button", { name: "Continue to payment" }),
+ ).toBeDisabled();
+ await user.click(
+ screen.getByRole("button", { name: /talk to us about Enterprise/ }),
+ );
+ expect(onContactSales).toHaveBeenCalledTimes(1);
+});
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx b/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx
index 50453ee7bb..098058d3dc 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx
@@ -1,22 +1,15 @@
-import React, { useState } from "react";
-import {
- Stack,
- Text,
- Group,
- Divider,
- Alert,
- NumberInput,
- Box,
-} from "@mantine/core";
+import React, { useId, useRef, useState } from "react";
+import { Stack, Text, Group, Divider, Alert, Box } from "@mantine/core";
import "@editor/components/shared/stripeCheckout/team-checkout.css";
import { Button } from "@editor/ui/Button";
+import { Icon } from "@editor/ui/Icon";
import { useTranslation } from "react-i18next";
import { PlanTier } from "@editor/services/licenseService";
import { formatPrice } from "@editor/components/shared/stripeCheckout/utils/pricingUtils";
import {
- USERS_PER_BLOCK,
+ PRESET_BLOCKS,
SELF_SERVE_MAX_BLOCKS,
- USER_PRESETS,
+ USERS_PER_BLOCK,
usersForBlocks,
blocksForUsers,
shouldOfferEnterprise,
@@ -38,25 +31,20 @@ interface CapacityStageProps {
onContactSales?: () => void;
}
-function showCustomValueInvalid(
- value: number | string,
- minimum: number,
- maximum: number,
-) {
- return (
- value === "" ||
- !Number.isSafeInteger(Number(value)) ||
- Number(value) < minimum ||
- Number(value) > maximum
- );
+type CustomEntry = "ok" | "empty" | "overLimit";
+
+function checkCustomEntry(value: string, maximum: number): CustomEntry {
+ const n = Number(value);
+ if (value === "" || !Number.isSafeInteger(n) || n <= 0) return "empty";
+ return n > maximum ? "overLimit" : "ok";
}
/**
* Choose how many users the Team plan should cover.
*
* The buyer picks users; the plan is priced per block of {@link USERS_PER_BLOCK}. Presets cover the
- * common sizes and "Other" opens a free entry that rounds up to the next whole block, because a
- * part-block cannot be bought.
+ * common sizes and "Custom" turns into a free entry that rounds up to the next whole block, because
+ * a part-block cannot be bought. Above the self-serve maximum the hint points to Enterprise.
*/
export const CapacityStage: React.FC<CapacityStageProps> = ({
selectedPlan,
@@ -75,21 +63,26 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({
const blockPrice = selectedPlan?.price || 0;
const isYearly = selectedPlan?.period?.includes("year") ?? false;
const covered = usersForBlocks(serverQuantity);
- const total = blockPrice * serverQuantity;
- const [draftUsers, setDraftUsers] = useState<number | string>(covered);
+ const [draftUsers, setDraftUsers] = useState(String(covered));
- const minBlocks = currentLimit == null ? blocksForUsers(currentUsers) : 1;
- const reducing = currentLimit != null && covered < currentLimit;
+ const adjusting = currentLimit != null;
+ const minBlocks = adjusting ? 1 : blocksForUsers(currentUsers);
+ const reducing = adjusting && covered < currentLimit;
const minUsers = usersForBlocks(minBlocks);
const maxUsers = usersForBlocks(SELF_SERVE_MAX_BLOCKS);
const belowMinimumCapacity = serverQuantity < minBlocks;
const offerEnterprise = shouldOfferEnterprise(serverQuantity);
- const invalidDraft = showCustomValueInvalid(draftUsers, 1, maxUsers);
- const presets = USER_PRESETS.filter((users) => users <= maxUsers);
+ const presets = PRESET_BLOCKS.filter(
+ (blocks) => blocks <= SELF_SERVE_MAX_BLOCKS,
+ ).map((blocks) => usersForBlocks(blocks));
const [showCustom, setShowCustom] = useState(
- () => !presets.includes(usersForBlocks(serverQuantity)),
+ () => !presets.includes(covered),
);
+ const customEntry = checkCustomEntry(draftUsers, maxUsers);
+ // Focus only when the buyer picks Custom, not whenever the stage remounts in custom mode.
+ const focusCustom = useRef(false);
+ const hintId = useId();
const period = isYearly
? t("payment.capacityStage.perYear", "/yr")
@@ -99,138 +92,285 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({
setServerQuantity(blocksForUsers(users));
return (
- <Stack gap="sm" className="team-capacity">
- {capacityNotice && capacityNotice.users > capacityNotice.limit && (
- <Box className="team-capacity__notice">
- <Text size="sm" fw={500}>
- {t(
- "payment.capacityStage.overCapacityTitle",
- "Your server has more users than your plan covers",
+ <div className="team-capacity">
+ <Stack gap="md" className="team-capacity__choices">
+ {capacityNotice && capacityNotice.users > capacityNotice.limit && (
+ <Box className="team-capacity__notice">
+ <Text size="sm" fw={500}>
+ {t(
+ "payment.capacityStage.overCapacityTitle",
+ "Your server has more users than your plan covers",
+ )}
+ </Text>
+ <Text size="sm" mt={4}>
+ {t(
+ "payment.capacityStage.overCapacityBody",
+ "{{users}} users are on this server; your current allowance is {{limit}}. Choose a Team plan below to cover everyone.",
+ { users: capacityNotice.users, limit: capacityNotice.limit },
+ )}
+ </Text>
+ <Text size="xs" c="dimmed" mt={6}>
+ {t(
+ "payment.capacityStage.overCapacityConsequence",
+ "Existing accounts stay in place. Adding or inviting users is blocked until you add capacity or free up seats.",
+ )}
+ </Text>
+ </Box>
+ )}
+ <Text size="sm" c="dimmed">
+ {adjusting
+ ? t(
+ "payment.capacityStage.subheadingAdd",
+ "Your plan covers {{current}} users today. Choose the new total.",
+ {
+ current: currentLimit,
+ },
+ )
+ : t(
+ "payment.capacityStage.subheading",
+ "Covers everyone you invite, in blocks of {{users}} users.",
+ {
+ users: USERS_PER_BLOCK,
+ },
+ )}
+ </Text>
+
+ {periodPicker && (
+ <Stack gap="xs">
+ <Text size="sm" fw={600}>
+ {t("payment.capacityStage.billingLabel", "Billing")}
+ </Text>
+ {periodPicker}
+ </Stack>
+ )}
+
+ <Stack gap="xs">
+ <Text size="sm" fw={600}>
+ {t("payment.capacityStage.usersLabel", "Users")}
+ </Text>
+ <div
+ className="team-capacity__pills"
+ style={{
+ gridTemplateColumns: `repeat(${presets.length}, minmax(0, 1fr)) minmax(0, 1.4fr)`,
+ }}
+ >
+ {presets.map((users) => (
+ <Button
+ key={users}
+ variant="secondary"
+ px="xs"
+ className="team-capacity__pill"
+ aria-pressed={!showCustom && covered === users}
+ disabled={users < minUsers}
+ onClick={() => {
+ setShowCustom(false);
+ setDraftUsers(String(users));
+ selectUsers(users);
+ }}
+ >
+ {users}
+ </Button>
+ ))}
+ {showCustom ? (
+ <span className="team-capacity__pill team-capacity__pill--input">
+ <input
+ ref={(el) => {
+ if (el && focusCustom.current) {
+ focusCustom.current = false;
+ el.focus();
+ }
+ }}
+ aria-label={t(
+ "payment.capacityStage.customLabel",
+ "Number of users",
+ )}
+ aria-invalid={customEntry !== "ok"}
+ aria-describedby={hintId}
+ inputMode="numeric"
+ value={draftUsers}
+ onChange={(event) => {
+ const value = event.target.value.replace(/\D/g, "");
+ setDraftUsers(value);
+ if (checkCustomEntry(value, maxUsers) === "ok")
+ selectUsers(Number(value));
+ }}
+ />
+ </span>
+ ) : (
+ <Button
+ variant="secondary"
+ px="xs"
+ className="team-capacity__pill"
+ aria-pressed={false}
+ onClick={() => {
+ focusCustom.current = true;
+ setDraftUsers(String(covered));
+ setShowCustom(true);
+ }}
+ >
+ {t("payment.capacityStage.custom", "Custom")}
+ </Button>
+ )}
+ </div>
+ <Text
+ id={hintId}
+ aria-live="polite"
+ size="xs"
+ c="dimmed"
+ className="team-capacity__hint"
+ >
+ {showCustom && (
+ <CapacityHint
+ entry={customEntry}
+ draftUsers={draftUsers}
+ covered={covered}
+ maxUsers={maxUsers}
+ onContactSales={onContactSales}
+ />
)}
</Text>
- <Text size="sm" mt={4}>
+ </Stack>
+
+ {belowMinimumCapacity && (
+ <Alert color="yellow" variant="light">
{t(
- "payment.capacityStage.overCapacityBody",
- "{{users}} users are on this server; your current allowance is {{limit}}. Choose a Team plan below to cover everyone.",
- { users: capacityNotice.users, limit: capacityNotice.limit },
+ "payment.capacityStage.minimumForCurrentUsers",
+ "You have {{users}} users, so the plan must cover at least {{minimum}}.",
+ { users: currentUsers, minimum: minUsers },
)}
- </Text>
- <Text size="xs" c="dimmed" mt={6}>
+ </Alert>
+ )}
+
+ {reducing && (
+ <Text size="sm" c="dimmed">
{t(
- "payment.capacityStage.overCapacityConsequence",
- "Existing accounts stay in place. Adding or inviting users is blocked until you add capacity or free up seats.",
+ "payment.capacityStage.reductionNote",
+ "The lower capacity starts at your next renewal. Until then, you can use your current allowance. Existing users stay; new users are blocked if you are over capacity when the change takes effect.",
)}
</Text>
- </Box>
- )}
- <Text size="sm" c="dimmed">
- {currentLimit != null
- ? t(
- "payment.capacityStage.subheadingAdd",
- "Your plan covers {{current}} users today. Choose the new total.",
- {
- current: currentLimit,
- },
- )
- : t(
- "payment.capacityStage.subheading",
- "Covers everyone you invite, in blocks of {{users}} users.",
- {
- users: USERS_PER_BLOCK,
- },
- )}
- </Text>
+ )}
+ </Stack>
- <Box className="team-capacity__selection">
- <Group gap="xs" wrap="wrap" align="center">
- <Text size="sm" fw={500}>
- {t("payment.capacityStage.usersLabel", "Users")}
- </Text>
- {presets.map((users) => (
- <Button
- key={users}
- variant="secondary"
- className="team-capacity__pill"
- aria-pressed={!showCustom && covered === users}
- disabled={users < minUsers}
- onClick={() => {
- setShowCustom(false);
- setDraftUsers(users);
- selectUsers(users);
- }}
- >
- {users}
- </Button>
- ))}
- <Button
- variant="secondary"
- className="team-capacity__pill"
- aria-pressed={showCustom}
- onClick={() => {
- setDraftUsers(covered);
- setShowCustom(true);
- }}
- >
- {t("payment.capacityStage.other", "Other")}
- </Button>
- </Group>
+ <CapacitySummary
+ blocks={serverQuantity}
+ blockPrice={blockPrice}
+ currency={currency}
+ period={period}
+ adjusting={adjusting}
+ continueDisabled={
+ belowMinimumCapacity || (showCustom && customEntry !== "ok")
+ }
+ onContinue={onContinue}
+ onEnterpriseQuote={offerEnterprise ? onContactSales : undefined}
+ />
+ </div>
+ );
+};
+
+interface CapacityHintProps {
+ entry: CustomEntry;
+ draftUsers: string;
+ covered: number;
+ maxUsers: number;
+ onContactSales?: () => void;
+}
+
+/** What a custom entry will buy, or why it cannot be bought here. */
+function CapacityHint({
+ entry,
+ draftUsers,
+ covered,
+ maxUsers,
+ onContactSales,
+}: CapacityHintProps) {
+ const { t } = useTranslation();
- {showCustom && (
- <Group gap="xs" mt="xs">
- <NumberInput
- aria-label={t(
- "payment.capacityStage.customLabel",
- "Number of users",
+ if (entry === "empty") {
+ return t("payment.capacityStage.enterUsers", "Enter a number of users.");
+ }
+ if (entry === "overLimit") {
+ return (
+ <>
+ {t(
+ "payment.capacityStage.selfServeLimit",
+ "Up to {{users}} users here.",
+ {
+ users: maxUsers,
+ },
+ )}
+ {onContactSales && (
+ <>
+ {" "}
+ <button
+ type="button"
+ className="team-capacity__link"
+ onClick={onContactSales}
+ >
+ {t(
+ "payment.capacityStage.talkToEnterprise",
+ "For more, talk to us about Enterprise.",
)}
- value={draftUsers}
- onChange={(value) => {
- setDraftUsers(value);
- if (
- value !== "" &&
- Number.isSafeInteger(Number(value)) &&
- Number(value) > 0
- )
- selectUsers(Number(value));
- }}
- min={minUsers}
- max={maxUsers}
- clampBehavior="none"
- hideControls
- allowDecimal={false}
- allowNegative={false}
- style={{ width: 80 }}
- />
- <Text size="xs" c="dimmed">
- {t("payment.capacityStage.roundsTo", "rounds to {{users}}", {
- users: covered,
- })}
- </Text>
- </Group>
+ </button>
+ </>
)}
- </Box>
+ </>
+ );
+ }
+ if (Number(draftUsers) !== covered) {
+ return t(
+ "payment.capacityStage.roundsUp",
+ "Rounds up to {{users}} users.",
+ {
+ users: covered,
+ },
+ );
+ }
+ return null;
+}
- {belowMinimumCapacity && (
- <Alert color="yellow" variant="light">
- {t(
- "payment.capacityStage.minimumForCurrentUsers",
- "You have {{users}} users, so the plan must cover at least {{minimum}}.",
- { users: currentUsers, minimum: minUsers },
- )}
- </Alert>
- )}
+interface CapacitySummaryProps {
+ blocks: number;
+ blockPrice: number;
+ currency: string;
+ period: string;
+ /** Changing an existing plan rather than buying a first one. */
+ adjusting: boolean;
+ continueDisabled: boolean;
+ onContinue: () => void;
+ onEnterpriseQuote?: () => void;
+}
- {periodPicker}
- {reducing && (
+/** The order as it stands, and the way on to payment. */
+function CapacitySummary({
+ blocks,
+ blockPrice,
+ currency,
+ period,
+ adjusting,
+ continueDisabled,
+ onContinue,
+ onEnterpriseQuote,
+}: CapacitySummaryProps) {
+ const { t } = useTranslation();
+ const covered = usersForBlocks(blocks);
+ const total = blockPrice * blocks;
+
+ return (
+ <Stack gap="md" className="team-capacity__summary">
+ <Group gap="xs" wrap="nowrap">
+ <Icon name="users" />
+ <Text fw={600}>
+ {t("payment.capacityStage.planName", "Stirling Team")}
+ </Text>
+ </Group>
+ <div>
+ <Text className="team-capacity__covered">{covered}</Text>
<Text size="sm" c="dimmed">
- {t(
- "payment.capacityStage.reductionNote",
- "The lower capacity starts at your next renewal. Until then, you can use your current allowance. Existing users stay; new users are blocked if you are over capacity when the change takes effect.",
- )}
+ {t("payment.capacityStage.usersCovered", "users covered")}
</Text>
- )}
-
- <Stack gap="sm" className="team-capacity__receipt">
- <Group justify="space-between">
+ </div>
+ <Stack gap="sm">
+ <Group justify="space-between" wrap="nowrap">
<Text size="sm" c="dimmed">
{t(
"payment.capacityStage.lineItem",
@@ -251,17 +391,36 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({
<Divider />
<Group justify="space-between" align="baseline">
<Text fw={600}>
- {currentLimit != null
+ {adjusting
? t("payment.capacityStage.newPlanTotal", "New plan total")
: t("payment.capacityStage.estimatedTotal", "Estimated total")}
</Text>
- <Text size="md" fw={600}>
+ <Text size="xl" fw={700}>
{formatPrice(total, currency)}
</Text>
</Group>
</Stack>
- <Text size="xs" c="dimmed">
- {currentLimit != null
+ <div className="team-capacity__spacer" />
+ <Button
+ fullWidth
+ size="lg"
+ onClick={onContinue}
+ disabled={continueDisabled}
+ >
+ {adjusting
+ ? t("payment.capacityStage.reviewChange", "Review change in Stripe")
+ : t("payment.capacityStage.continue", "Continue to payment")}
+ </Button>
+ {onEnterpriseQuote && (
+ <Button variant="secondary" onClick={onEnterpriseQuote} fullWidth>
+ {t(
+ "payment.capacityStage.enterpriseQuote",
+ "Get an enterprise quote",
+ )}
+ </Button>
+ )}
+ <Text size="xs" c="dimmed" ta="center">
+ {adjusting
? t(
"payment.capacityStage.adjustmentNote",
"Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available.",
@@ -273,34 +432,12 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({
total: formatPrice(total, currency, 0),
period,
},
- )}
- </Text>
-
- <Text size="xs" c="dimmed">
+ )}{" "}
{t(
"payment.capacityStage.currencyAtCheckout",
"Stripe confirms the final amount and payment currency at checkout.",
)}
</Text>
- <Group justify="flex-end" mt="sm">
- <Button
- onClick={onContinue}
- disabled={belowMinimumCapacity || (showCustom && invalidDraft)}
- >
- {currentLimit != null
- ? t("payment.capacityStage.reviewChange", "Review change in Stripe")
- : t("payment.capacityStage.continue", "Continue to payment")}
- </Button>
-
- {offerEnterprise && onContactSales && (
- <Button variant="secondary" onClick={onContactSales} fullWidth>
- {t(
- "payment.capacityStage.enterpriseQuote",
- "Get an enterprise quote",
- )}
- </Button>
- )}
- </Group>
</Stack>
);
-};
+}
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx b/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx
index 0a527ebf6e..ac7edbb2a2 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx
@@ -12,6 +12,8 @@ import {
calculateTotalWithSeats,
} from "@editor/components/shared/stripeCheckout/utils/pricingUtils";
import { getClickablePaperStyle } from "@editor/components/shared/stripeCheckout/utils/cardStyles";
+import { USERS_PER_BLOCK } from "@editor/components/shared/stripeCheckout/utils/capacity";
+import "@editor/components/shared/stripeCheckout/team-checkout.css";
interface PlanSelectionStageProps {
planGroup: PlanTierGroup;
@@ -42,7 +44,7 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({
if (compact) {
return (
<div
- role="group"
+ role="radiogroup"
aria-label={t("payment.billingPeriod", "Billing period")}
style={{
display: "grid",
@@ -58,36 +60,45 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({
<button
key={period}
type="button"
- aria-pressed={selected}
+ role="radio"
+ aria-checked={selected}
onClick={() => onSelectPlan(period)}
style={{
textAlign: "left",
- padding: "0.75rem",
+ padding: "0.875rem 1rem",
borderRadius: "0.75rem",
cursor: "pointer",
color: "var(--c-text)",
- border: `1px solid ${selected ? "var(--c-primary)" : "var(--c-border)"}`,
+ border: `${selected ? 2 : 1}px solid ${selected ? "var(--c-primary)" : "var(--c-border)"}`,
background: selected
? "var(--c-primary-subtle)"
: "transparent",
}}
>
- <Text component="span" display="block" fw={600}>
+ <Text
+ component="span"
+ fw={600}
+ style={{ display: "flex", alignItems: "center", gap: 8 }}
+ >
{period === "monthly"
? t("payment.monthly", "Monthly")
- : t("payment.yearly", "Yearly")}
+ : t("payment.annually", "Annually")}
+ {period === "yearly" && savings && (
+ <span className="team-period__saving">
+ {t("payment.planStage.savePercent", "Save {{percent}}%", {
+ percent: savings.percent,
+ })}
+ </span>
+ )}
</Text>
<Text component="span" display="block" size="sm" c="dimmed">
{formatPrice(plan.price, plan.currency, 0)}
{period === "monthly"
? t("payment.capacityStage.perMonth", "/mo")
- : t("payment.capacityStage.perYear", "/yr")}
- {" · "}
- {period === "yearly" && savings
- ? t("payment.planStage.savePercent", "Save {{percent}}%", {
- percent: savings.percent,
- })
- : t("payment.perUserBlock", "per 100 users")}
+ : t("payment.capacityStage.perYear", "/yr")}{" "}
+ {t("payment.perUserBlock", "per {{users}} users", {
+ users: USERS_PER_BLOCK,
+ })}
</Text>
</button>
);
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/team-checkout.css b/frontend/src/editor/proprietary/components/shared/stripeCheckout/team-checkout.css
index d633fb3e34..29292a37d1 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/team-checkout.css
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/team-checkout.css
@@ -1,22 +1,85 @@
.team-capacity {
- padding: 0;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(17.5rem, 1fr));
+ gap: 1.5rem;
+ padding-top: 0.5rem;
}
-.team-capacity__selection,
-.team-capacity__receipt {
- border: 1px solid var(--c-border);
- border-radius: 0.75rem;
- padding: 0.875rem;
+.team-capacity__choices,
+.team-capacity__summary {
+ min-width: 0;
+}
+.team-capacity__summary {
+ background: var(--c-surface-sunken);
+ border-radius: 1rem;
+ padding: 1.5rem;
+}
+.team-capacity__covered {
+ font-size: 2.5rem;
+ font-weight: 700;
+ line-height: 1.1;
+ font-variant-numeric: tabular-nums;
+}
+.team-capacity__spacer {
+ flex: 1;
+}
+
+.team-capacity__pills {
+ display: grid;
+ gap: 0.5rem;
}
.team-capacity__pill {
border-radius: 999px;
font-weight: 500;
- min-width: 3rem;
+ min-width: 0;
}
.team-capacity__pill[aria-pressed="true"] {
border-color: var(--c-primary);
color: var(--c-accent-text);
background: var(--c-primary-subtle);
}
+.team-capacity__pill--input {
+ display: flex;
+ align-items: center;
+ border: 2px solid var(--c-primary);
+ background: var(--c-primary-subtle);
+}
+.team-capacity__pill--input input {
+ width: 100%;
+ min-width: 0;
+ border: 0;
+ outline: none;
+ background: transparent;
+ color: var(--c-text);
+ font: inherit;
+ font-weight: 600;
+ text-align: center;
+}
+.team-capacity__hint {
+ min-height: 1.25em;
+}
+.team-capacity__link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--c-accent-text);
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+}
+.team-capacity__link:hover {
+ text-decoration: underline;
+}
+
+.team-period__saving {
+ padding: 1px 8px;
+ border-radius: 999px;
+ background: var(--c-success-subtle);
+ /* Green text on the green tint is below AA at this size; the tint carries the colour. */
+ color: var(--c-text);
+ font-size: 0.6875rem;
+ font-weight: 700;
+ white-space: nowrap;
+}
.team-capacity__notice {
padding: 14px 16px;
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/types/checkout.ts b/frontend/src/editor/proprietary/components/shared/stripeCheckout/types/checkout.ts
index b0c0f9cba6..dac7da8418 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/types/checkout.ts
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/types/checkout.ts
@@ -11,6 +11,8 @@ export interface StripeCheckoutProps {
currentLimit?: number | null;
/** Present only for a self-hosted server above its actual allowance. */
capacityNotice?: { users: number; limit: number };
+ /** Where a buyer above the self-serve maximum is sent; without it the capacity step offers no way on. */
+ onContactSales?: () => void;
opened: boolean;
onClose: () => void;
planGroup: PlanTierGroup;
diff --git a/frontend/src/editor/proprietary/components/shared/stripeCheckout/utils/capacity.ts b/frontend/src/editor/proprietary/components/shared/stripeCheckout/utils/capacity.ts
index eba9897f16..d70f6fb753 100644
--- a/frontend/src/editor/proprietary/components/shared/stripeCheckout/utils/capacity.ts
+++ b/frontend/src/editor/proprietary/components/shared/stripeCheckout/utils/capacity.ts
@@ -20,8 +20,8 @@ export const SELF_SERVE_MAX_BLOCKS = 5;
/** Capacity at which an enterprise quote is also worth offering. */
export const ENTERPRISE_ADVISORY_USERS = 1000;
-/** The user counts offered as one-click presets, before "Other". */
-export const USER_PRESETS = [100, 200, 300, 400];
+/** The block counts offered as one-click presets, before "Custom". */
+export const PRESET_BLOCKS = [1, 2, 3, 4];
/** Users covered by a given number of blocks. */
export function usersForBlocks(blocks: number): number {
diff --git a/frontend/src/editor/proprietary/constants/planConstants.test.ts b/frontend/src/editor/proprietary/constants/planConstants.test.ts
index 6589c8ffec..dd5586fb8b 100644
--- a/frontend/src/editor/proprietary/constants/planConstants.test.ts
+++ b/frontend/src/editor/proprietary/constants/planConstants.test.ts
@@ -6,7 +6,10 @@ import {
} from "@editor/constants/planConstants";
vi.mock("react-i18next", () => ({
- useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),
+ useTranslation: () => ({
+ t: (_key: string, fallback: string, values?: Record<string, unknown>) =>
+ fallback.replace(/\{\{(\w+)\}\}/g, (_, name) => String(values?.[name])),
+ }),
}));
describe("self-hosted authentication entitlements", () => {
diff --git a/frontend/src/editor/proprietary/constants/planConstants.ts b/frontend/src/editor/proprietary/constants/planConstants.ts
index 0efc58610b..3c146d3ac6 100644
--- a/frontend/src/editor/proprietary/constants/planConstants.ts
+++ b/frontend/src/editor/proprietary/constants/planConstants.ts
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import type { PlanFeature } from "@editor/types/license";
+import { USERS_PER_BLOCK } from "@editor/components/shared/stripeCheckout/utils/capacity";
/**
* Shared plan feature definitions for Stirling PDF Self-Hosted
@@ -52,7 +53,8 @@ export const usePlanFeatures = (): PlanFeaturesMap => {
const upToFiveUsers = t("plan.features.upToFiveUsers", "Up to 5 users");
const usersIncluded = t(
"plan.features.usersIncluded",
- "100 users included",
+ "{{users}} users included",
+ { users: USERS_PER_BLOCK },
);
const googleDriveIntegration = t(
"plan.features.googleDriveIntegration",
@@ -155,7 +157,8 @@ export const usePlanHighlights = (): PlanHighlightsMap => {
);
const usersIncluded = t(
"plan.highlights.usersIncluded",
- "100 users included",
+ "{{users}} users included",
+ { users: USERS_PER_BLOCK },
);
const advancedIntegrations = t(
"plan.highlights.advancedIntegrations",
diff --git a/frontend/src/editor/proprietary/contexts/CheckoutContext.test.tsx b/frontend/src/editor/proprietary/contexts/CheckoutContext.test.tsx
index 70d126b274..5881c75675 100644
--- a/frontend/src/editor/proprietary/contexts/CheckoutContext.test.tsx
+++ b/frontend/src/editor/proprietary/contexts/CheckoutContext.test.tsx
@@ -1,4 +1,10 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
import {
CheckoutProvider,
@@ -50,18 +56,42 @@ vi.mock("@editor/services/licenseService", () => ({
mapLicenseToTier: () => "free",
}));
vi.mock("@editor/components/shared/stripeCheckout", () => ({
- StripeCheckout: () => <div role="dialog">Checkout</div>,
+ StripeCheckout: ({
+ onSuccess,
+ onClose,
+ onContactSales,
+ }: {
+ onSuccess: (sessionId: string) => void;
+ onClose: () => void;
+ onContactSales?: () => void;
+ }) => (
+ <div role="dialog">
+ Checkout
+ <button onClick={() => onSuccess("cs_test")}>Pay</button>
+ <button onClick={onClose}>Close</button>
+ <button onClick={onContactSales}>Contact sales</button>
+ </div>
+ ),
}));
-function Buyer({ linked = false }: { linked?: boolean }) {
+function Buyer({
+ linked = false,
+ onClose,
+ onContactSales,
+}: {
+ linked?: boolean;
+ onClose?: (paid: boolean) => void;
+ onContactSales?: () => void;
+}) {
const checkout = useCheckout();
return (
<button
onClick={() =>
- void checkout.openCheckout(
- "server",
- linked ? { resolveCurrency: mocks.pricing } : {},
- )
+ void checkout.openCheckout("server", {
+ ...(linked ? { resolveCurrency: mocks.pricing } : {}),
+ onClose,
+ onContactSales,
+ })
}
>
Add capacity
@@ -136,3 +166,50 @@ it("resolves a linked customer's currency before fetching Team prices", async ()
"server",
);
});
+
+it("tells the caller on close whether that checkout was paid for", async () => {
+ mocks.getPlans.mockResolvedValue({ plans: [{ id: "server-monthly" }] });
+ const onClose = vi.fn();
+ render(
+ <CheckoutProvider>
+ <Buyer onClose={onClose} />
+ </CheckoutProvider>,
+ );
+ const open = async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));
+ await screen.findByRole("dialog");
+ };
+ // Closing refetches plans; let that settle before the next step.
+ const close = async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ await act(async () => {});
+ };
+
+ await open();
+ fireEvent.click(screen.getByRole("button", { name: "Pay" }));
+ await close();
+ expect(onClose).toHaveBeenLastCalledWith(true);
+
+ // A later checkout starts unpaid.
+ await open();
+ await close();
+ expect(onClose).toHaveBeenLastCalledWith(false);
+});
+
+it("closes the checkout before handing a buyer to Enterprise", async () => {
+ mocks.getPlans.mockResolvedValue({ plans: [{ id: "server-monthly" }] });
+ const onContactSales = vi.fn();
+ render(
+ <CheckoutProvider>
+ <Buyer onContactSales={onContactSales} />
+ </CheckoutProvider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));
+ await screen.findByRole("dialog");
+
+ fireEvent.click(screen.getByRole("button", { name: "Contact sales" }));
+ await act(async () => {});
+
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(onContactSales).toHaveBeenCalledTimes(1);
+});
diff --git a/frontend/src/editor/proprietary/contexts/CheckoutContext.tsx b/frontend/src/editor/proprietary/contexts/CheckoutContext.tsx
index 0c5cdbcf2a..1c51bfc559 100644
--- a/frontend/src/editor/proprietary/contexts/CheckoutContext.tsx
+++ b/frontend/src/editor/proprietary/contexts/CheckoutContext.tsx
@@ -54,6 +54,10 @@ export interface CheckoutOptions {
currentLimit?: number | null;
/** Present only for a self-hosted server above its actual allowance. */
capacityNotice?: { users: number; limit: number };
+ /** Where a buyer above the self-serve maximum is sent. */
+ onContactSales?: () => void;
+ /** Runs when the checkout is dismissed, so a caller can move on from it once the buyer has paid. */
+ onClose?: (paid: boolean) => void;
}
interface CheckoutContextValue {
@@ -101,6 +105,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({
const [plans, setPlans] = useState<PlanTier[]>([]);
const [plansLoaded, setPlansLoaded] = useState(false);
const openingCheckout = useRef(false);
+ const paid = useRef(false);
// Lazy fetch plans only when needed
const fetchPlansIfNeeded = useCallback(
@@ -428,6 +433,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({
}
// Store options for callbacks
+ paid.current = false;
setCurrentOptions(options);
setMinimumSeats(calculatedMinSeats);
setSelectedPlanGroup(planGroup);
@@ -447,6 +453,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({
);
const closeCheckout = useCallback(() => {
+ currentOptions.onClose?.(paid.current);
setIsOpen(false);
setSelectedPlanGroup(null);
setCurrentOptions({});
@@ -455,11 +462,12 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({
// Refetch plans and license after modal closes to update subscription display
refetchPlans();
refetchLicense();
- }, [refetchPlans, refetchLicense]);
+ }, [currentOptions, refetchPlans, refetchLicense]);
const handlePaymentSuccess = useCallback(
(sessionId: string) => {
console.log("Payment successful, session:", sessionId);
+ paid.current = true;
currentOptions.onSuccess?.(sessionId);
// Don't close modal - let user view license key and close manually
},
@@ -509,6 +517,15 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({
combinedChoose={currentOptions.combinedChoose}
currentLimit={currentOptions.currentLimit ?? null}
capacityNotice={currentOptions.capacityNotice}
+ onContactSales={
+ currentOptions.onContactSales &&
+ (() => {
+ // Enterprise opens its own flow; leaving the checkout on top would hide it.
+ const contactSales = currentOptions.onContactSales;
+ closeCheckout();
+ contactSales?.();
+ })
+ }
onSuccess={handlePaymentSuccess}
onError={handlePaymentError}
onLicenseActivated={handleLicenseActivated}
diff --git a/frontend/src/editor/saas/App.tsx b/frontend/src/editor/saas/App.tsx
index dbe9c89c9f..ea5115015b 100644
--- a/frontend/src/editor/saas/App.tsx
+++ b/frontend/src/editor/saas/App.tsx
@@ -14,6 +14,8 @@ import Landing from "@editor/routes/Landing";
import Login from "@editor/routes/Login";
import { ResumePendingConnect } from "@editor/routes/ResumePendingConnect";
import Signup from "@editor/routes/Signup";
+import { TeamRedirect } from "@editor/routes/TeamRedirect";
+import { TEAM_PATH } from "@editor/routes/teamPath";
import AuthCallback from "@editor/routes/AuthCallback";
import ResetPassword from "@editor/routes/ResetPassword";
import OAuthConsent from "@editor/routes/OAuthConsent";
@@ -72,6 +74,7 @@ function MainRoutes() {
<Route element={<NoAppChrome />}>
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Signup />} />
+ <Route path={TEAM_PATH} element={<TeamRedirect />} />
<Route path="/auth/callback" element={<AuthCallback />} />
<Route path="/auth/reset" element={<ResetPassword />} />
<Route path="/oauth/consent" element={<OAuthConsent />} />
diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx
index 7c11d8be79..403bacbc7f 100644
--- a/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx
+++ b/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx
@@ -1,7 +1,7 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { MantineProvider } from "@mantine/core";
import type { ReactNode } from "react";
-import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { MemoryRouter, Navigate, Route, Routes } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { RunLocationGate } from "@editor/components/runLocation/RunLocationGate";
import { startDownload } from "@editor/components/runLocation/startDownload";
@@ -74,6 +74,20 @@ describe("RunLocationGate", () => {
expect(screen.getByText("The app")).toBeInTheDocument();
});
+ it("lets the Team link through without recording a choice", () => {
+ renderAt("/team");
+ expect(screen.getByText("The app")).toBeInTheDocument();
+ expect(window.localStorage.getItem(SEEN_KEY)).toBeNull();
+ });
+
+ it.each(["/login?next=%2Fteam%3Futm_campaign%3Dnov", "/signup?next=%2Fteam"])(
+ "lets sign-in through on the way back to the Team link: %s",
+ (path) => {
+ renderAt(path);
+ expect(screen.getByText("The app")).toBeInTheDocument();
+ },
+ );
+
it.each(["/enterprise", "/procurement"])(
"lets the Enterprise landing link %s through without recording a choice",
(path) => {
@@ -88,6 +102,28 @@ describe("RunLocationGate", () => {
expect(screen.getByText("The app")).toBeInTheDocument();
});
+ it.each(["/team", "/login?next=%2Fteam"])(
+ "stays out of the way once %s hands the visitor on into the app",
+ (path) => {
+ render(
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route element={<RunLocationGate />}>
+ {/* Each step of the Team link moves on, as TeamRedirect and sign-in do. */}
+ <Route path="/login" element={<Navigate to="/team" replace />} />
+ <Route
+ path="/team"
+ element={<Navigate to="/settings/billing" replace />}
+ />
+ <Route path="*" element={<div>The app</div>} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+ expect(screen.getByText("The app")).toBeInTheDocument();
+ },
+ );
+
it("still asks on sign-in headed anywhere else", () => {
renderAt("/login");
expect(screen.queryByText("The app")).not.toBeInTheDocument();
diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx
index e603072784..b95269ae2a 100644
--- a/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx
+++ b/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx
@@ -4,40 +4,51 @@ import { normalizePath } from "@editor/utils/pathUtils";
import { PublicRouteProviders } from "@editor/components/PublicRouteProviders";
import { RunLocationChooser } from "@editor/components/runLocation/RunLocationChooser";
import { hasChosenRunLocation } from "@editor/components/runLocation/runLocationChosen";
+import { TEAM_PATH } from "@editor/routes/teamPath";
+import { nextPathOf } from "@editor/routes/authShared/nextPath";
import {
ENTERPRISE_PATH,
LEGACY_ENTERPRISE_PATH,
} from "@editor/portal/components/procurement/enterprisePath";
+// Landing links from campaigns and sales replies. Team is bought for a Stirling
+// account, so it settles where Stirling runs on its own; the Enterprise page
+// asks where Stirling will be deployed itself.
+const LANDING_PATHS = [TEAM_PATH, ENTERPRISE_PATH, LEGACY_ENTERPRISE_PATH];
+
// Links that finish a flow already in progress (an emailed sign-in, an OAuth
// redirect, a shared file). Interrupting them with the chooser in a fresh
// browser would strand the visitor mid-flow, or lose the token in the URL.
-// The Enterprise page is a landing link from campaigns and sales replies, and
-// asks where Stirling will be deployed itself.
const FLOW_PATHS = [
"/auth/callback",
"/auth/reset",
"/oauth/consent",
"/link",
"/account-link/callback",
- ENTERPRISE_PATH,
- LEGACY_ENTERPRISE_PATH,
+ ...LANDING_PATHS,
];
-// Signing in from the Enterprise page detours through these, naming it as `next`.
+// Signing in from a landing link detours through these, naming it as `next`.
const AUTH_PATHS = ["/login", "/signup"];
-export function bypassesRunLocation(pathname: string, search = ""): boolean {
+/** On a landing link, or signing in on the way to one. */
+function isLanding(pathname: string, search: string): boolean {
const path = normalizePath(pathname);
- if (FLOW_PATHS.includes(path) || path.startsWith("/share/")) return true;
- const next = new URLSearchParams(search).get("next");
- const nextPath = next?.split(/[?#]/)[0];
+ if (LANDING_PATHS.includes(path)) return true;
+ const nextPath = nextPathOf(new URLSearchParams(search).get("next"));
return (
AUTH_PATHS.includes(path) &&
- (nextPath === ENTERPRISE_PATH || nextPath === LEGACY_ENTERPRISE_PATH)
+ nextPath !== undefined &&
+ LANDING_PATHS.includes(nextPath)
);
}
+export function bypassesRunLocation(pathname: string, search = ""): boolean {
+ const path = normalizePath(pathname);
+ if (FLOW_PATHS.includes(path) || path.startsWith("/share/")) return true;
+ return isLanding(pathname, search);
+}
+
/**
* Layout route that shows the run-location chooser ahead of everything else,
* auth included, until this browser has confirmed a choice once.
@@ -45,6 +56,9 @@ export function bypassesRunLocation(pathname: string, search = ""): boolean {
export function RunLocationGate() {
const { pathname, search } = useLocation();
const [showChooser, setShowChooser] = useState(() => !hasChosenRunLocation());
+ // A landing link hands the visitor on into the app (checkout, the editor), so it settles the
+ // question for the rest of the visit, not just its own page.
+ if (showChooser && isLanding(pathname, search)) setShowChooser(false);
if (!showChooser || bypassesRunLocation(pathname, search)) {
return <Outlet />;
diff --git a/frontend/src/editor/saas/routes/Signup.tsx b/frontend/src/editor/saas/routes/Signup.tsx
index 678b804211..000795841b 100644
--- a/frontend/src/editor/saas/routes/Signup.tsx
+++ b/frontend/src/editor/saas/routes/Signup.tsx
@@ -6,6 +6,8 @@ import { useTranslation } from "@editor/hooks/useTranslation";
import { useDocumentMeta } from "@editor/hooks/useDocumentMeta";
import { getBaseUrl, withBasePath } from "@editor/constants/app";
import { rememberPendingDestination } from "@editor/services/pendingDestination";
+import { nextPathOf } from "@editor/routes/authShared/nextPath";
+import { TEAM_PATH } from "@editor/routes/teamPath";
import AuthLayout from "@editor/routes/authShared/AuthLayout";
import "@editor/auth/ui/auth.css";
import "@editor/routes/authShared/saas-auth.css";
@@ -36,18 +38,15 @@ export default function Signup() {
const [confirmPassword, setConfirmPassword] = useState("");
const [agree, setAgree] = useState(true);
const [fieldErrors, setFieldErrors] = useState<SignupFieldErrors>({});
+ const next = new URLSearchParams(location.search).get("next");
+ // Skipping makes a guest, and a guest cannot buy Team.
+ const buyingTeam = nextPathOf(next) === TEAM_PATH;
// Stashed rather than threaded onward: Supabase builds the confirmation link and
// it cannot carry a `next`.
useEffect(() => {
- try {
- rememberPendingDestination(
- new URL(window.location.href).searchParams.get("next"),
- );
- } catch (_) {
- // Unparseable URL; the visitor just lands on the default.
- }
- }, []);
+ rememberPendingDestination(next);
+ }, [next]);
// Check if we were redirected here with an auto-auth error
useEffect(() => {
@@ -169,7 +168,7 @@ export default function Signup() {
location: "top-right",
durationMs: 3000,
});
- setTimeout(() => navigate("/login"), 2000);
+ setTimeout(() => navigate(`/login${location.search}`), 2000);
}
} catch (err) {
console.error("[Signup] Unexpected error:", err);
@@ -276,25 +275,27 @@ export default function Signup() {
</div>
{/* Skip — small + muted, at the very bottom */}
- <div style={{ textAlign: "center", margin: "0.5rem 0 0.25rem" }}>
- <Button
- variant="tertiary"
- onClick={handleAnonymousSignIn}
- disabled={isSigningUp}
- style={{
- background: "none",
- border: "none",
- cursor: "pointer",
- fontSize: "0.8125rem",
- fontWeight: 500,
- color: "var(--c-text-subtle)",
- }}
- >
- {isSigningUp
- ? t("login.signingIn", "Signing in...")
- : `${t("signup.skip", "Skip")} →`}
- </Button>
- </div>
+ {!buyingTeam && (
+ <div style={{ textAlign: "center", margin: "0.5rem 0 0.25rem" }}>
+ <Button
+ variant="tertiary"
+ onClick={handleAnonymousSignIn}
+ disabled={isSigningUp}
+ style={{
+ background: "none",
+ border: "none",
+ cursor: "pointer",
+ fontSize: "0.8125rem",
+ fontWeight: 500,
+ color: "var(--c-text-subtle)",
+ }}
+ >
+ {isSigningUp
+ ? t("login.signingIn", "Signing in...")
+ : `${t("signup.skip", "Skip")} →`}
+ </Button>
+ </div>
+ )}
</AuthLayout>
);
}
diff --git a/frontend/src/editor/saas/routes/TeamRedirect.test.tsx b/frontend/src/editor/saas/routes/TeamRedirect.test.tsx
new file mode 100644
index 0000000000..5ffa015bc3
--- /dev/null
+++ b/frontend/src/editor/saas/routes/TeamRedirect.test.tsx
@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
+import { TeamRedirect } from "@editor/routes/TeamRedirect";
+import {
+ resetPendingDestinationForTests,
+ takePendingDestination,
+} from "@editor/services/pendingDestination";
+
+const auth = vi.hoisted(() => ({
+ session: null as object | null,
+ isAnonymous: false,
+ loading: false,
+}));
+
+vi.mock("@editor/auth/UseSession", () => ({ useAuth: () => auth }));
+vi.mock("@editor/components/shared/LoadingFallback", () => ({
+ LoadingFallback: () => <span>Loading</span>,
+}));
+
+function Location() {
+ const location = useLocation();
+ return (
+ <output data-testid="location">
+ {location.pathname}
+ {location.search}
+ </output>
+ );
+}
+
+function renderAt(entry: string) {
+ render(
+ <MemoryRouter initialEntries={[entry]}>
+ <Routes>
+ <Route path="/team" element={<TeamRedirect />} />
+ <Route path="*" element={<Location />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+describe("TeamRedirect", () => {
+ beforeEach(() => {
+ auth.session = null;
+ auth.isAnonymous = false;
+ auth.loading = false;
+ window.localStorage.clear();
+ resetPendingDestinationForTests();
+ });
+
+ it("sends a signed-in account straight to the Team checkout", async () => {
+ auth.session = { user: { id: "u1" } };
+ renderAt("/team");
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/settings/billing?upgrade=team",
+ ),
+ );
+ });
+
+ it("sends a signed-out visitor to log in and back, keeping the campaign query", async () => {
+ renderAt("/team?utm_campaign=nov");
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/login?next=%2Fteam%3Futm_campaign%3Dnov",
+ ),
+ );
+ expect(takePendingDestination()).toBe("/team?utm_campaign=nov");
+ });
+
+ it("treats a guest as signed out", async () => {
+ auth.session = { user: { id: "guest" } };
+ auth.isAnonymous = true;
+ renderAt("/team");
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/login?next=%2Fteam",
+ ),
+ );
+ });
+
+ it("waits for the session before deciding", () => {
+ auth.loading = true;
+ renderAt("/team");
+ expect(screen.getByText("Loading")).toBeInTheDocument();
+ expect(screen.queryByTestId("location")).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/saas/routes/TeamRedirect.tsx b/frontend/src/editor/saas/routes/TeamRedirect.tsx
new file mode 100644
index 0000000000..947e9fe8e3
--- /dev/null
+++ b/frontend/src/editor/saas/routes/TeamRedirect.tsx
@@ -0,0 +1,33 @@
+import { useEffect } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+import { useAuth } from "@editor/auth/UseSession";
+import { LoadingFallback } from "@editor/components/shared/LoadingFallback";
+import { rememberPendingDestination } from "@editor/services/pendingDestination";
+import { TEAM_PATH } from "@editor/routes/teamPath";
+import { TEAM_CHECKOUT_PATH } from "@editor/routes/teamCheckoutLink";
+
+/**
+ * Routes a Team buyer by who they are, so one link works for everyone: an account goes straight to
+ * the checkout in Usage & Billing (which leaves an existing Team customer on billing), anyone else
+ * signs in first and comes back here. A guest counts as signed out, since a guest session cannot
+ * hold a subscription.
+ */
+export function TeamRedirect() {
+ const { session, isAnonymous, loading } = useAuth();
+ const { search } = useLocation();
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ if (loading) return;
+ if (session && !isAnonymous) {
+ navigate(TEAM_CHECKOUT_PATH, { replace: true });
+ return;
+ }
+ const here = `${TEAM_PATH}${search}`;
+ // Remembered as well as named: a sign-up's confirmation email cannot carry a `next`.
+ rememberPendingDestination(here);
+ navigate(`/login?next=${encodeURIComponent(here)}`, { replace: true });
+ }, [loading, session, isAnonymous, search, navigate]);
+
+ return <LoadingFallback />;
+}
diff --git a/frontend/src/editor/saas/routes/authShared/nextPath.ts b/frontend/src/editor/saas/routes/authShared/nextPath.ts
new file mode 100644
index 0000000000..8ddb8c4895
--- /dev/null
+++ b/frontend/src/editor/saas/routes/authShared/nextPath.ts
@@ -0,0 +1,6 @@
+/** The path an auth page's `?next=` returns to, without its query or hash. */
+export function nextPathOf(
+ next: string | null | undefined,
+): string | undefined {
+ return next?.split(/[?#]/)[0];
+}
diff --git a/frontend/src/editor/saas/routes/teamPath.ts b/frontend/src/editor/saas/routes/teamPath.ts
new file mode 100644
index 0000000000..fe54fedbf1
--- /dev/null
+++ b/frontend/src/editor/saas/routes/teamPath.ts
@@ -0,0 +1,2 @@
+/** The one link for buying Team: the pricing page, campaign emails and sales replies all use it. */
+export const TEAM_PATH = "/team";
diff --git a/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx b/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx
index 66937daf2d..2e229720e2 100644
--- a/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx
+++ b/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx
@@ -14,6 +14,7 @@ import { SaasSessionBanner } from "@editor/portal/components/account-link/SaasSe
import { FreeTierPlanView } from "@editor/portal/components/billing/FreeTierPlanView";
import { Usage } from "@editor/portal/views/Usage";
import type { Wallet } from "@editor/portal/api/billing";
+import { requestsTeamCheckout } from "@editor/routes/teamCheckoutLink";
import { legacyProcurementTarget } from "@processor/components/procurement/enterprisePath";
/**
@@ -37,7 +38,7 @@ export function PortalBillingGate() {
const link = useLinkOptional();
const [searchParams] = useSearchParams();
const prompted = useRef(false);
- const accountLinkRequested = searchParams.get("upgrade") === "team";
+ const accountLinkRequested = requestsTeamCheckout(searchParams);
useEffect(() => {
if (!accountLinkRequested || link?.isLinked) prompted.current = false;
diff --git a/frontend/src/processor/proprietary/views/Usage.test.tsx b/frontend/src/processor/proprietary/views/Usage.test.tsx
index d3ae100cc9..af786ef0af 100644
--- a/frontend/src/processor/proprietary/views/Usage.test.tsx
+++ b/frontend/src/processor/proprietary/views/Usage.test.tsx
@@ -23,6 +23,7 @@ import {
import type { ProcurementSnapshot } from "@editor/portal/api/procurement";
import type { LegacyBillingState } from "@editor/types/legacyBilling";
import { formatPeriodDate } from "@editor/billing";
+import { isTeamWelcome } from "@editor/billing/teamWelcome";
const fetchCheckoutPricing = vi.hoisted(() => vi.fn());
vi.mock("@editor/portal/billing/stripe", () => ({ fetchCheckoutPricing }));
@@ -40,10 +41,13 @@ vi.mock("@editor/hooks/useLegacySubscriptions", () => ({
useLegacySubscriptions: () => legacyBilling,
}));
+let locationState: unknown;
+
// Usage renders Mantine-backed @editor/ui components (e.g. the "Manage Payment"
// Button in the subscribed header), which need a MantineProvider in the tree.
function Location() {
const location = useLocation();
+ locationState = location.state;
return (
<output data-testid="location">
{location.pathname}
@@ -296,6 +300,78 @@ describe("Usage — link-free wallet renderer", () => {
expect(checkout.openCheckout).not.toHaveBeenCalled();
});
+ it("opens Team for a hosted buyer arriving from the Team link", async () => {
+ checkoutEnabled = true;
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ renderUsage(<Usage />, "/settings/billing?upgrade=team");
+ await waitFor(() => expect(checkout.openCheckout).toHaveBeenCalledTimes(1));
+ expect(checkout.openCheckout).toHaveBeenCalledWith(
+ "server",
+ expect.objectContaining({
+ combinedChoose: true,
+ onContactSales: expect.any(Function),
+ onClose: expect.any(Function),
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).not.toHaveTextContent("upgrade="),
+ );
+ });
+
+ it.each([
+ ["an active Team", true, "leader"],
+ ["a member", false, "member"],
+ ] as const)(
+ "leaves a hosted account with %s on billing",
+ async (_label, held, role) => {
+ checkoutEnabled = true;
+ fetchWallet.mockResolvedValue({
+ ...walletOf("free"),
+ role,
+ team: { held, licensedUsers: 100 },
+ });
+ renderUsage(<Usage />, "/settings/billing?upgrade=team");
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).not.toHaveTextContent(
+ "upgrade=",
+ ),
+ );
+ expect(checkout.openCheckout).not.toHaveBeenCalled();
+ },
+ );
+
+ it("sends a Team-link buyer to the editor once they close a paid checkout", async () => {
+ checkoutEnabled = true;
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ renderUsage(<Usage />, "/settings/billing?upgrade=team");
+ await waitFor(() => expect(checkout.openCheckout).toHaveBeenCalledTimes(1));
+ const options = checkout.openCheckout.mock.calls[0][1];
+
+ act(() => options.onClose(true));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).toHaveTextContent("/editor"),
+ );
+ expect(isTeamWelcome(locationState)).toBe(true);
+ });
+
+ it("keeps a Team-link buyer on billing when they close without paying", async () => {
+ checkoutEnabled = true;
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ renderUsage(<Usage />, "/settings/billing?upgrade=team");
+ await waitFor(() => expect(checkout.openCheckout).toHaveBeenCalledTimes(1));
+
+ act(() => checkout.openCheckout.mock.calls[0][1].onClose(false));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).not.toHaveTextContent("upgrade="),
+ );
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/settings/billing",
+ );
+ expect(isTeamWelcome(locationState)).toBe(false);
+ });
+
it("loads the wallet on mount and reports it via onWalletLoaded (no link gate)", async () => {
fetchWallet.mockResolvedValue(walletOf("free"));
const onWalletLoaded = vi.fn();
diff --git a/frontend/src/processor/proprietary/views/Usage.tsx b/frontend/src/processor/proprietary/views/Usage.tsx
index ba55425875..f28e27cde6 100644
--- a/frontend/src/processor/proprietary/views/Usage.tsx
+++ b/frontend/src/processor/proprietary/views/Usage.tsx
@@ -12,7 +12,7 @@ import {
} from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
-import { useSearchParams } from "react-router-dom";
+import { useNavigate, useSearchParams } from "react-router-dom";
import { Banner, Button } from "@editor/ui";
import { BillingScreen, KvRow, formatPeriodDate } from "@editor/billing";
import { useLegacySubscriptions } from "@editor/hooks/useLegacySubscriptions";
@@ -37,6 +37,12 @@ import { useFleetStats } from "@editor/portal/queries/infrastructure";
import { qk } from "@editor/portal/queries/keys";
import { walletQuery, WALLET_POLL_MS } from "@editor/portal/queries/wallet";
import { useCheckoutOptional } from "@editor/contexts/CheckoutContext";
+import { EDITOR_BASENAME } from "@editor/routes/editorBasename";
+import {
+ TEAM_CHECKOUT_PARAM,
+ requestsTeamCheckout,
+} from "@editor/routes/teamCheckoutLink";
+import { TEAM_WELCOME_STATE } from "@editor/billing/teamWelcome";
import { SubscribedPlanView } from "@editor/portal/components/billing/SubscribedPlanView";
import {
HttpError,
@@ -121,6 +127,7 @@ export function Usage({
: null;
const openEnterprise = useOpenEnterprise();
const [searchParams, setSearchParams] = useSearchParams();
+ const navigate = useNavigate();
const isLeader = wallet?.role === "leader";
const bundleFlow = useBundleFlowState(
wallet?.teamId,
@@ -207,6 +214,10 @@ export function Usage({
// The same flow the settings plan section uses, so there is one purchase implementation.
// Optional on purpose: a build that mounts no provider must lose the door, not the page.
const checkout = useCheckoutOptional();
+ const overLocalLimit =
+ localUsersInUse != null &&
+ localUserLimit != null &&
+ localUsersInUse > localUserLimit;
const heldLimit = wallet?.team?.held ? wallet.team.licensedUsers : null;
const usersInUse = wallet?.team?.fleet
? fleetUsersInUse(
@@ -217,44 +228,55 @@ export function Usage({
: localUsersInUse === undefined
? wallet?.team?.usersInUse
: localUsersInUse;
- const addCapacity = useCallback(() => {
- const teamId = wallet?.teamId;
- // No email: the only one this instance holds is its local admin record, which is a Spring
- // username and not an address the buyer owns. The checkout asks for one instead.
- void checkout?.openCheckout("server", {
- combinedChoose: true,
- currentLimit: heldLimit,
- minimumSeats: usersInUse ?? undefined,
- resolveCurrency:
- teamId != null
- ? (preferredCurrency) =>
- fetchCheckoutPricing(teamId, "currency", preferredCurrency)
- : undefined,
- capacityNotice:
- !serverPlan &&
- !wallet?.team?.held &&
- localUsersInUse != null &&
- localUserLimit != null &&
- localUsersInUse > localUserLimit
- ? { users: localUsersInUse, limit: localUserLimit }
- : undefined,
- onSuccess: refresh,
- });
- }, [
- checkout,
- refresh,
- heldLimit,
- usersInUse,
- serverPlan,
- wallet?.team?.held,
- wallet?.teamId,
- localUsersInUse,
- localUserLimit,
- ]);
+ const addCapacity = useCallback(
+ (afterPurchase?: () => void) => {
+ const teamId = wallet?.teamId;
+ // No email: the only one this instance holds is its local admin record, which is a Spring
+ // username and not an address the buyer owns. The checkout asks for one instead.
+ void checkout?.openCheckout("server", {
+ combinedChoose: true,
+ currentLimit: heldLimit,
+ minimumSeats: usersInUse ?? undefined,
+ resolveCurrency:
+ teamId != null
+ ? (preferredCurrency) =>
+ fetchCheckoutPricing(teamId, "currency", preferredCurrency)
+ : undefined,
+ capacityNotice:
+ !serverPlan && !wallet?.team?.held && overLocalLimit
+ ? { users: localUsersInUse, limit: localUserLimit }
+ : undefined,
+ onContactSales: openEnterprise,
+ onSuccess: refresh,
+ onClose: (paid) => {
+ if (paid) afterPurchase?.();
+ },
+ });
+ },
+ [
+ checkout,
+ refresh,
+ openEnterprise,
+ heldLimit,
+ usersInUse,
+ serverPlan,
+ wallet?.team?.held,
+ wallet?.teamId,
+ localUsersInUse,
+ localUserLimit,
+ overLocalLimit,
+ ],
+ );
+
+ // Someone who came to buy Team is done with billing once they have it; the editor is where they
+ // invite their team.
+ const welcomeToTeam = useCallback(() => {
+ navigate(EDITOR_BASENAME, { state: TEAM_WELCOME_STATE });
+ }, [navigate]);
const handledTeamRequest = useRef(false);
useEffect(() => {
- if (searchParams.get("upgrade") !== "team") {
+ if (!requestsTeamCheckout(searchParams)) {
handledTeamRequest.current = false;
return;
}
@@ -267,26 +289,25 @@ export function Usage({
return;
handledTeamRequest.current = true;
const next = new URLSearchParams(searchParams);
- next.delete("upgrade");
+ next.delete(TEAM_CHECKOUT_PARAM);
setSearchParams(next, { replace: true });
- if (
- wallet.role === "leader" &&
- !wallet.team?.held &&
- !serverPlan &&
- localUsersInUse != null &&
- localUserLimit != null &&
- localUsersInUse > localUserLimit
- )
- addCapacity();
+ if (wallet.role !== "leader" || wallet.team?.held || serverPlan) return;
+ // Hosted billing has no local server: the link is a buyer asking for Team.
+ if (!hasLocalInstance) {
+ addCapacity(welcomeToTeam);
+ return;
+ }
+ if (overLocalLimit) addCapacity();
}, [
searchParams,
setSearchParams,
wallet,
checkout,
localUsersInUse,
- localUserLimit,
+ overLocalLimit,
serverPlan,
addCapacity,
+ welcomeToTeam,
hasLocalInstance,
]);
@@ -452,7 +473,7 @@ export function Usage({
licenseSection={renderLicenseSection?.(refreshAfterLicense)}
onAddCapacity={
!enterpriseProcessor && checkout && wallet?.role === "leader"
- ? addCapacity
+ ? () => addCapacity()
: undefined
}
onActivateProcessor={