Skip to content

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

Move procurement and license management into Usage & Billing (#7955)

ConnorYoh26fda9549833
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 685f118d8d..529573cbbf 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -9671,6 +9671,7 @@ sentenceTrial = "set up your trial workspace"
[portal.procurement.journey]
daysLeft_one = "{{count}} day left"
daysLeft_other = "{{count}} days left"
+expired = "Trial expired"
[portal.procurement.journeySteps.agreement]
blurb = "One signature covers MSA, order form, EULA and DPA."
diff --git a/frontend/editor/src/core/services/pendingDestination.test.ts b/frontend/editor/src/core/services/pendingDestination.test.ts
index f3dd77a8ad..0e71c08d13 100644
--- a/frontend/editor/src/core/services/pendingDestination.test.ts
+++ b/frontend/editor/src/core/services/pendingDestination.test.ts
@@ -19,8 +19,8 @@ afterEach(() => {
describe("pendingDestination", () => {
it("returns the remembered path", () => {
- rememberPendingDestination("/processor/procurement");
- expect(takePendingDestination()).toBe("/processor/procurement");
+ rememberPendingDestination("/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
});
it("keeps the query string, which carries the destination's own intent", () => {
@@ -35,22 +35,22 @@ describe("pendingDestination", () => {
});
it("survives a new page load", () => {
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
resetPendingDestinationForTests();
- expect(takePendingDestination()).toBe("/processor/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
});
it("consumes the intent, so it redirects one sign-in only", () => {
- rememberPendingDestination("/processor/procurement");
- expect(takePendingDestination()).toBe("/processor/procurement");
+ rememberPendingDestination("/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
resetPendingDestinationForTests();
expect(takePendingDestination()).toBeNull();
});
it("gives the same answer twice within a page load", () => {
- rememberPendingDestination("/processor/procurement");
- expect(takePendingDestination()).toBe("/processor/procurement");
- expect(takePendingDestination()).toBe("/processor/procurement");
+ rememberPendingDestination("/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
});
it("refuses to store an unsafe path", () => {
@@ -78,7 +78,7 @@ describe("pendingDestination", () => {
it("expires an intent older than the window", () => {
vi.useFakeTimers();
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
vi.advanceTimersByTime(25 * 60 * 60 * 1000);
resetPendingDestinationForTests();
expect(takePendingDestination()).toBeNull();
@@ -86,10 +86,10 @@ describe("pendingDestination", () => {
it("keeps an intent inside the window", () => {
vi.useFakeTimers();
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
vi.advanceTimersByTime(23 * 60 * 60 * 1000);
resetPendingDestinationForTests();
- expect(takePendingDestination()).toBe("/processor/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
});
it("survives a corrupt entry", () => {
@@ -98,14 +98,14 @@ describe("pendingDestination", () => {
});
it("clears without reading", () => {
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
clearPendingDestination();
expect(takePendingDestination()).toBeNull();
});
it("re-remembering replaces a taken intent in the same page load", () => {
- rememberPendingDestination("/processor/procurement");
- expect(takePendingDestination()).toBe("/processor/procurement");
+ rememberPendingDestination("/procurement");
+ expect(takePendingDestination()).toBe("/procurement");
rememberPendingDestination("/processor/users");
expect(takePendingDestination()).toBe("/processor/users");
});
diff --git a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx
index 724bcc74b8..68695465a7 100644
--- a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx
+++ b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx
@@ -1,33 +1,20 @@
import { describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen } from "@testing-library/react";
-import { MemoryRouter, useLocation } from "react-router-dom";
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
vi.mock("@portal/views/Usage", () => ({
- Usage: ({ onEnterpriseQuote }: { onEnterpriseQuote?: () => void }) => (
- <div data-testid="usage">
- <button onClick={onEnterpriseQuote}>Get enterprise quote</button>
- </div>
- ),
+ Usage: () => <div data-testid="usage" />,
}));
import { BillingSettingsSection } from "@portal/components/settings/BillingSettingsSection";
-function Location() {
- return <output>{useLocation().pathname}</output>;
-}
-
describe("PortalBillingGate — SaaS", () => {
it("renders the Usage page directly, with no link concept", () => {
render(
<MemoryRouter initialEntries={["/settings/billing"]}>
<BillingSettingsSection />
- <Location />
</MemoryRouter>,
);
expect(screen.getByTestId("usage")).toBeInTheDocument();
- fireEvent.click(
- screen.getByRole("button", { name: "Get enterprise quote" }),
- );
- expect(screen.getByText("/processor/procurement")).toBeInTheDocument();
});
});
diff --git a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx
index efb35aaa5e..73c3eba8f3 100644
--- a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx
+++ b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx
@@ -1,6 +1,4 @@
import { withBasePath } from "@app/constants/app";
-import { useNavigate } from "react-router-dom";
-import { toPortalPath } from "@portal/contexts/ViewContext";
import { Usage } from "@portal/views/Usage";
/**
@@ -13,10 +11,8 @@ import { Usage } from "@portal/views/Usage";
* without this a "Session expired" notice would dead-end until a manual reload.
*/
export function PortalBillingGate() {
- const navigate = useNavigate();
return (
<Usage
- onEnterpriseQuote={() => navigate(toPortalPath("/procurement"))}
onReauth={() => {
window.location.href = withBasePath("/login");
}}
diff --git a/frontend/editor/src/portal/PortalProviders.test.tsx b/frontend/editor/src/portal/PortalProviders.test.tsx
new file mode 100644
index 0000000000..8a0d54b796
--- /dev/null
+++ b/frontend/editor/src/portal/PortalProviders.test.tsx
@@ -0,0 +1,134 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter } from "react-router-dom";
+import { MantineProvider } from "@mantine/core";
+import type { ReactNode } from "react";
+import { PortalProviders } from "@portal/PortalProviders";
+import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";
+
+const { fetchAppConfig, getLicenseInfo } = vi.hoisted(() => ({
+ fetchAppConfig: vi.fn(),
+ getLicenseInfo: vi.fn(),
+}));
+
+vi.mock("@app/api/config", () => ({
+ DEFAULT_APP_CONFIG: { enableLogin: true },
+ fetchAppConfig,
+}));
+vi.mock("@app/services/licenseService", () => ({
+ default: { getLicenseInfo },
+}));
+vi.mock("@app/testing/serverExperienceSimulations", () => ({
+ getSimulatedLicenseInfo: () => null,
+}));
+vi.mock("@portal/contexts/TierContext", () => ({
+ TierProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@portal/contexts/LinkContext", () => ({
+ LinkProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@portal/contexts/UIContext", () => ({
+ UIProvider: ({ children }: { children: ReactNode }) => children,
+ useUI: () => ({ linkModalOpen: false }),
+}));
+vi.mock("@portal/contexts/AccountLinkContext", () => ({
+ AccountLinkProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@app/contexts/CheckoutContext", () => ({
+ CheckoutProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@portal/components/account-link/LinkAccountModal", () => ({
+ LinkAccountModal: () => null,
+}));
+vi.mock("@portal/components/account-link/ConnectCallbackHost", () => ({
+ ConnectCallbackHost: () => null,
+}));
+vi.mock("@portal/hooks/useFreeTierExhaustedPrompt", () => ({
+ useFreeTierExhaustedPrompt: () => {},
+}));
+vi.mock("@portal/components/PortalChrome", () => ({
+ PortalChrome: () => <ServerLicenseSection onSaved={() => {}} />,
+}));
+
+function renderPortal() {
+ return render(
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ }
+ >
+ <MemoryRouter initialEntries={["/processor/usage"]}>
+ <MantineProvider>
+ <PortalProviders />
+ </MantineProvider>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+}
+
+describe("PortalProviders license loading", () => {
+ beforeEach(() => {
+ fetchAppConfig
+ .mockReset()
+ .mockResolvedValue({ isAdmin: true, enableLogin: true });
+ getLicenseInfo
+ .mockReset()
+ .mockResolvedValue({ licenseKey: null, licenseType: "NORMAL" });
+ });
+
+ it("loads local config before fetching the license on a direct portal visit", async () => {
+ let resolveConfig!: (config: {
+ isAdmin: boolean;
+ enableLogin: boolean;
+ }) => void;
+ fetchAppConfig.mockReturnValue(
+ new Promise((resolve) => {
+ resolveConfig = resolve;
+ }),
+ );
+ renderPortal();
+ await waitFor(() => expect(fetchAppConfig).toHaveBeenCalledTimes(1));
+ expect(getLicenseInfo).not.toHaveBeenCalled();
+ expect(
+ screen.queryByRole("button", { name: "Add" }),
+ ).not.toBeInTheDocument();
+
+ resolveConfig({ isAdmin: true, enableLogin: true });
+ expect(await screen.findByText("No license installed")).toBeInTheDocument();
+ expect(getLicenseInfo).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole("button", { name: "Add" }));
+ expect(
+ screen.getByLabelText("License Key", {
+ selector: 'input[type="password"]',
+ }),
+ ).not.toBeDisabled();
+ });
+
+ it("settles a failed license request and retries without leaving a spinner", async () => {
+ getLicenseInfo.mockRejectedValueOnce(new Error("License request failed"));
+ renderPortal();
+ expect(
+ await screen.findByText("License request failed"),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(await screen.findByText("No license installed")).toBeInTheDocument();
+ expect(getLicenseInfo).toHaveBeenCalledTimes(2);
+ });
+
+ it("reports a failed config read instead of claiming no license is installed", async () => {
+ fetchAppConfig.mockRejectedValueOnce(new Error("Config request failed"));
+ renderPortal();
+ expect(
+ await screen.findByText("Config request failed"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("No license installed")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Add" }),
+ ).not.toBeInTheDocument();
+ expect(getLicenseInfo).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(await screen.findByText("No license installed")).toBeInTheDocument();
+ expect(getLicenseInfo).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/editor/src/portal/ViewRouter.test.tsx b/frontend/editor/src/portal/ViewRouter.test.tsx
new file mode 100644
index 0000000000..111088bd6c
--- /dev/null
+++ b/frontend/editor/src/portal/ViewRouter.test.tsx
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from "vitest";
+import { Suspense } from "react";
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
+import { ViewRouter } from "@portal/ViewRouter";
+import { getAdminRouteExtensions } from "@app/routes/adminRouteExtensions";
+
+vi.mock("@app/routes/hasPortal", () => ({ HAS_PORTAL: true }));
+vi.mock("@portal/PortalApp", () => ({ PortalApp: () => <ViewRouter /> }));
+
+vi.mock("@portal/views/Home", () => ({ Home: () => <div>Home</div> }));
+vi.mock("@portal/views/Users", () => ({ Users: () => null }));
+vi.mock("@portal/views/Documents", () => ({ Documents: () => null }));
+vi.mock("@portal/views/Review", () => ({ Review: () => null }));
+vi.mock("@portal/views/Pipelines", () => ({ Pipelines: () => null }));
+vi.mock("@portal/views/PipelineBuilder", () => ({
+ PipelineBuilder: () => null,
+}));
+vi.mock("@portal/views/Sources", () => ({ Sources: () => null }));
+vi.mock("@portal/views/Integrations", () => ({ Integrations: () => null }));
+
+function BillingLocation() {
+ const { pathname, search, hash } = useLocation();
+ return (
+ <output>
+ {pathname}
+ {search}
+ {hash}
+ </output>
+ );
+}
+
+describe("procurement sales links", () => {
+ it.each(["/", "/app"])(
+ "accepts the short link under basename %s without duplicating the prefix",
+ async (basename) => {
+ render(
+ <MemoryRouter
+ basename={basename}
+ initialEntries={[
+ `${basename === "/" ? "" : basename}/procurement?source=sales`,
+ ]}
+ >
+ <Suspense fallback={null}>
+ <Routes>
+ {getAdminRouteExtensions()}
+ <Route path="/settings/billing" element={<BillingLocation />} />
+ </Routes>
+ </Suspense>
+ </MemoryRouter>,
+ );
+ expect(
+ await screen.findByText(
+ "/settings/billing?source=sales&procurement=start",
+ ),
+ ).toBeInTheDocument();
+ },
+ );
+
+ it.each(["/", "/app"])(
+ "keeps the old usage bookmark's query and section under %s",
+ async (basename) => {
+ render(
+ <MemoryRouter
+ basename={basename}
+ initialEntries={[
+ `${basename === "/" ? "" : basename}/processor/usage?procurement=start#ub-license`,
+ ]}
+ >
+ <Suspense fallback={null}>
+ <Routes>
+ {getAdminRouteExtensions()}
+ <Route path="/settings/billing" element={<BillingLocation />} />
+ </Routes>
+ </Suspense>
+ </MemoryRouter>,
+ );
+ expect(
+ await screen.findByText(
+ "/settings/billing?procurement=start#ub-license",
+ ),
+ ).toBeInTheDocument();
+ },
+ );
+});
diff --git a/frontend/editor/src/portal/ViewRouter.tsx b/frontend/editor/src/portal/ViewRouter.tsx
index 9d73259f56..a6508504dc 100644
--- a/frontend/editor/src/portal/ViewRouter.tsx
+++ b/frontend/editor/src/portal/ViewRouter.tsx
@@ -1,11 +1,4 @@
-import { useEffect } from "react";
-import {
- Navigate,
- Route,
- Routes,
- useLocation,
- useNavigate,
-} from "react-router-dom";
+import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import { Home } from "@portal/views/Home";
import { Documents } from "@portal/views/Documents";
import { Review } from "@portal/views/Review";
@@ -15,7 +8,6 @@ import { Sources } from "@portal/views/Sources";
import { Integrations } from "@portal/views/Integrations";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
import { DOCS_PATH } from "@app/routes/docsRoute";
-import { useUI } from "@portal/contexts/UIContext";
/** Keeps the query and hash a moved tab's deep links carry (?tab=, #doc-id). */
function MovedTo({ to }: { to: string }) {
@@ -29,21 +21,6 @@ function MovedTo({ to }: { to: string }) {
// so they resolve to the portal, not the editor root.
const rel = (viewPath: string) => viewPath.replace(/^\//, "");
-/**
- * Procurement is not a surface of its own: the deal lives on Home, so this raises
- * the trial-setup step and bounces there. Raised imperatively rather than by
- * rendering <Navigate>, so the signal is set before the navigation, not racing it.
- */
-function ProcurementRedirect() {
- const { requestTrialSetup } = useUI();
- const navigate = useNavigate();
- useEffect(() => {
- requestTrialSetup();
- navigate(toPortalPath(VIEW_PATHS.home), { replace: true });
- }, [requestTrialSetup, navigate]);
- return null;
-}
-
/** Redirect the retired Policies path to the unified Pipelines page, carrying any query string. */
function PoliciesRedirect() {
const { search } = useLocation();
@@ -101,8 +78,6 @@ export function ViewRouter() {
element={<MovedTo to="/settings/billing" />}
/>
<Route path={rel(VIEW_PATHS.docs)} element={<MovedTo to={DOCS_PATH} />} />
- {/* A bare path, not a VIEW_PATHS entry: nothing should list it as a view. */}
- <Route path="procurement" element={<ProcurementRedirect />} />
{/* Account-link is a settings section now. */}
<Route
path="account-link"
diff --git a/frontend/editor/src/portal/api/procurement.ts b/frontend/editor/src/portal/api/procurement.ts
index b49de2f6b6..b318b82848 100644
--- a/frontend/editor/src/portal/api/procurement.ts
+++ b/frontend/editor/src/portal/api/procurement.ts
@@ -5,8 +5,7 @@ import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";
/*
* Procurement models the enterprise commercial journey: trial → quote → agreement → payment →
- * implementation. It is surfaced by the deal-status hero on Home and the takeover flow beside it;
- * there is no separate procurement route.
+ * implementation. Usage & Billing hosts the deal summary and its flow dialogs.
*/
/* ──────────────────────────────────────────────────────────────────────── */
@@ -221,7 +220,10 @@ export function startTrial(
): Promise<ProcurementSnapshot> {
return apiClient.saas.json<ProcurementSnapshot>(
"/api/v1/procurement/trial/start",
- { method: "POST", body: { deployment, users: seats, ...details } },
+ {
+ method: "POST",
+ body: { deployment, users: seats, ...details },
+ },
);
}
diff --git a/frontend/editor/src/portal/components/HomeHero.tsx b/frontend/editor/src/portal/components/HomeHero.tsx
index f2fdd36b51..6a507a25c1 100644
--- a/frontend/editor/src/portal/components/HomeHero.tsx
+++ b/frontend/editor/src/portal/components/HomeHero.tsx
@@ -1,54 +1,11 @@
-import { useEffect } from "react";
-import { Skeleton } from "@app/ui";
-import { useUI } from "@portal/contexts/UIContext";
import { EditorStatusCard } from "@portal/components/EditorStatusCard";
import { ConnectAccountRail } from "@portal/components/ConnectAccountRail";
-import { ControlledDealStatusHero } from "@portal/components/procurement/ProcurementBanner";
-import { ProcurementFlow } from "@portal/components/procurement/ProcurementFlow";
-import { useProcurement } from "@portal/components/procurement/useProcurement";
-/**
- * The Home hero: always the Editor deployment rail, carrying the deal-status hero as its footer
- * while a procurement deal is underway (procurement is a bolt-on to any tier). The rail states its
- * own deployment status and deploy ask, so there is nothing for a tier to choose between. The
- * procurement takeover modals render alongside.
- */
export function HomeHero() {
- const procurement = useProcurement();
- const { trialSetupRequested, clearTrialSetupRequest } = useUI();
- const dealActive =
- procurement.isLinked && procurement.started && !!procurement.data;
-
- // Someone said yes to enterprise elsewhere (the billing upsell, a sales link). Open trial setup
- // once the snapshot has landed, so a buyer who already has a deal is not asked to start another.
- useEffect(() => {
- if (!trialSetupRequested || procurement.loading) return;
- clearTrialSetupRequest();
- if (!procurement.started) procurement.onExploreEnterprise();
- }, [trialSetupRequested, procurement, clearTrialSetupRequest]);
-
return (
<>
<ConnectAccountRail />
- {procurement.loading ? (
- // Hold the rail's shape rather than committing to a footer: branching before the snapshot
- // lands paints the no-deal rail first, flashing on every refresh of an active deal.
- <section className="portal-surface portal-editor-hero" aria-busy>
- <div className="portal-editor-hero__row">
- <Skeleton width="2rem" height="2rem" />
- <Skeleton width="12rem" height="1rem" />
- </div>
- </section>
- ) : (
- <EditorStatusCard
- footer={
- dealActive ? (
- <ControlledDealStatusHero controller={procurement} />
- ) : undefined
- }
- />
- )}
- <ProcurementFlow controller={procurement} />
+ <EditorStatusCard />
</>
);
}
diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
index 3ed7706e80..459c884dca 100644
--- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
@@ -190,6 +190,8 @@ function openUrl(url: string): boolean {
interface Props {
open: boolean;
onClose: () => void;
+ /** Return to payment choices without cancelling the saved quote; omitted for top-ups. */
+ onBack?: () => void;
/** Drives teamId, per-run rate, currency, and top-up vs first-buy copy. */
wallet: Wallet;
/** Fired after a completed purchase so the parent can refetch the wallet. */
@@ -201,6 +203,7 @@ type Phase = "calc" | "pay";
export function BundleCheckoutModal({
open,
onClose,
+ onBack,
wallet,
onComplete,
}: Props) {
@@ -662,11 +665,17 @@ export function BundleCheckoutModal({
const footer =
phase === "calc" ? (
<div className="portal-billing__checkout-cap-actions">
- <Button variant="quiet" disabled={pdfBusy} onClick={onClose}>
- {t("portal.billing.prepaid.buy.cancel", "Cancel")}
+ <Button
+ variant="quiet"
+ disabled={busy || pdfBusy}
+ onClick={onBack ?? onClose}
+ >
+ {onBack
+ ? t("portal.billing.prepaid.buy.back", "Back")
+ : t("portal.billing.prepaid.buy.cancel", "Cancel")}
</Button>
<Button
- disabled={!canContinue || pdfBusy}
+ disabled={!canContinue || busy || pdfBusy}
onClick={handleContinue}
rightSection={<span aria-hidden>›</span>}
>
diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx
index e89219fd3c..f14ced89a4 100644
--- a/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx
+++ b/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx
@@ -1,22 +1,66 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useState } from "react";
+import { http, HttpResponse } from "msw";
+import { BillingScreen } from "@app/billing";
import { FreePlanView } from "@portal/components/billing/FreePlanView";
-import { freeWallet } from "@portal/components/billing/walletFixtures";
+import { freeWallet } from "@app/billing/walletFixtures";
import "@portal/components/billing/billing.css";
const meta: Meta<typeof FreePlanView> = {
title: "Portal/Billing/FreePlanView",
component: FreePlanView,
- parameters: { layout: "padded" },
+ parameters: {
+ layout: "fullscreen",
+ msw: {
+ handlers: [
+ http.post("*/rest/v1/rpc/payg_get_latest_bundle_quote", () =>
+ HttpResponse.json([
+ {
+ quote_id: 7,
+ users: 25,
+ posture_policies: 4,
+ size_mult: 1.2,
+ pipeline_mult: 1,
+ pool_credits: 576000,
+ price_minor: 480000,
+ currency: "usd",
+ consented_at: null,
+ stripe_quote_id: "qt_preview",
+ stripe_quote_number: "QT-0007",
+ stripe_ref: null,
+ valid_until: "2099-01-01T00:00:00Z",
+ },
+ ]),
+ ),
+ ],
+ },
+ },
};
export default meta;
type Story = StoryObj<typeof FreePlanView>;
-/** Leader — free meter + the "Turn on Processor" CTA (opens embedded checkout on click). */
-export const Leader: Story = {
- args: { wallet: freeWallet },
-};
+function ActivationPreview({ resume = false }: { resume?: boolean }) {
+ const [step, setStep] = useState<"choose" | "prepay" | "payg" | null>(
+ resume ? "prepay" : null,
+ );
+ return (
+ <BillingScreen
+ wallet={freeWallet}
+ onActivateProcessor={() => setStep(resume ? "prepay" : "choose")}
+ activateLabel={resume ? "View quote" : undefined}
+ extras={
+ <FreePlanView wallet={freeWallet} step={step} onStepChange={setStep} />
+ }
+ />
+ );
+}
-/** Member — sees the explainer but not the enable CTA. */
+export const Leader: Story = { render: () => <ActivationPreview /> };
export const Member: Story = {
args: { wallet: { ...freeWallet, role: "member" } },
};
+export const SavedQuote: Story = { render: () => <ActivationPreview resume /> };
+export const SavedQuoteDark: Story = {
+ ...SavedQuote,
+ globals: { theme: "dark" },
+};
diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx
new file mode 100644
index 0000000000..80ab4bd27f
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx
@@ -0,0 +1,109 @@
+import { useState } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { FreePlanView } from "@portal/components/billing/FreePlanView";
+import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";
+import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";
+import type { LatestBundleQuote } from "@portal/billing/stripe";
+
+const api = vi.hoisted(() => ({
+ getLatestBundleQuote: vi.fn(),
+ cancelBundleQuote: vi.fn(),
+ createBundleStripeQuote: vi.fn(),
+ acceptBundleStripeQuote: vi.fn(),
+ upsertBundleQuote: vi.fn(),
+ createCheckoutSession: vi.fn(),
+}));
+vi.mock("@portal/billing/stripe", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@portal/billing/stripe")>()),
+ ...api,
+ getStripePublishableKey: () => null,
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ }),
+}));
+
+const savedQuote: LatestBundleQuote = {
+ quoteId: 7,
+ users: 25,
+ posturePolicies: 4,
+ sizeMult: 1.2,
+ pipelineMult: 1,
+ poolCredits: 576000,
+ priceMinor: 480000,
+ currency: "usd",
+ consentedAt: null,
+ stripeQuoteId: "qt_test",
+ stripeQuoteNumber: "QT-0007",
+ stripeRef: null,
+ validUntil: "2099-01-01T00:00:00Z",
+};
+
+function ResumedActivation() {
+ const [step, setStep] = useState<"choose" | "prepay" | "payg" | null>(
+ "prepay",
+ );
+ return (
+ <FreePlanView wallet={freeWallet} step={step} onStepChange={setStep} />
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ sessionStorage.clear();
+ api.getLatestBundleQuote.mockResolvedValue(savedQuote);
+});
+
+describe("Processor activation navigation", () => {
+ it("returns from a saved quote to monthly limit selection without cancelling or purchasing", async () => {
+ render(
+ <MantineProvider>
+ <ResumedActivation />
+ </MantineProvider>,
+ );
+ fireEvent.click(await screen.findByRole("button", { name: "Back" }));
+ fireEvent.click(screen.getByRole("button", { name: "Pay as you go" }));
+ const limit = screen.getByRole("textbox", { name: "Monthly spend limit" });
+ fireEvent.change(limit, { target: { value: "250" } });
+ expect(limit).toHaveValue("250");
+ expect(api.cancelBundleQuote).not.toHaveBeenCalled();
+ expect(api.acceptBundleStripeQuote).not.toHaveBeenCalled();
+ expect(api.createCheckoutSession).not.toHaveBeenCalled();
+ });
+
+ it("returns from the monthly limit to the same annual quote without minting another", async () => {
+ render(
+ <MantineProvider>
+ <ResumedActivation />
+ </MantineProvider>,
+ );
+ fireEvent.click(await screen.findByRole("button", { name: "Back" }));
+ fireEvent.click(screen.getByRole("button", { name: "Pay as you go" }));
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ fireEvent.click(screen.getByRole("button", { name: "Prepay a year" }));
+ expect(
+ await screen.findByText("Calculate your annual payment"),
+ ).toBeInTheDocument();
+ expect(api.getLatestBundleQuote).toHaveBeenCalledTimes(2);
+ expect(api.cancelBundleQuote).not.toHaveBeenCalled();
+ expect(api.createBundleStripeQuote).not.toHaveBeenCalled();
+ expect(api.upsertBundleQuote).not.toHaveBeenCalled();
+ });
+
+ it("keeps Cancel for a subscribed team's standalone top-up", async () => {
+ const onClose = vi.fn();
+ render(
+ <MantineProvider>
+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={onClose} />
+ </MantineProvider>,
+ );
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel" }));
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(
+ screen.queryByRole("button", { name: "Pay as you go" }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
index 7892ac4bfe..d4c074790d 100644
--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx
+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
@@ -1,13 +1,12 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
-import { Banner, Button } from "@app/ui";
+import { Banner } from "@app/ui";
import type { Wallet } from "@portal/api/billing";
import type { SaasCurrency } from "@portal/billing/stripe";
import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";
import { ActivationChoiceModal } from "@portal/components/billing/ActivationChoiceModal";
import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";
import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";
-import { useBundleFlowState } from "@portal/hooks/useBundleFlowState";
interface Props {
wallet: Wallet;
@@ -24,22 +23,21 @@ interface Props {
* modal awaits this to stay open through activation.
*/
onSubscribed?: () => Promise<boolean>;
+ /** Refresh the host's quote status when an activation dialog closes. */
+ onActivationClosed?: () => void;
}
function isSaasCurrency(c: string | null): c is SaasCurrency {
return c === "usd" || c === "eur" || c === "gbp";
}
-/**
- * Linked, not yet subscribed — the "Editor" current plan. Shows the team's free
- * editor fleet, the Processor trial meter (with the inline "Switch on the
- * Processor" CTA → embedded Stripe Checkout), and the Enterprise upsell.
- */
+/** Owns activation dialogs and prepaid capacity; the host supplies the Processor row action. */
export function FreePlanView({
wallet,
step: controlledStep,
onStepChange,
onSubscribed,
+ onActivationClosed,
}: Props) {
const { t } = useTranslation();
// Activation fork (demo D97): choose → the metered checkout (payg) or the
@@ -56,11 +54,6 @@ export function FreePlanView({
? wallet.currency
: "usd";
- // Where this team sits in the prepaid-bundle flow, read on load so the CTA names
- // the resume action rather than always restarting the fork. Leader + team gated
- // (the RPC 403s otherwise). Refreshed when any activation modal closes.
- const flow = useBundleFlowState(wallet.teamId, isLeader);
-
function requireTeam(): boolean {
if (wallet.teamId == null) {
setMissingTeam(
@@ -85,24 +78,9 @@ export function FreePlanView({
// freshly-minted quote / invoice without a full page reload.
function closeModals() {
setStep(null);
- flow.refresh();
+ onActivationClosed?.();
}
- // Starting the Processor is the row's own door. What survives here is the case that door
- // cannot express: a quote or invoice already raised, which resumes rather than starts.
- const resumeAction =
- isLeader && flow.status !== "none" ? (
- <Button
- variant="primary"
- onClick={resumeBundle}
- disabled={wallet.teamId == null}
- >
- {flow.status === "invoice"
- ? t("portal.billing.freePlan.payInvoice", "Pay invoice to complete")
- : t("portal.billing.freePlan.viewQuote", "View quote")}
- </Button>
- ) : null;
-
return (
<div className="portal-billing__stack">
{/* A live pool is usable without a metered subscription, so it surfaces on the free plan
@@ -114,10 +92,6 @@ export function FreePlanView({
/>
)}
- {resumeAction && (
- <div className="portal-billing__prepaid-foot">{resumeAction}</div>
- )}
-
{missingTeam && (
<Banner
tone="warning"
@@ -140,6 +114,7 @@ export function FreePlanView({
<StripeCheckoutModal
open={step === "payg"}
onClose={closeModals}
+ onBack={() => setStep("choose")}
teamId={wallet.teamId}
currency={currency}
pricePerDocMinor={wallet.pricePerDocMinor}
@@ -158,6 +133,7 @@ export function FreePlanView({
<BundleCheckoutModal
open={step === "prepay"}
onClose={closeModals}
+ onBack={() => setStep("choose")}
wallet={wallet}
onComplete={() => {
closeModals();
diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx
index 27742d8a3e..389a6b8996 100644
--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx
+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ReactNode } from "react";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { PortalTestProviders } from "@portal/test/TestQueryProvider";
@@ -46,11 +47,11 @@ const BALANCE = {
periodEnd: "2026-10-01T00:00:00",
};
-const renderView = () =>
+const renderView = (licenseSection?: ReactNode) =>
render(
<PortalTestProviders>
<MemoryRouter>
- <FreeTierPlanView />
+ <FreeTierPlanView licenseSection={licenseSection} />
</MemoryRouter>
</PortalTestProviders>,
);
@@ -63,6 +64,26 @@ describe("FreeTierPlanView", () => {
openLinkModal.mockReset();
});
+ it.each(["ready", "failed"])(
+ "retains license management at the end of the shared card when the ledger is %s",
+ async (state) => {
+ if (state === "ready") fetchFreeTier.mockResolvedValue(BALANCE);
+ else
+ fetchFreeTier.mockRejectedValue(
+ new HttpError(500, "Server Error", null),
+ );
+ renderView(<button>Manage local license</button>);
+ await screen.findByText(
+ state === "ready" ? "120 of 500 used" : "Couldn't load credit usage",
+ );
+ const section = screen
+ .getByRole("button", { name: "Manage local license" })
+ .closest("section");
+ expect(section).toHaveAttribute("id", "ub-license");
+ expect(section?.parentElement?.lastElementChild).toBe(section);
+ },
+ );
+
it("meters the local ledger on the shared screen", async () => {
fetchFreeTier.mockResolvedValue(BALANCE);
renderView();
diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
index 30dc8061dd..256a496d14 100644
--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
@@ -1,13 +1,12 @@
vi.mock("@portal/hooks/useServerPlan", () => ({
useServerPlan: () => ({ serverPlan: undefined, loading: false }),
}));
-vi.mock("@portal/components/billing/ServerLicenseSection", () => ({
- ServerLicenseSection: () => null,
-}));
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, useLocation } from "react-router-dom";
+import type { ReactNode } from "react";
+import { MantineProvider } from "@mantine/core";
/**
* Which usage page this instance has one of. The unlinked half must not go anywhere near the
@@ -21,6 +20,32 @@ const link = { is: false };
const connect = vi.fn();
const applyLinkFacts = vi.fn();
+const config = { isAdmin: false, enableLogin: true };
+const license = {
+ licenseInfo: {
+ licenseKey: "test-existing-license" as string | null,
+ licenseType: "ENTERPRISE",
+ },
+ loading: false,
+ error: null as string | null,
+ refetchLicense: vi.fn(),
+};
+const saveLicenseKey = vi.fn();
+const saveLicenseFile = vi.fn();
+const onLicenseSaved = vi.fn();
+
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config }),
+}));
+vi.mock("@app/contexts/LicenseContext", () => ({ useLicense: () => license }));
+vi.mock("@app/services/licenseService", () => ({
+ default: {
+ saveLicenseKey: (...args: unknown[]) => saveLicenseKey(...args),
+ saveLicenseFile: (...args: unknown[]) => saveLicenseFile(...args),
+ },
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
vi.mock("@portal/hooks/useConnectGate", () => ({
useConnectGate: () => ({ ...gate, connect, guard: (f: unknown) => f }),
}));
@@ -37,36 +62,46 @@ vi.mock("@portal/hooks/usePortalAdmin", () => ({
vi.mock("@portal/views/Usage", () => ({
Usage: ({
onWalletLoaded,
- onEnterpriseQuote,
+ renderLicenseSection,
}: {
onWalletLoaded?: (w: unknown) => void;
- onEnterpriseQuote?: () => void;
+ renderLicenseSection?: (onSaved: () => void) => ReactNode;
}) => {
onWalletLoaded?.({ status: "free" });
return (
- <div data-testid="usage">
- <button onClick={onEnterpriseQuote}>Get enterprise quote</button>
- </div>
+ <div data-testid="usage">{renderLicenseSection?.(onLicenseSaved)}</div>
);
},
}));
+
vi.mock("@portal/components/billing/FreeTierPlanView", () => ({
- FreeTierPlanView: () => <div data-testid="free-tier" />,
+ FreeTierPlanView: ({ licenseSection }: { licenseSection?: ReactNode }) => (
+ <div data-testid="free-tier">{licenseSection}</div>
+ ),
}));
import { BillingSettingsSection } from "@portal/components/settings/BillingSettingsSection";
function Location() {
- return <output>{useLocation().pathname}</output>;
+ const location = useLocation();
+ return (
+ <output data-testid="location">
+ {location.pathname}
+ {location.search}
+ </output>
+ );
}
-
-const renderGate = () =>
- render(
- <MemoryRouter initialEntries={["/settings/billing"]}>
- <BillingSettingsSection />
- <Location />
- </MemoryRouter>,
+function GateTree({ entry = "/settings/billing" }: { entry?: string }) {
+ return (
+ <MantineProvider>
+ <MemoryRouter initialEntries={[entry]}>
+ <Location />
+ <BillingSettingsSection />
+ </MemoryRouter>
+ </MantineProvider>
);
+}
+const renderGate = () => render(<GateTree />);
describe("PortalBillingGate — self-hosted", () => {
beforeEach(() => {
@@ -76,6 +111,15 @@ describe("PortalBillingGate — self-hosted", () => {
applyLinkFacts.mockReset();
gate.gated = false;
gate.loading = false;
+ config.isAdmin = false;
+ config.enableLogin = true;
+ license.licenseInfo.licenseKey = "test-existing-license";
+ license.loading = false;
+ license.error = null;
+ license.refetchLicense.mockReset().mockResolvedValue(undefined);
+ saveLicenseKey.mockReset().mockResolvedValue({ success: true });
+ saveLicenseFile.mockReset().mockResolvedValue({ success: true });
+ onLicenseSaved.mockReset();
});
it("shows the instance's own meter when there is no account, rather than a bounce", () => {
@@ -85,15 +129,6 @@ describe("PortalBillingGate — self-hosted", () => {
expect(screen.queryByTestId("usage")).toBeNull();
});
- it("starts enterprise through the processor entry route across the settings provider boundary", () => {
- link.is = true;
- renderGate();
- fireEvent.click(
- screen.getByRole("button", { name: "Get enterprise quote" }),
- );
- expect(screen.getByText("/processor/procurement")).toBeInTheDocument();
- });
-
it("asks for nothing on the way in", () => {
gate.gated = true;
renderGate();
@@ -142,4 +177,178 @@ describe("PortalBillingGate — self-hosted", () => {
expect(screen.queryByTestId("usage")).not.toBeInTheDocument();
expect(applyLinkFacts).not.toHaveBeenCalled();
});
+ it.each([null, "", "00000000-0000-0000-0000-000000000000"])(
+ "treats %s as empty and discards an unsaved edit on close",
+ (key) => {
+ config.isAdmin = true;
+ link.is = true;
+ license.licenseInfo.licenseKey = key;
+ renderGate();
+ expect(screen.getByText("No license installed")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "View" }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Add" }));
+ expect(screen.queryByText("Active License")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("⚠️ Warning: Existing License Detected"),
+ ).not.toBeInTheDocument();
+ const input = screen.getByLabelText("License Key", {
+ selector: 'input[type="password"]',
+ });
+ fireEvent.change(input, { target: { value: "unsaved" } });
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ expect(saveLicenseKey).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Add" }));
+ expect(
+ screen.getByLabelText("License Key", {
+ selector: 'input[type="password"]',
+ }),
+ ).toHaveValue("");
+ },
+ );
+
+ it("reveals an installed key only when View is opened", () => {
+ config.isAdmin = true;
+ link.is = true;
+ renderGate();
+ expect(screen.queryByText("test-existing-license")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View" }));
+ expect(screen.getByText("test-existing-license")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ expect(screen.queryByText("test-existing-license")).not.toBeInTheDocument();
+ });
+
+ it("shows a certificate filename and exposes its full source in View", () => {
+ config.isAdmin = true;
+ link.is = true;
+ license.licenseInfo.licenseKey = "file:/licenses/enterprise.lic";
+ renderGate();
+ expect(screen.getByText("enterprise.lic")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View" }));
+ expect(screen.getByText("/licenses/enterprise.lic")).toBeInTheDocument();
+ });
+
+ it("reuses the license-key save flow and refreshes billing after activation", async () => {
+ config.isAdmin = true;
+ link.is = true;
+ renderGate();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Update",
+ }),
+ );
+ expect(screen.getByText("Active License")).toBeInTheDocument();
+ expect(
+ screen.getByText("⚠️ Warning: Existing License Detected"),
+ ).toBeInTheDocument();
+ fireEvent.change(
+ screen.getByLabelText("License Key", {
+ selector: 'input[type="password"]',
+ }),
+ {
+ target: { value: " new-test-license " },
+ },
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Save Changes" }),
+ );
+ await waitFor(() => expect(onLicenseSaved).toHaveBeenCalledTimes(1));
+ expect(saveLicenseKey).toHaveBeenCalledWith("new-test-license");
+ expect(license.refetchLicense).toHaveBeenCalledTimes(1);
+ expect(saveLicenseFile).not.toHaveBeenCalled();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("reuses certificate upload instead of sending it as a license string", async () => {
+ config.isAdmin = true;
+ link.is = true;
+ renderGate();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Update",
+ }),
+ );
+ fireEvent.click(
+ await screen.findByRole("radio", { name: "Certificate File" }),
+ );
+ const file = new File(["test-certificate"], "license.lic");
+ fireEvent.change(document.querySelector('input[type="file"]')!, {
+ target: { files: [file] },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save Changes" }));
+ await waitFor(() => expect(onLicenseSaved).toHaveBeenCalledTimes(1));
+ expect(saveLicenseFile).toHaveBeenCalledWith(file);
+ expect(saveLicenseKey).not.toHaveBeenCalled();
+ });
+
+ it("does not refresh billing when license activation fails", async () => {
+ config.isAdmin = true;
+ link.is = true;
+ saveLicenseKey.mockResolvedValue({
+ success: false,
+ error: "Invalid license",
+ });
+ renderGate();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Update",
+ }),
+ );
+ fireEvent.change(
+ screen.getByLabelText("License Key", {
+ selector: 'input[type="password"]',
+ }),
+ {
+ target: { value: "invalid" },
+ },
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Save Changes" }),
+ );
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Save Changes" }),
+ ).not.toBeDisabled(),
+ );
+ expect(license.refetchLicense).not.toHaveBeenCalled();
+ expect(onLicenseSaved).not.toHaveBeenCalled();
+ });
+
+ it("offers a retry without exposing the form when the current license cannot load", () => {
+ config.isAdmin = true;
+ link.is = true;
+ license.error = "License unavailable";
+ renderGate();
+ expect(screen.getByText("License unavailable")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", {
+ name: "Update",
+ }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(license.refetchLicense).toHaveBeenCalledTimes(1);
+ });
+ it("keeps local license management available without linking", () => {
+ renderGate();
+ expect(screen.getByRole("button", { name: "View" })).toBeInTheDocument();
+ expect(applyLinkFacts).not.toHaveBeenCalled();
+ });
+
+ it("prompts once for a procurement link and preserves it when linking completes", () => {
+ gate.gated = true;
+ const view = render(
+ <GateTree entry="/settings/billing?procurement=start" />,
+ );
+ expect(connect).toHaveBeenCalledTimes(1);
+ view.rerender(<GateTree entry="/settings/billing?procurement=start" />);
+ expect(connect).toHaveBeenCalledTimes(1);
+ link.is = true;
+ gate.gated = false;
+ view.rerender(<GateTree entry="/settings/billing?procurement=start" />);
+ expect(screen.getByTestId("usage")).toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/settings/billing?procurement=start",
+ );
+ });
});
diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx
index 4d2f05d85a..f82adc9c1c 100644
--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx
+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx
@@ -1,8 +1,8 @@
-import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";
import { useServerPlan } from "@portal/hooks/useServerPlan";
import { ManageBillingButton } from "@app/components/shared/ManageBillingButton";
-import { useCallback } from "react";
-import { useNavigate } from "react-router-dom";
+import { useCallback, useEffect, useRef } from "react";
+import { useSearchParams } from "react-router-dom";
+import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";
import {
useApplyLinkFacts,
useLinkOptional,
@@ -11,7 +11,6 @@ import { useUI } from "@portal/contexts/UIContext";
import { useConnectGate } from "@portal/hooks/useConnectGate";
import { usePortalAdmin } from "@portal/hooks/usePortalAdmin";
import { FreeTierPlanView } from "@portal/components/billing/FreeTierPlanView";
-import { toPortalPath } from "@portal/contexts/ViewContext";
import { Usage } from "@portal/views/Usage";
import type { Wallet } from "@portal/api/billing";
@@ -24,23 +23,30 @@ import type { Wallet } from "@portal/api/billing";
*/
export function PortalBillingGate() {
const applyLinkFacts = useApplyLinkFacts();
- const { openLinkModal } = useUI();
- const { loading } = useConnectGate();
+ const { openLinkModal, trialSetupRequested } = useUI();
+ const { loading, gated, connect } = useConnectGate();
const isAdmin = usePortalAdmin();
const { serverPlan, loading: licenseLoading } = useServerPlan(isAdmin);
const serverPlanAction = serverPlan ? <ManageBillingButton /> : undefined;
const link = useLinkOptional();
- const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const prompted = useRef(false);
+ const procurementRequested =
+ trialSetupRequested || searchParams.get("procurement") === "start";
+
+ useEffect(() => {
+ if (!procurementRequested || link?.isLinked) prompted.current = false;
+ else if (isAdmin && !loading && gated && !prompted.current) {
+ prompted.current = true;
+ connect();
+ }
+ }, [procurementRequested, link?.isLinked, isAdmin, loading, gated, connect]);
const onWalletLoaded = useCallback(
(w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),
[applyLinkFacts],
);
const onReauth = useCallback(() => openLinkModal("reauth"), [openLinkModal]);
- // The processor owns a separate UIProvider, so its entry route must raise the trial request.
- const onEnterpriseQuote = useCallback(() => {
- navigate(toPortalPath("/procurement"));
- }, [navigate]);
// Administrators only: the figures are instance-wide and the endpoints ADMIN-gated. The nav
// hides the entry to match, so this is the backstop for a typed URL.
@@ -62,12 +68,11 @@ export function PortalBillingGate() {
<Usage
serverPlan={serverPlan}
serverPlanAction={serverPlanAction}
+ onWalletLoaded={onWalletLoaded}
+ onReauth={onReauth}
renderLicenseSection={(onSaved) => (
<ServerLicenseSection onSaved={onSaved} />
)}
- onWalletLoaded={onWalletLoaded}
- onReauth={onReauth}
- onEnterpriseQuote={onEnterpriseQuote}
/>
);
}
diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
index ee76a780c2..faaf8664cb 100644
--- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
@@ -23,6 +23,8 @@ import { PrepayModalHeader } from "@portal/components/billing/PrepayModalHeader"
interface Props {
open: boolean;
onClose: () => void;
+ /** Return from the spend limit to the host's payment choices. */
+ onBack?: () => void;
/** Caller's resolved team id. The edge function needs it to scope checkout. */
teamId: number;
/** "usd" | "eur" | "gbp" — the SaaS PAYG offering's supported set. */
@@ -224,6 +226,7 @@ function SpendLimitPicker({
export function StripeCheckoutModal({
open,
onClose,
+ onBack,
teamId,
currency,
pricePerDocMinor,
@@ -447,7 +450,11 @@ export function StripeCheckoutModal({
</Banner>
)}
<div className="portal-billing__checkout-cap-actions">
- <Button variant="quiet" onClick={onClose} disabled={capBusy}>
+ <Button
+ variant="quiet"
+ onClick={onBack ?? onClose}
+ disabled={capBusy}
+ >
{t("portal.billing.checkout.cap.back", "Back")}
</Button>
<Button
diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx
index 77c008ce41..5d8befccf5 100644
--- a/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx
+++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx
@@ -1,6 +1,8 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { DealStatusHero } from "@portal/components/procurement/DealStatusHero";
import type { ProcurementSnapshot } from "@portal/api/procurement";
+import { BillingScreen } from "@app/billing/BillingScreen";
+import { freeWallet } from "@app/billing/walletFixtures";
const base: ProcurementSnapshot = {
dealId: 1,
@@ -19,7 +21,7 @@ const base: ProcurementSnapshot = {
latestQuote: null,
};
-/** The Home deal-status hero across the commercial stages; the CTA expands the takeover modal. */
+/** The CTA opens the existing flow; the billing stories exercise its section and jump link. */
const meta: Meta<typeof DealStatusHero> = {
title: "Portal/Procurement/DealStatusHero",
component: DealStatusHero,
@@ -32,13 +34,21 @@ const meta: Meta<typeof DealStatusHero> = {
onInvite: () => {},
onSchedule: () => {},
onManageTrial: () => {},
+ onDocuments: () => {},
},
};
export default meta;
type Story = StoryObj<typeof DealStatusHero>;
-export const Trial: Story = { args: { snapshot: base } };
+export const Trial: Story = {
+ args: {
+ snapshot: {
+ ...base,
+ trialEndsAt: new Date(Date.now() + 7 * 86_400_000).toISOString(),
+ },
+ },
+};
export const Quote: Story = {
args: { snapshot: { ...base, stage: "quote", trialEndsAt: null } },
};
@@ -53,3 +63,26 @@ export const Live: Story = {
snapshot: { ...base, stage: "active", licensed: true, trialEndsAt: null },
},
};
+
+export const BillingTrial: Story = {
+ parameters: { layout: "fullscreen" },
+ args: Trial.args,
+ render: (args) => (
+ <BillingScreen
+ wallet={freeWallet}
+ procurementSection={<DealStatusHero {...args} />}
+ />
+ ),
+};
+
+export const BillingExpiredTrial: Story = {
+ ...BillingTrial,
+ args: {
+ snapshot: { ...base, stage: "quote", trialEndsAt: "2020-01-01T00:00:00Z" },
+ },
+};
+
+export const BillingTrialDark: Story = {
+ ...BillingTrial,
+ globals: { theme: "dark" },
+};
diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.test.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.test.tsx
new file mode 100644
index 0000000000..5026a50a62
--- /dev/null
+++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.test.tsx
@@ -0,0 +1,104 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { DealStatusHero } from "@portal/components/procurement/DealStatusHero";
+import type { ProcurementSnapshot } from "@portal/api/procurement";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, value?: string | { count?: number }) => {
+ if (typeof value === "string") return value;
+ if (key === "portal.procurement.journey.daysLeft")
+ return `${value?.count} days left`;
+ return key;
+ },
+ }),
+}));
+vi.mock("@portal/components/procurement/CalendlyInline", () => ({
+ warmCalendly: vi.fn(),
+}));
+
+const snapshot: ProcurementSnapshot = {
+ dealId: 1,
+ stage: "trial",
+ deployment: "selfhost",
+ seats: 100,
+ trialStartedAt: "2026-09-01T00:00:00Z",
+ trialEndsAt: "2026-09-18T00:00:00Z",
+ trialExtensionsUsed: 0,
+ licensed: true,
+ licenseKey: "trial-license",
+ agreementSignedVersion: null,
+ businessName: null,
+ contactName: null,
+ contactEmail: null,
+ latestQuote: null,
+};
+
+function mount(overrides: Partial<ProcurementSnapshot> = {}, readOnly = false) {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-09-11T00:00:00Z"));
+ const onManageTrial = vi.fn();
+ const onDocuments = vi.fn();
+ render(
+ <MantineProvider>
+ <DealStatusHero
+ snapshot={{ ...snapshot, ...overrides }}
+ readOnly={readOnly}
+ canSchedule={false}
+ onExpand={vi.fn()}
+ onAcceptQuote={vi.fn()}
+ onLicense={vi.fn()}
+ onInvite={vi.fn()}
+ onSchedule={vi.fn()}
+ onManageTrial={onManageTrial}
+ onDocuments={onDocuments}
+ />
+ </MantineProvider>,
+ );
+ return { onManageTrial, onDocuments };
+}
+
+afterEach(() => vi.useRealTimers());
+
+describe("DealStatusHero trial status", () => {
+ it("preserves the trial-management action and document icon", () => {
+ const { onManageTrial, onDocuments } = mount();
+ fireEvent.click(screen.getByRole("button", { name: "7 days left" }));
+ expect(onManageTrial).toHaveBeenCalledOnce();
+ fireEvent.click(
+ screen.getByRole("button", { name: "portal.procurement.hero.documents" }),
+ );
+ expect(onDocuments).toHaveBeenCalledOnce();
+ });
+
+ it.each(["trial", "quote", "security"] as const)(
+ "shows expiry during %s without using the licensed flag as proof of validity",
+ (stage) => {
+ mount({ stage, trialEndsAt: "2026-09-10T00:00:00Z" });
+ expect(screen.getByText("Trial expired")).toBeInTheDocument();
+ },
+ );
+
+ it("does not offer trial extensions after the deal advances to quote", () => {
+ mount({ stage: "quote" });
+ expect(screen.getByText("7 days left")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "7 days left" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it.each(["exploring", "procurement", "active"] as const)(
+ "does not label %s using a historical trial date",
+ (stage) => {
+ mount({ stage, trialEndsAt: "2026-09-10T00:00:00Z" });
+ expect(screen.queryByText("Trial expired")).not.toBeInTheDocument();
+ },
+ );
+
+ it("shows the member's trial status without mutation actions", () => {
+ mount({}, true);
+ expect(screen.getByText("7 days left")).toBeInTheDocument();
+ expect(screen.queryAllByRole("button")).toHaveLength(0);
+ });
+});
diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
index 643d6dd56b..186fa22b72 100644
--- a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
+++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
@@ -42,13 +42,13 @@ const STAGE_CTA: Record<DealStage, string> = {
};
/**
- * The enterprise deal-status hero on Home (procurement lives here, not as a nav tab) — this card IS
- * the procurement surface. It carries the journey as a segmented progress band plus a stage
+ * The enterprise deal summary carries the journey as a segmented progress band plus a stage
* sentence, and one primary action with quiet icon buttons beside it; the flow itself opens in the
* takeover modal. Rollout setup lives in the non-procurement setup checklist, not here.
*/
export function DealStatusHero({
snapshot,
+ readOnly = false,
busy = false,
canSchedule,
onExpand,
@@ -60,6 +60,8 @@ export function DealStatusHero({
onDocuments,
}: {
snapshot: ProcurementSnapshot;
+ /** Members can follow the deal without access to the leader's procurement actions. */
+ readOnly?: boolean;
busy?: boolean;
/** Booking a call runs through the linked account (its email prefills Calendly), so the
* "Schedule a call" action only appears when the org has linked its account. */
@@ -87,6 +89,14 @@ export function DealStatusHero({
const stage = snapshot.stage ?? "trial";
const inTrial = stage === "trial";
+ const trialDaysLeft =
+ snapshot.trialEndsAt && ["trial", "quote", "security"].includes(stage)
+ ? daysLeft(snapshot.trialEndsAt)
+ : null;
+ const trialLabel =
+ trialDaysLeft === 0
+ ? t("portal.procurement.journey.expired", "Trial expired")
+ : t("portal.procurement.journey.daysLeft", { count: trialDaysLeft ?? 0 });
const isLive = stage === "active";
// A live quote is sitting with the buyer. A draft (or an expired/cancelled one) is not something to
// accept — that stage still means "finish building it".
@@ -149,17 +159,19 @@ export function DealStatusHero({
)}
</p>
- {inTrial && snapshot.trialEndsAt && (
+ {trialDaysLeft != null && Number.isFinite(trialDaysLeft) && (
<div className="portal-hero__chips">
- <button
- type="button"
- className="portal-hero__chip portal-hero__chip--action"
- onClick={onManageTrial}
- >
- {t("portal.procurement.journey.daysLeft", {
- count: daysLeft(snapshot.trialEndsAt),
- })}
- </button>
+ {inTrial && !readOnly ? (
+ <button
+ type="button"
+ className="portal-hero__chip portal-hero__chip--action"
+ onClick={onManageTrial}
+ >
+ {trialLabel}
+ </button>
+ ) : (
+ <span className="portal-hero__chip">{trialLabel}</span>
+ )}
</div>
)}
</div>
@@ -181,60 +193,62 @@ export function DealStatusHero({
</div>
)}
- <div className="portal-hero__cta">
- {/* An issued quote is a decision point, so the card carries both halves of it: accept it, or
+ {!readOnly && (
+ <div className="portal-hero__cta">
+ {/* An issued quote is a decision point, so the card carries both halves of it: accept it, or
open it again to read and circulate first. Every other stage has one next step. */}
- {quoteAwaitingDecision ? (
- <>
- <Button variant="primary" loading={busy} onClick={onAcceptQuote}>
- {t("portal.procurement.review.acceptCta")}
+ {quoteAwaitingDecision ? (
+ <>
+ <Button variant="primary" loading={busy} onClick={onAcceptQuote}>
+ {t("portal.procurement.review.acceptCta")}
+ </Button>
+ <Button variant="secondary" onClick={onExpand}>
+ {t("portal.procurement.hero.ctaReviewQuote")}
+ </Button>
+ </>
+ ) : invoiceUrl ? (
+ <Button variant="primary" onClick={() => openApiUrl(invoiceUrl)}>
+ {t("portal.procurement.payment.viewInvoice")}
</Button>
- <Button variant="secondary" onClick={onExpand}>
- {t("portal.procurement.hero.ctaReviewQuote")}
+ ) : (
+ <Button variant="primary" loading={busy} onClick={onExpand}>
+ {t(STAGE_CTA[stage])}
</Button>
- </>
- ) : invoiceUrl ? (
- <Button variant="primary" onClick={() => openApiUrl(invoiceUrl)}>
- {t("portal.procurement.payment.viewInvoice")}
- </Button>
- ) : (
- <Button variant="primary" loading={busy} onClick={onExpand}>
- {t(STAGE_CTA[stage])}
- </Button>
- )}
- <div className="portal-hero__icons">
- {snapshot.licenseKey && (
- <IconAction
- label={t("portal.procurement.hero.licenseKey")}
- onClick={onLicense}
- >
- <KeyIcon size={15} />
- </IconAction>
- )}
- <IconAction
- label={t("portal.procurement.hero.documents")}
- onClick={onDocuments}
- >
- <DocumentsIcon size={15} />
- </IconAction>
- {!isLive && (
- <IconAction
- label={t("portal.procurement.hero.inviteTeammates")}
- onClick={onInvite}
- >
- <UserPlusIcon size={15} />
- </IconAction>
)}
- {canSchedule && (
+ <div className="portal-hero__icons">
+ {snapshot.licenseKey && (
+ <IconAction
+ label={t("portal.procurement.hero.licenseKey")}
+ onClick={onLicense}
+ >
+ <KeyIcon size={15} />
+ </IconAction>
+ )}
<IconAction
- label={t("portal.procurement.hero.scheduleCall")}
- onClick={onSchedule}
+ label={t("portal.procurement.hero.documents")}
+ onClick={onDocuments}
>
- <CalendarIcon size={15} />
+ <DocumentsIcon size={15} />
</IconAction>
- )}
+ {!isLive && (
+ <IconAction
+ label={t("portal.procurement.hero.inviteTeammates")}
+ onClick={onInvite}
+ >
+ <UserPlusIcon size={15} />
+ </IconAction>
+ )}
+ {canSchedule && (
+ <IconAction
+ label={t("portal.procurement.hero.scheduleCall")}
+ onClick={onSchedule}
+ >
+ <CalendarIcon size={15} />
+ </IconAction>
+ )}
+ </div>
</div>
- </div>
+ )}
</div>
);
}
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx b/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx
index af2a13b6e5..5e6c409af2 100644
--- a/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx
+++ b/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx
@@ -3,19 +3,21 @@ import { DealStatusHero } from "@portal/components/procurement/DealStatusHero";
import type { ProcurementController } from "@portal/components/procurement/useProcurement";
/**
- * The deal-status hero, wired to a shared ProcurementController. Rendered as the Home hero card's
- * footer once a deal is underway; assumes an active deal (controller.data present).
+ * The deal-status hero and the dialogs must share the same controller instance.
*/
export function ControlledDealStatusHero({
controller,
+ readOnly = false,
}: {
controller: ProcurementController;
+ readOnly?: boolean;
}) {
const { openSettings } = useUI();
if (!controller.data) return null;
return (
<DealStatusHero
snapshot={controller.data}
+ readOnly={readOnly}
busy={controller.busy}
canSchedule={controller.isLinked}
onExpand={() =>
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementFlow.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementFlow.stories.tsx
index 03984936c8..67e96f355f 100644
--- a/frontend/editor/src/portal/components/procurement/ProcurementFlow.stories.tsx
+++ b/frontend/editor/src/portal/components/procurement/ProcurementFlow.stories.tsx
@@ -70,6 +70,8 @@ function makeController(
return {
isLinked: true,
loading: false,
+ loadError: null,
+ retry: () => {},
data: snapshot,
started: true,
stage: snapshot.stage ?? undefined,
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx b/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx
index 9dc8cd5b7e..670b6d6782 100644
--- a/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx
+++ b/frontend/editor/src/portal/components/procurement/ProcurementFlow.tsx
@@ -22,8 +22,7 @@ import type { ProcurementController } from "@portal/components/procurement/usePr
* The procurement takeover flow: the full-screen journey modal (quote builder →
* quote & agreement → payment → live) plus the licence-key, schedule-call, trial-setup,
* and trial-management modals. Driven entirely by a shared ProcurementController
- * so it can sit next to a deal-status hero rendered elsewhere (e.g. inside the
- * tier hero card on Home).
+ * so it can sit alongside the deal-status section in Usage & Billing.
*/
export function ProcurementFlow({
controller,
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementRedirect.tsx b/frontend/editor/src/portal/components/procurement/ProcurementRedirect.tsx
new file mode 100644
index 0000000000..256a689385
--- /dev/null
+++ b/frontend/editor/src/portal/components/procurement/ProcurementRedirect.tsx
@@ -0,0 +1,9 @@
+import { Navigate, useLocation } from "react-router-dom";
+
+/** Keep sales links resumable across sign-in, account linking and page reloads. */
+export function ProcurementRedirect() {
+ const { search } = useLocation();
+ const params = new URLSearchParams(search);
+ params.set("procurement", "start");
+ return <Navigate to={`/settings/billing?${params}`} replace />;
+}
diff --git a/frontend/editor/src/portal/components/procurement/useProcurement.ts b/frontend/editor/src/portal/components/procurement/useProcurement.ts
index 111dcff8a6..583d55401b 100644
--- a/frontend/editor/src/portal/components/procurement/useProcurement.ts
+++ b/frontend/editor/src/portal/components/procurement/useProcurement.ts
@@ -30,14 +30,13 @@ export type ProcurementExtra =
| "documents";
/**
- * Owns the procurement deal state and actions shared by the Home hero footer
- * (deal-status hero) and the takeover flow modals. Extracted from
- * ProcurementHome so the deal-status hero can render inside the tier hero card
- * while the flow modals live alongside it. Gated on an account link.
+ * Shares a linked account's deal state between the billing summary and procurement dialogs.
*/
export interface ProcurementController {
isLinked: boolean;
loading: boolean;
+ loadError: string | null;
+ retry: () => void;
data: ProcurementSnapshot | null;
started: boolean;
stage: ProcurementSnapshot["stage"] | undefined;
@@ -92,18 +91,17 @@ export function useProcurement(): ProcurementController {
const isLinked = usePortalLinked();
// Through the shared query cache, not a per-mount fetch: the snapshot survives navigation, so
- // returning to Home renders the deal from cache instead of flashing the loading state again.
+ // returning to billing renders the deal from cache instead of flashing the loading state again.
// No retry — a failing snapshot must not hold `loading` true through backoff, since the hero
// gates its whole card on it.
const queryClient = useQueryClient();
const snapshotKey = qk.procurement(isLinked);
- const state = toAsyncState(
- useQuery<ProcurementSnapshot | null>({
- queryKey: snapshotKey,
- queryFn: () => (isLinked ? fetchSnapshot() : Promise.resolve(null)),
- retry: false,
- }),
- );
+ const query = useQuery<ProcurementSnapshot | null>({
+ queryKey: snapshotKey,
+ queryFn: () => (isLinked ? fetchSnapshot() : Promise.resolve(null)),
+ retry: false,
+ });
+ const state = toAsyncState(query);
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [editing, setEditing] = useState(false);
@@ -284,6 +282,14 @@ export function useProcurement(): ProcurementController {
return {
isLinked,
loading: state.loading,
+ loadError: state.error
+ ? state.error instanceof Error
+ ? state.error.message
+ : String(state.error)
+ : null,
+ retry: () => {
+ void query.refetch();
+ },
data,
started,
stage,
diff --git a/frontend/editor/src/portal/contexts/UIContext.tsx b/frontend/editor/src/portal/contexts/UIContext.tsx
index 73c9d73307..354afaa6ff 100644
--- a/frontend/editor/src/portal/contexts/UIContext.tsx
+++ b/frontend/editor/src/portal/contexts/UIContext.tsx
@@ -51,8 +51,7 @@ interface UIContextValue {
clearConnectOutcome: () => void;
/**
* A request to begin the enterprise trial, raised from wherever the buyer said yes (the billing
- * upsell, a sales link). The deal controller lives on Home, so this is a one-shot signal rather
- * than a direct call: Home consumes it, opens trial setup, and clears it.
+ * upsell). Usage & Billing consumes it once the deal is loaded, then starts or resumes the flow.
*/
trialSetupRequested: boolean;
requestTrialSetup: () => void;
diff --git a/frontend/editor/src/portal/views/Procurement.css b/frontend/editor/src/portal/views/Procurement.css
index 8bdd97c118..94a19257f8 100644
--- a/frontend/editor/src/portal/views/Procurement.css
+++ b/frontend/editor/src/portal/views/Procurement.css
@@ -380,7 +380,6 @@
margin-top: 3px;
}
-/* ── Deal-status hero (Home, active deal) ─────────────────────────────────── */
.portal-hero {
padding: 1.1rem 1.25rem;
display: flex;
@@ -388,12 +387,11 @@
gap: 1rem;
}
-/* Attached under the editor rail the two read as one card, so the hero drops its standalone frame
- and lets the footer's top border be the only seam. It keeps the frame on the procurement view,
- where it stands alone. */
-.portal-editor-hero__footer .portal-hero {
+.billing-sec--procurement .portal-hero {
+ padding: 0;
border: none;
border-radius: 0;
+ background: transparent;
}
.portal-hero__top {
display: flex;
diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsx
index 2eca3a5dfe..603a9dc18f 100644
--- a/frontend/editor/src/portal/views/Usage.test.tsx
+++ b/frontend/editor/src/portal/views/Usage.test.tsx
@@ -2,24 +2,90 @@ vi.mock("@portal/queries/infrastructure", () => ({
useFleetStats: () => ({ data: null, loading: false, error: null }),
}));
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MantineProvider } from "@mantine/core";
import type { ReactElement } from "react";
+import { StrictMode } from "react";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { UIProvider } from "@portal/contexts/UIContext";
+import type { ProcurementSnapshot } from "@portal/api/procurement";
// Usage renders Mantine-backed @app/ui components (e.g. the "Manage Payment"
// Button in the subscribed header), which need a MantineProvider in the tree.
-const renderUsage = (ui: ReactElement) =>
- render(<MantineProvider>{ui}</MantineProvider>);
+function Location() {
+ const location = useLocation();
+ return (
+ <output data-testid="location">
+ {location.pathname}
+ {location.search}
+ </output>
+ );
+}
+
+const renderUsage = (ui: ReactElement, entry = "/settings/billing") =>
+ render(
+ <StrictMode>
+ <MemoryRouter initialEntries={[entry]}>
+ <UIProvider>
+ <MantineProvider>
+ {ui}
+ <Location />
+ </MantineProvider>
+ </UIProvider>
+ </MemoryRouter>
+ </StrictMode>,
+ );
+
+const translate = (key: string, def?: string) => def ?? key;
vi.mock("react-i18next", () => ({
useTranslation: () => ({
- t: (key: string, def?: string) => def ?? key,
+ t: translate,
i18n: { changeLanguage: vi.fn() },
}),
}));
const fetchWallet = vi.fn();
const refreshWalletCache = vi.fn();
+const bundleFlow = { status: "none", refresh: vi.fn() };
+vi.mock("@portal/hooks/useBundleFlowState", () => ({
+ useBundleFlowState: () => bundleFlow,
+}));
+const procurement = {
+ isLinked: true,
+ loading: false,
+ loadError: null as string | null,
+ error: null,
+ open: false,
+ started: false,
+ stage: null as ProcurementSnapshot["stage"],
+ retry: vi.fn(),
+ onExploreEnterprise: vi.fn(),
+ onStartTrial: vi.fn(),
+ setOpen: vi.fn(),
+};
+vi.mock("@portal/components/procurement/useProcurement", () => ({
+ useProcurement: () => procurement,
+}));
+vi.mock("@portal/components/procurement/ProcurementBanner", () => ({
+ ControlledDealStatusHero: ({ readOnly }: { readOnly: boolean }) => (
+ <div data-testid="procurement-summary">
+ {readOnly ? "Read-only deal" : "Enterprise deal"}
+ </div>
+ ),
+}));
+vi.mock("@portal/components/procurement/ProcurementFlow", () => ({
+ ProcurementFlow: () => <div data-testid="procurement-flow" />,
+}));
+vi.mock("@portal/api/fleetStats", () => ({
+ fetchFleetStats: () => Promise.resolve(null),
+}));
+vi.mock("@portal/api/users", () => ({
+ fetchAdminEmail: () => Promise.resolve(null),
+}));
+vi.mock("@app/contexts/CheckoutContext", () => ({
+ useCheckoutOptional: () => null,
+}));
vi.mock("@portal/api/billing", () => ({
fetchWallet: () => fetchWallet(),
refreshWalletCache: () => refreshWalletCache(),
@@ -33,13 +99,27 @@ vi.mock("@portal/hooks/useStripePortal", () => ({
}));
// Stub the plan views so the test doesn't depend on the full wallet shape.
vi.mock("@portal/components/billing/FreePlanView", () => ({
- FreePlanView: () => null,
+ FreePlanView: ({
+ step,
+ onActivationClosed,
+ }: {
+ step?: string | null;
+ onActivationClosed?: () => void;
+ }) =>
+ step ? (
+ <div data-testid="activation-step">
+ {step}
+ <button onClick={onActivationClosed}>Close activation</button>
+ </div>
+ ) : null,
}));
vi.mock("@portal/components/billing/SubscribedPlanView", () => ({
SubscribedPlanView: () => null,
}));
import { Usage } from "@portal/views/Usage";
+import { BillingScreen } from "@app/billing/BillingScreen";
+import { freeWallet } from "@app/billing/walletFixtures";
describe("Usage — link-free wallet renderer", () => {
// Enough of a wallet for BillingScreen to render; the bare {status} fixture predates it.
@@ -61,8 +141,17 @@ describe("Usage — link-free wallet renderer", () => {
});
beforeEach(() => {
+ bundleFlow.status = "none";
+ bundleFlow.refresh.mockReset();
fetchWallet.mockReset();
refreshWalletCache.mockReset();
+ procurement.loading = false;
+ procurement.loadError = null;
+ procurement.started = false;
+ procurement.stage = null;
+ procurement.onExploreEnterprise.mockReset();
+ procurement.onStartTrial.mockReset();
+ procurement.setOpen.mockReset();
});
it("loads the wallet on mount and reports it via onWalletLoaded (no link gate)", async () => {
@@ -83,6 +172,199 @@ describe("Usage — link-free wallet renderer", () => {
renderUsage(<Usage />);
+ await waitFor(() => expect(fetchWallet).toHaveBeenCalled());
+ expect(
+ screen.queryByRole("button", { name: "License Key" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("places local license management at the end of billing and refreshes after a save", async () => {
+ fetchWallet.mockResolvedValue(walletOf("free"));
+ refreshWalletCache.mockResolvedValue(undefined);
+ renderUsage(
+ <Usage
+ renderLicenseSection={(onSaved) => (
+ <button onClick={onSaved}>Activate local license</button>
+ )}
+ />,
+ );
+ await screen.findByText("This cycle");
+ const sections = Array.from(document.querySelectorAll(".billing-sec")).map(
+ (section) => section.id,
+ );
+ expect(sections).toEqual(["ub-plan", "ub-usage", "ub-license"]);
+ const scrollIntoView = vi.fn();
+ document.getElementById("ub-license")!.scrollIntoView = scrollIntoView;
+ fireEvent.click(screen.getByRole("button", { name: "License Key" }));
+ expect(scrollIntoView).toHaveBeenCalled();
+ fetchWallet.mockClear();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Activate local license" }),
+ );
await waitFor(() => expect(fetchWallet).toHaveBeenCalledTimes(1));
+ expect(refreshWalletCache).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the license section and navigation after payment and invoices", () => {
+ renderUsage(
+ <BillingScreen
+ wallet={freeWallet}
+ paymentSection={<div>Payment details</div>}
+ invoicesSection={<div>Invoices</div>}
+ licenseSection={<div>License details</div>}
+ />,
+ );
+ expect(
+ Array.from(
+ document.querySelectorAll(".billing-sec"),
+ (section) => section.id,
+ ),
+ ).toEqual(["ub-plan", "ub-usage", "ub-pay", "ub-inv", "ub-license"]);
+ expect(
+ Array.from(
+ document.querySelectorAll(".billing-card__chip"),
+ (chip) => chip.textContent,
+ ),
+ ).toEqual(["Plan", "Usage", "Payment", "Invoices", "License Key"]);
+ });
+
+ it.each([
+ ["none", "Switch on the Processor", "choose"],
+ ["quote", "View quote", "prepay"],
+ ["invoice", "Pay invoice to complete", "prepay"],
+ ])("uses the Processor row to resume %s", async (status, label, step) => {
+ bundleFlow.status = status;
+ fetchWallet.mockResolvedValue({
+ ...walletOf("free"),
+ role: "leader",
+ teamId: 42,
+ });
+ renderUsage(<Usage />);
+ const action = await screen.findByRole("button", { name: label });
+ expect(action.closest(".billing-meter")).toHaveTextContent("Processor");
+ expect(screen.getAllByRole("button", { name: label })).toHaveLength(1);
+ if (status !== "none")
+ expect(
+ screen.queryByRole("button", { name: "Switch on the Processor" }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(action);
+ expect(screen.getByTestId("activation-step")).toHaveTextContent(step);
+ fireEvent.click(screen.getByRole("button", { name: "Close activation" }));
+ expect(bundleFlow.refresh).toHaveBeenCalledTimes(1);
+ });
+
+ it("withholds a quote resume action from members", async () => {
+ bundleFlow.status = "quote";
+ fetchWallet.mockResolvedValue(walletOf("free"));
+ renderUsage(<Usage />);
+ await screen.findByText("This cycle");
+ expect(
+ screen.queryByRole("button", { name: "View quote" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps local license management available when the cloud wallet cannot load", async () => {
+ fetchWallet.mockRejectedValue(new Error("Wallet unavailable"));
+ renderUsage(
+ <Usage renderLicenseSection={() => <div>Local license form</div>} />,
+ );
+ await screen.findByText("Wallet unavailable");
+ expect(screen.getByText("Local license form")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "License Key" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Plan" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("starts procurement from the billing CTA without leaving Usage", async () => {
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ renderUsage(<Usage />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Get an enterprise quote" }),
+ );
+ expect(procurement.onExploreEnterprise).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/settings/billing",
+ );
+ });
+
+ it.each([
+ [null, "onExploreEnterprise"],
+ ["exploring", "onStartTrial"],
+ ["trial", "setOpen"],
+ ["quote", "setOpen"],
+ ["security", "setOpen"],
+ ["procurement", "setOpen"],
+ ["active", "setOpen"],
+ ] as const)("resumes %s once from a sales link", async (stage, action) => {
+ procurement.stage = stage;
+ procurement.started = stage !== null;
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ renderUsage(<Usage />, "/settings/billing?procurement=start&source=sales");
+ await waitFor(() => expect(procurement[action]).toHaveBeenCalledTimes(1));
+ await waitFor(() =>
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "/settings/billing?source=sales",
+ ),
+ );
+ if (stage) expect(procurement.onExploreEnterprise).not.toHaveBeenCalled();
+ });
+
+ it("keeps a failed snapshot's start request pending instead of creating another deal", async () => {
+ procurement.loadError = "Snapshot unavailable";
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ renderUsage(<Usage />, "/settings/billing?procurement=start");
+ await screen.findByText("The full PDF Editor.");
+ expect(screen.getByText("Snapshot unavailable")).toBeInTheDocument();
+ expect(procurement.onExploreEnterprise).not.toHaveBeenCalled();
+ expect(screen.getByTestId("location")).toHaveTextContent(
+ "procurement=start",
+ );
+ expect(
+ screen.queryByRole("button", { name: "Get an enterprise quote" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("anchors an existing deal before Plan and connects its jump button", async () => {
+ procurement.started = true;
+ procurement.stage = "trial";
+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });
+ const scroll = vi.fn();
+ renderUsage(<Usage />);
+ await screen.findByText("The full PDF Editor.");
+ const section = screen.getByRole("region", { name: "Procurement" });
+ section.scrollIntoView = scroll;
+ expect(section.nextElementSibling?.id).toBe("ub-plan");
+ fireEvent.click(screen.getByRole("button", { name: "Procurement" }));
+ expect(scroll).toHaveBeenCalled();
+ expect(
+ screen.queryByRole("button", { name: "Get an enterprise quote" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows members the deal without starting or mounting its mutation dialogs", async () => {
+ procurement.started = true;
+ procurement.stage = "trial";
+ fetchWallet.mockResolvedValue(walletOf("free"));
+ renderUsage(<Usage />, "/settings/billing?procurement=start");
+ await screen.findByText("The full PDF Editor.");
+ expect(screen.getByText("Read-only deal")).toBeInTheDocument();
+ expect(screen.queryByTestId("procurement-flow")).not.toBeInTheDocument();
+ expect(procurement.setOpen).not.toHaveBeenCalled();
+ });
+
+ it("keeps the deal visible if the wallet fails", async () => {
+ procurement.started = true;
+ fetchWallet.mockRejectedValue(new Error("Wallet unavailable"));
+ renderUsage(<Usage />);
+ await screen.findByText("Wallet unavailable");
+ expect(
+ screen.getByRole("region", { name: "Procurement" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Plan" }),
+ ).not.toBeInTheDocument();
});
});
diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsx
index 50e7e02e88..bc1b7f9668 100644
--- a/frontend/editor/src/portal/views/Usage.tsx
+++ b/frontend/editor/src/portal/views/Usage.tsx
@@ -1,9 +1,19 @@
-import type { ReactNode } from "react";
import type { ServerPlan } from "@app/billing/serverPlan";
-import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import { useTranslation } from "react-i18next";
+import { useSearchParams } from "react-router-dom";
import { Banner, Button } from "@app/ui";
import { BillingScreen } from "@app/billing";
+import { useUI } from "@portal/contexts/UIContext";
+import { useProcurement } from "@portal/components/procurement/useProcurement";
+import { ControlledDealStatusHero } from "@portal/components/procurement/ProcurementBanner";
+import { ProcurementFlow } from "@portal/components/procurement/ProcurementFlow";
import {
fetchWallet,
refreshWalletCache,
@@ -15,6 +25,7 @@ import {
type LocalUsage,
} from "@portal/api/link";
import { useStripePortal } from "@portal/hooks/useStripePortal";
+import { useBundleFlowState } from "@portal/hooks/useBundleFlowState";
import { FreePlanView } from "@portal/components/billing/FreePlanView";
import { PaymentSection } from "@portal/components/billing/PaymentSection";
import { InvoicesSection } from "@portal/components/billing/InvoicesSection";
@@ -32,7 +43,6 @@ import "@portal/components/billing/billing.css";
export interface UsageProps {
serverPlan?: ServerPlan;
serverPlanAction?: ReactNode;
- renderLicenseSection?: (onSaved: () => void) => ReactNode;
/**
* Called with the wallet whenever it loads (initial fetch + post-checkout
* flip). A flavor-agnostic hook the composition uses for cross-cutting state —
@@ -46,9 +56,8 @@ export interface UsageProps {
* is owned by the app, so this path never triggers).
*/
onReauth?: () => void;
- /** A prop rather than a hook, as {@link onReauth} is: reaching for a router here would make
- * this view unrenderable wherever one is absent. */
- onEnterpriseQuote?: () => void;
+ /** Only the self-hosted host supplies local license management; notify after activation. */
+ renderLicenseSection?: (onSaved: () => void) => ReactNode;
}
/**
@@ -63,13 +72,57 @@ export interface UsageProps {
export function Usage({
serverPlan,
serverPlanAction,
- renderLicenseSection,
onWalletLoaded,
onReauth,
- onEnterpriseQuote,
+ renderLicenseSection,
}: UsageProps = {}) {
const { t } = useTranslation();
const [wallet, setWallet] = useState<Wallet | null>(null);
+ const procurement = useProcurement();
+ const { trialSetupRequested, clearTrialSetupRequest } = useUI();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const handledProcurementRequest = useRef(false);
+ const canManageProcurement = wallet?.role === "leader";
+ const bundleFlow = useBundleFlowState(
+ wallet?.teamId,
+ canManageProcurement && wallet?.status === "free",
+ );
+
+ useEffect(() => {
+ const requested =
+ trialSetupRequested || searchParams.get("procurement") === "start";
+ if (!requested) {
+ handledProcurementRequest.current = false;
+ return;
+ }
+ if (
+ handledProcurementRequest.current ||
+ !wallet ||
+ !procurement.isLinked ||
+ procurement.loading ||
+ procurement.loadError
+ )
+ return;
+ handledProcurementRequest.current = true;
+ clearTrialSetupRequest();
+ if (searchParams.get("procurement") === "start") {
+ const next = new URLSearchParams(searchParams);
+ next.delete("procurement");
+ setSearchParams(next, { replace: true });
+ }
+ if (!canManageProcurement) return;
+ if (!procurement.started) procurement.onExploreEnterprise();
+ else if (procurement.stage === "exploring") procurement.onStartTrial();
+ else procurement.setOpen(true);
+ }, [
+ trialSetupRequested,
+ searchParams,
+ setSearchParams,
+ wallet,
+ procurement,
+ canManageProcurement,
+ clearTrialSetupRequest,
+ ]);
// Locally-accrued usage SaaS hasn't billed yet; added to the synced figure so
// "current usage" reflects work since the last daily sync. Best-effort.
const [localUsage, setLocalUsage] = useState<LocalUsage | null>(null);
@@ -78,6 +131,22 @@ export function Usage({
// The SaaS session has lapsed and needs a re-sign-in (self-hosted only).
const [sessionExpired, setSessionExpired] = useState(false);
const [refreshKey, setRefreshKey] = useState(0);
+ const previousDeal = useRef(procurement.data);
+ useEffect(() => {
+ const previous = previousDeal.current;
+ previousDeal.current = procurement.data;
+ if (!previous || previous === procurement.data) return;
+ // A trial or agreement can change entitlements while the buyer stays on this page.
+ let cancelled = false;
+ void refreshWalletCache()
+ .catch(() => {})
+ .then(() => {
+ if (!cancelled) setRefreshKey((key) => key + 1);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [procurement.data]);
// From fleet-stats, not the wallet. Null when the backend cannot compute it, which omits the row.
const { data: fleetStats } = useFleetStats();
const editorsDeployed = fleetStats?.editorsDeployed ?? null;
@@ -150,6 +219,13 @@ export function Usage({
}, [refreshKey, onWalletLoaded, t]);
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
+ const refreshAfterLicense = useCallback(() => {
+ void refreshWalletCache()
+ .catch(() => {})
+ .then(() => {
+ if (mounted.current) refresh();
+ });
+ }, [refresh]);
const onInvoicesEmpty = useCallback(() => setHasInvoices(false), []);
// The same flow the settings plan section uses, so there is one purchase implementation.
@@ -210,11 +286,32 @@ export function Usage({
wallet={wallet}
serverPlan={serverPlan}
serverPlanAction={serverPlanAction}
- licenseSection={renderLicenseSection?.(refresh)}
loading={loading}
pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}
notices={
<>
+ {procurement.loadError && (
+ <Banner
+ tone="danger"
+ title={t("portal.procurement.error.title")}
+ action={
+ <Button size="sm" onClick={procurement.retry}>
+ {t("portal.accountLink.gate.retry", "Try again")}
+ </Button>
+ }
+ >
+ {procurement.loadError}
+ </Banner>
+ )}
+ {procurement.error && !procurement.open && (
+ <Banner
+ tone="danger"
+ title={t("portal.procurement.error.title")}
+ onDismiss={() => procurement.setError(null)}
+ >
+ {procurement.error}
+ </Banner>
+ )}
{sessionExpired && (
<Banner
tone="warning"
@@ -257,6 +354,7 @@ export function Usage({
</>
}
editorsDeployed={editorsDeployed}
+ licenseSection={renderLicenseSection?.(refreshAfterLicense)}
onAddCapacity={
checkout && wallet?.role === "leader" ? addCapacity : undefined
}
@@ -264,9 +362,19 @@ export function Usage({
!enterpriseProcessor &&
wallet?.role === "leader" &&
!wallet?.processor?.active
- ? () => setActivationStep("choose")
+ ? () =>
+ setActivationStep(
+ bundleFlow.status === "none" ? "choose" : "prepay",
+ )
: undefined
}
+ activateLabel={
+ bundleFlow.status === "invoice"
+ ? t("portal.billing.freePlan.payInvoice", "Pay invoice to complete")
+ : bundleFlow.status === "quote"
+ ? t("portal.billing.freePlan.viewQuote", "View quote")
+ : undefined
+ }
onGovernSpend={
!enterpriseProcessor &&
wallet?.role === "leader" &&
@@ -274,7 +382,23 @@ export function Usage({
? () => setAdjustingLimit(true)
: undefined
}
- onEnterpriseQuote={onEnterpriseQuote}
+ procurementSection={
+ procurement.isLinked && procurement.started ? (
+ <ControlledDealStatusHero
+ controller={procurement}
+ readOnly={!canManageProcurement}
+ />
+ ) : undefined
+ }
+ onEnterpriseQuote={
+ canManageProcurement &&
+ procurement.isLinked &&
+ !procurement.loading &&
+ !procurement.loadError &&
+ !procurement.started
+ ? procurement.onExploreEnterprise
+ : undefined
+ }
paymentSection={
paying && wallet ? (
<PaymentSection
@@ -292,12 +416,14 @@ export function Usage({
}
extras={
<>
+ {canManageProcurement && <ProcurementFlow controller={procurement} />}
{!enterpriseProcessor && wallet && wallet.status === "free" && (
<FreePlanView
wallet={wallet}
step={activationStep}
onStepChange={setActivationStep}
onSubscribed={confirmSubscription}
+ onActivationClosed={bundleFlow.refresh}
/>
)}
diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx
index 06bd264a69..f9ac2d9edc 100644
--- a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx
+++ b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx
@@ -1,8 +1,13 @@
+import { ManageBillingButton } from "@app/components/shared/ManageBillingButton";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { BillingScreen } from "@app/billing/BillingScreen";
import { KvRow } from "@app/billing/KvRow";
import { InvoiceRow } from "@app/billing/InvoiceRow";
import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";
+import { AppConfigProvider } from "@app/contexts/AppConfigContext";
+import { LicenseProvider } from "@app/contexts/LicenseContext";
+import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";
+import { http, HttpResponse } from "msw";
const meta: Meta<typeof BillingScreen> = {
title: "Billing/BillingScreen",
@@ -13,6 +18,130 @@ const meta: Meta<typeof BillingScreen> = {
export default meta;
type Story = StoryObj<typeof BillingScreen>;
+export const SelfHostedLicense: Story = {
+ args: {
+ wallet: freeWallet,
+ selfHosted: true,
+ paymentSection: (
+ <KvRow
+ label="Payment method"
+ value="No card on file"
+ door={<button type="button">Update</button>}
+ />
+ ),
+ licenseSection: <ServerLicenseSection onSaved={() => {}} />,
+ },
+ decorators: [
+ (Story) => (
+ <AppConfigProvider
+ autoFetch={false}
+ initialConfig={{ isAdmin: true, enableLogin: true }}
+ >
+ <LicenseProvider>
+ <Story />
+ </LicenseProvider>
+ </AppConfigProvider>
+ ),
+ ],
+ parameters: {
+ msw: {
+ handlers: [
+ http.get("*/api/v1/admin/license-info", () =>
+ HttpResponse.json({
+ licenseType: "NORMAL",
+ enabled: false,
+ maxUsers: 5,
+ licenseKey: "00000000-0000-0000-0000-000000000000",
+ }),
+ ),
+ http.post("*/api/v1/admin/license-key", () =>
+ HttpResponse.json({ success: true }),
+ ),
+ http.post("*/api/v1/admin/license-file", () =>
+ HttpResponse.json({ success: true }),
+ ),
+ ],
+ },
+ },
+};
+
+export const SelfHostedLicenseDark: Story = {
+ ...SelfHostedLicense,
+ globals: { theme: "dark" },
+};
+
+export const SelfHostedInstalledLicense: Story = {
+ ...SelfHostedLicense,
+ args: {
+ ...SelfHostedLicense.args,
+ serverPlan: { licenseType: "ENTERPRISE", maxUsers: 100, usersInUse: 1 },
+ serverPlanAction: <ManageBillingButton />,
+ onActivateProcessor: () => {},
+ },
+ parameters: {
+ msw: {
+ handlers: [
+ http.get("*/api/v1/admin/license-info", () =>
+ HttpResponse.json({
+ licenseType: "ENTERPRISE",
+ enabled: true,
+ maxUsers: 100,
+ licenseKey: "11111111-2222-3333-4444-555555555555",
+ }),
+ ),
+ http.post("*/api/v1/admin/license-key", () =>
+ HttpResponse.json({ success: true }),
+ ),
+ http.post("*/api/v1/admin/license-file", () =>
+ HttpResponse.json({ success: true }),
+ ),
+ ],
+ },
+ },
+};
+
+export const SelfHostedCertificate: Story = {
+ ...SelfHostedInstalledLicense,
+ parameters: {
+ msw: {
+ handlers: [
+ http.get("*/api/v1/admin/license-info", () =>
+ HttpResponse.json({
+ licenseType: "ENTERPRISE",
+ enabled: true,
+ maxUsers: 100,
+ licenseKey: "file:/licenses/enterprise.lic",
+ }),
+ ),
+ ],
+ },
+ },
+};
+
+export const SelfHostedLongCertificate: Story = {
+ ...SelfHostedCertificate,
+ render: (args) => (
+ <div style={{ maxWidth: 375 }}>
+ <BillingScreen {...args} />
+ </div>
+ ),
+ parameters: {
+ msw: {
+ handlers: [
+ http.get("*/api/v1/admin/license-info", () =>
+ HttpResponse.json({
+ licenseType: "ENTERPRISE",
+ enabled: true,
+ maxUsers: 100,
+ licenseKey:
+ "file:/licenses/01a09086ef667363b2d99f773dc4755aenterprise.lic",
+ }),
+ ),
+ ],
+ },
+ },
+};
+
/** Stand-ins for the host's sections, so the chip row and section rhythm can be reviewed. */
const payment = (
<>
diff --git a/frontend/editor/src/proprietary/routes/adminRouteExtensions.tsx b/frontend/editor/src/proprietary/routes/adminRouteExtensions.tsx
index a422376086..8603685d42 100644
--- a/frontend/editor/src/proprietary/routes/adminRouteExtensions.tsx
+++ b/frontend/editor/src/proprietary/routes/adminRouteExtensions.tsx
@@ -11,6 +11,14 @@ const PortalApp = HAS_PORTAL
})
: null;
+const ProcurementRedirect = HAS_PORTAL
+ ? lazy(async () => {
+ const m =
+ await import("@portal/components/procurement/ProcurementRedirect");
+ return { default: m.ProcurementRedirect };
+ })
+ : null;
+
/**
* Return leg of the account-link handshake, which Stirling redirects to with the admin's session in the URL fragment.
*/
@@ -23,8 +31,13 @@ const ConnectCallback = HAS_PORTAL
/** The portal mounts as an admin-only route-set at PORTAL_BASENAME (/processor/*). */
export function getAdminRouteExtensions(): ReactElement[] {
- if (!PortalApp || !ConnectCallback) return [];
+ if (!PortalApp || !ConnectCallback || !ProcurementRedirect) return [];
return [
+ <Route
+ key="procurement"
+ path="/procurement"
+ element={<ProcurementRedirect />}
+ />,
<Route
key="portal"
path={`${PORTAL_BASENAME}/*`}
diff --git a/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx b/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx
index 7dd8bfaa02..23d525ea11 100644
--- a/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx
+++ b/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx
@@ -53,7 +53,7 @@ beforeEach(() => {
describe("AuthCallback destination", () => {
it("prefers an explicit next over anything remembered", async () => {
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
await arriveAtCallback("?next=%2Fprocessor%2Fusers");
expect(landedOn()).toBe("/processor/users");
});
@@ -65,15 +65,15 @@ describe("AuthCallback destination", () => {
it("prefers a pending connect request over a remembered destination", async () => {
rememberPendingConnect("req-1");
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
await arriveAtCallback();
expect(landedOn()).toBe("/link?request=req-1");
});
it("uses a remembered destination when the URL carries nothing", async () => {
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
await arriveAtCallback();
- expect(landedOn()).toBe("/processor/procurement");
+ expect(landedOn()).toBe("/procurement");
});
it("falls back to the role-based landing when nothing is remembered", async () => {
@@ -87,7 +87,7 @@ describe("AuthCallback destination", () => {
});
it("claims the remembered destination even when an explicit next wins", async () => {
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
await arriveAtCallback("?next=%2Fprocessor%2Fusers");
expect(landedOn()).toBe("/processor/users");
@@ -99,7 +99,7 @@ describe("AuthCallback destination", () => {
it("claims it even when a pending connect request wins", async () => {
rememberPendingConnect("req-1");
- rememberPendingDestination("/processor/procurement");
+ rememberPendingDestination("/procurement");
await arriveAtCallback();
expect(landedOn()).toBe("/link?request=req-1");
diff --git a/frontend/editor/vite.config.ts b/frontend/editor/vite.config.ts
index 569cd66807..cb9772e424 100644
--- a/frontend/editor/vite.config.ts
+++ b/frontend/editor/vite.config.ts
@@ -271,6 +271,10 @@ export default defineConfig(async ({ mode, command }) => {
"node_modules",
`.vite-${effectiveMode}`,
),
+ resolve: {
+ // Linked workspace dependencies must share the renderer's React instance.
+ dedupe: ["react", "react-dom"],
+ },
define: {
__DEV_WORKTREE_LABEL__: JSON.stringify(devWorktreeLabel),
},