#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Use Stripe currencies consistently in checkout and prepay (#8051)
ConnorYoh2d057b831662
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 373c1ad94d..9119b96fbf 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -6630,9 +6630,11 @@ title = "Adjust Team plan"[payment.capacityStage]adjustmentNote = "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available."continue = "Continue to payment"+currencyAtCheckout = "Stripe confirms the final amount and payment currency at checkout."customLabel = "Number of users"dueToday = "Due today"enterpriseQuote = "Get an enterprise quote"+estimatedTotal = "Estimated total"lineItem = "Team · {{price}}{{period}} per {{block}} users"minimumForCurrentUsers = "You have {{users}} users, so the plan must cover at least {{minimum}}."modalTitle = "Upgrade to {{planName}}"@@ -7727,6 +7729,8 @@ payTitle = "Pay for your year"step = "Step {{current}} of {{total}}"[portal.billing.prepaid.calc]+currency = "Quote currency"+currencyLocked = "Uses your existing Stripe billing currency."rateUnknown = "We'll show the exact price at checkout."[portal.billing.prepaid.consent]diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/StripeCheckoutPanel.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/StripeCheckoutPanel.tsxindex 03584f11de..aff3b8ee94 100644--- a/frontend/editor/src/cloud/components/shared/config/configSections/StripeCheckoutPanel.tsx+++ b/frontend/editor/src/cloud/components/shared/config/configSections/StripeCheckoutPanel.tsx@@ -89,7 +89,7 @@ export interface StripeCheckoutPanelProps {* other than via this hint).*/teamId: number;- /** Currency lower-case 3-letter ISO (e.g. {@code "gbp"}). Selects the Stripe Price. */+ /** Display currency; Stripe resolves the customer's payment currency. */currency?: string;/** Cap in USD; null means no cap. Tracked locally; set on the wallet via PATCH after subscription. */capUsd: number | null;@@ -114,7 +114,7 @@ function getStripe(publishableKey: string): Promise<Stripe | null> {const StripeCheckoutPanel: React.FC<StripeCheckoutPanelProps> = ({teamId,- currency = "gbp",+ currency = "usd",// capUsd is part of the props contract but intentionally unused here — the cap is set// application-side via PATCH /payg/cap after the subscription lands, not during checkout.onComplete,diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsxindex f9732ca641..3bd7355ab0 100644--- a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsx+++ b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsx@@ -420,7 +420,7 @@ function CheckoutStep({><StripeCheckoutPanelteamId={teamId}- currency={currency?.toLowerCase() ?? "gbp"}+ currency={currency?.toLowerCase() ?? "usd"}capUsd={effectiveCap}onComplete={onComplete}/>diff --git a/frontend/editor/src/cloud/services/billing.ts b/frontend/editor/src/cloud/services/billing.tsindex 7f049cd540..cf7989a6d5 100644--- a/frontend/editor/src/cloud/services/billing.ts+++ b/frontend/editor/src/cloud/services/billing.ts@@ -21,7 +21,7 @@export interface CheckoutParams {/** The caller's team id. Required — scopes the PAYG subscription. */teamId: number;- /** Lower-case 3-letter ISO currency (e.g. {@code "gbp"}). Selects the Stripe Price. */+ /** Billing display currency; Stripe selects the checkout payment currency. */currency?: string;/** Billing email for the Checkout Session; maps to Stripe {@code customer_email} when the team has no customer yet. */billingOwnerEmail?: string | null;diff --git a/frontend/editor/src/desktop/services/billing.ts b/frontend/editor/src/desktop/services/billing.tsindex 5ff0cb0e4d..954273b930 100644--- a/frontend/editor/src/desktop/services/billing.ts+++ b/frontend/editor/src/desktop/services/billing.ts@@ -64,7 +64,7 @@ export async function createCheckoutSession(headers: { Authorization: `Bearer ${token}` },body: {team_id: params.teamId,- currency: params.currency ?? "gbp",+ currency: params.currency ?? "usd",success_url: DESKTOP_BILLING_RETURN_URL,cancel_url: DESKTOP_BILLING_RETURN_URL,...(params.billingOwnerEmaildiff --git a/frontend/editor/src/portal/billing/sharedBillingFormat.test.ts b/frontend/editor/src/portal/billing/sharedBillingFormat.test.tsindex 03c0998e34..fd0bf41513 100644--- a/frontend/editor/src/portal/billing/sharedBillingFormat.test.ts+++ b/frontend/editor/src/portal/billing/sharedBillingFormat.test.ts@@ -77,6 +77,17 @@ describe("currencySymbol", () => {});describe("formatMinor", () => {+ it.each([+ [1200, "jpy", "JPY 1,200"],+ [1200, "krw", "KRW 1,200"],+ [1200, "cad", "CAD 12.00"],+ [1200, "isk", "ISK 12.00"],+ [1200, "ugx", "UGX 12.00"],+ [1200, "mga", "MGA 1,200"],+ ])("formats %s minor units in %s as %s", (amount, currency, expected) => {+ expect(formatMinor(amount, currency)).toBe(expected);+ });+it("formats whole and fractional cents", () => {expect(formatMinor(224, "usd")).toContain("2.24");expect(formatMinor(5, "usd")).toContain("0.05");diff --git a/frontend/editor/src/portal/billing/stripe.test.ts b/frontend/editor/src/portal/billing/stripe.test.tsindex 0322793101..672658149a 100644--- a/frontend/editor/src/portal/billing/stripe.test.ts+++ b/frontend/editor/src/portal/billing/stripe.test.ts@@ -26,6 +26,8 @@ import {createCheckoutSession,createPortalSession,fetchBundleQuotePdf,+ fetchBundlePricing,+ fetchCheckoutPricing,finalizeBundleInvoice,getLatestBundleQuote,StripeFunctionError,@@ -430,3 +432,173 @@ describe("createPortalSession", () => {).rejects.toBeInstanceOf(StripeFunctionError);});});++it("reads Stripe's billing currency and fractional credit rate before prepay", async () => {+ invoke.mockResolvedValue({+ data: { success: true, currency: "gbp", unit_amount_minor: 0.75 },+ error: null,+ });+ expect(await fetchBundlePricing(42)).toEqual({+ currency: "gbp",+ unitAmountMinor: 0.75,+ availableCurrencies: ["gbp"],+ currencyLocked: true,+ });+ expect(invoke).toHaveBeenCalledWith("create-payg-bundle-quote", {+ body: { team_id: 42, preview: true },+ headers: { Authorization: "Bearer billing-token" },+ });+});++it.each([+ { currency: "GBP" },+ { currency: "not-a-currency" },+ { currency: ["usd"] },+ { currency: 123 },+ { available_currencies: "usd" },+ { available_currencies: {} },+ { available_currencies: ["usd", "GBP"] },+ { available_currencies: ["usd", null] },+ { available_currencies: [["usd"]] },+ { unit_amount_minor: "1" },+ { unit_amount_minor: 0 },+ { unit_amount_minor: Infinity },+])("rejects malformed bundle pricing: %j", async (invalidFields) => {+ invoke.mockResolvedValue({+ data: {+ success: true,+ currency: "usd",+ unit_amount_minor: 1,+ ...invalidFields,+ },+ error: null,+ });+ await expect(fetchBundlePricing(42)).rejects.toThrow(+ "Bundle pricing is unavailable.",+ );+});++it("requests a chosen quote currency without setting a Checkout currency", async () => {+ invoke.mockResolvedValue({+ data: {+ success: true,+ currency: "eur",+ unit_amount_minor: 0.9,+ available_currencies: ["usd", "eur"],+ currency_locked: false,+ },+ error: null,+ });+ expect(await fetchBundlePricing(42, "eur")).toEqual({+ currency: "eur",+ unitAmountMinor: 0.9,+ availableCurrencies: ["usd", "eur"],+ currencyLocked: false,+ });+ expect(invoke).toHaveBeenCalledWith("create-payg-bundle-quote", {+ body: { team_id: 42, preview: true, currency: "eur" },+ headers: { Authorization: "Bearer billing-token" },+ });+});++it("uses the minted quote's currency and total instead of the estimate", async () => {+ invoke.mockResolvedValue({+ data: {+ success: true,+ stripe_quote_id: "qt_1",+ currency: "gbp",+ amount_subtotal: 12000,+ amount_total: 10000,+ },+ error: null,+ });+ expect(+ await createBundleStripeQuote({ teamId: 42, quoteId: 7 }),+ ).toMatchObject({+ currency: "gbp",+ amountSubtotal: 12000,+ amountTotal: 10000,+ });+});++it("shows Stripe's error details when a quote request fails", async () => {+ invoke.mockResolvedValue({+ data: null,+ error: {+ message: "Edge Function returned a non-2xx status code",+ context: new Response(+ JSON.stringify({+ error: "quote_creation_failed",+ stripe_error: "Currency mismatch",+ }),+ { status: 500 },+ ),+ },+ });+ await expect(+ createBundleStripeQuote({ teamId: 42, quoteId: 7 }),+ ).rejects.toMatchObject({+ code: "quote_creation_failed",+ message: "Currency mismatch",+ });+});++describe("checkout pricing preview", () => {+ beforeEach(() => {+ localStorage.clear();+ vi.stubGlobal("navigator", { languages: ["en-GB"] });+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ localStorage.clear();+ });+ it.each([+ [null, "gbp"],+ ["aud", "aud"],+ ])(+ "uses browser detection unless a manual preference exists (%s)",+ async (manual, expected) => {+ if (manual) localStorage.setItem("explicitPricingCurrency", manual);+ invoke.mockResolvedValue({+ data: {+ success: true,+ currency: expected,+ currency_locked: false,+ unit_amount_minor: 2,+ },+ error: null,+ });+ expect(await fetchCheckoutPricing(42, "processor")).toEqual({+ currency: expected,+ currencyLocked: false,+ unitAmountMinor: 2,+ });+ expect(invoke).toHaveBeenCalledWith(+ "create-checkout-session",+ expect.objectContaining({+ body: { team_id: 42, preview: "processor", currency: expected },+ }),+ );+ },+ );+ it("accepts the customer's confirmed currency over browser and manual preference", async () => {+ localStorage.setItem("explicitPricingCurrency", "aud");+ invoke.mockResolvedValue({+ data: { success: true, currency: "usd", currency_locked: true },+ error: null,+ });+ expect(await fetchCheckoutPricing(42, "currency")).toMatchObject({+ currency: "usd",+ currencyLocked: true,+ });+ });+ it("rejects a malformed rate instead of substituting the USD wallet rate", async () => {+ invoke.mockResolvedValue({+ data: { success: true, currency: "gbp", currency_locked: false },+ error: null,+ });+ await expect(fetchCheckoutPricing(42, "processor")).rejects.toThrow(+ "Couldn't load checkout pricing",+ );+ });+});diff --git a/frontend/editor/src/portal/billing/stripe.ts b/frontend/editor/src/portal/billing/stripe.tsindex 39bbd0ed74..e6a130c7c9 100644--- a/frontend/editor/src/portal/billing/stripe.ts+++ b/frontend/editor/src/portal/billing/stripe.ts@@ -5,6 +5,7 @@ import {} from "@app/portal/auth/sessionClient";import { invokeSaasFunction } from "@app/portal/auth/saasFunctions";import { withPortalSaasSession } from "@app/portal/auth/portalSaasSession";+import { getPreferredCurrency } from "@app/utils/currencyDetection";/*** Stripe checkout + portal sessions, minted via the SaaS Supabase edge@@ -24,8 +25,47 @@ export class StripeFunctionError extends Error {}}-/** Currencies the SaaS PAYG offering supports. Default for new checkouts is "usd". */-export type SaasCurrency = "usd" | "eur" | "gbp";+/** Lower-case ISO currency; Stripe determines availability for the customer and price. */+export type SaasCurrency = string;++export interface CheckoutPricing {+ currency: string;+ currencyLocked: boolean;+ unitAmountMinor?: number;+}++/** Resolves customer currency before preferences; Processor rates come from its pricing policy. */+export async function fetchCheckoutPricing(+ teamId: number,+ preview: "currency" | "processor",+ currency = getPreferredCurrency(),+): Promise<CheckoutPricing> {+ const result = await invoke<{+ success: boolean;+ currency: string;+ currency_locked: boolean;+ unit_amount_minor?: number;+ error?: string;+ }>("create-checkout-session", { team_id: teamId, preview, currency }, true);+ if (+ !result.success ||+ !/^[a-z]{3}$/.test(result.currency) ||+ typeof result.currency_locked !== "boolean" ||+ (preview === "processor" &&+ (typeof result.unit_amount_minor !== "number" ||+ !Number.isFinite(result.unit_amount_minor) ||+ result.unit_amount_minor < 0))+ ) {+ throw new StripeFunctionError(+ result.error ?? "Couldn't load checkout pricing.",+ );+ }+ return {+ currency: result.currency,+ currencyLocked: result.currency_locked,+ unitAmountMinor: result.unit_amount_minor,+ };+}interface CheckoutSessionRequest {teamId: number;@@ -70,6 +110,7 @@ interface PortalResponse {async function invoke<T>(name: string,body: Record<string, unknown>,+ readOnly = false,): Promise<T> {ensurePortalSessionClient();const supabase = getPortalSessionClient();@@ -79,11 +120,31 @@ async function invoke<T>("unconfigured",);}- const { data, error } = await invokeSaasFunction<T>(name, { body });+ const { data, error } = await invokeSaasFunction<T>(name, { body }, readOnly);if (error) {- throw new StripeFunctionError(- error.message ?? `Edge function ${name} failed`,- );+ let message = error.message ?? `Edge function ${name} failed`;+ let code: string | undefined;+ if (error.context instanceof Response) {+ try {+ const details: unknown = await error.context.clone().json();+ if (details && typeof details === "object") {+ if ("error" in details && typeof details.error === "string") {+ code = details.error;+ message = details.error;+ }+ if ("message" in details && typeof details.message === "string")+ message = details.message;+ if (+ "stripe_error" in details &&+ typeof details.stripe_error === "string"+ )+ message = details.stripe_error;+ }+ } catch {+ // Gateway failures may not return JSON.+ }+ }+ throw new StripeFunctionError(message, code);}if (data == null) {throw new StripeFunctionError(`Edge function ${name} returned no data`);@@ -316,10 +377,62 @@ export async function createCheckoutSession(};}+export interface BundlePricing {+ currency: string;+ unitAmountMinor: number;+ availableCurrencies: string[];+ currencyLocked: boolean;+}++/** Reads the customer's billing currency and configured rate without creating a quote. */+export async function fetchBundlePricing(+ teamId: number,+ currency?: string,+): Promise<BundlePricing> {+ const res = await invoke<{+ success?: boolean;+ currency?: string;+ unit_amount_minor?: number;+ available_currencies?: string[];+ currency_locked?: boolean;+ error?: string;+ }>("create-payg-bundle-quote", {+ team_id: teamId,+ preview: true,+ ...(currency ? { currency } : {}),+ });+ if (+ !res.success ||+ typeof res.currency !== "string" ||+ !/^[a-z]{3}$/.test(res.currency) ||+ (res.available_currencies != null &&+ (!Array.isArray(res.available_currencies) ||+ !res.available_currencies.every(+ (value) => typeof value === "string" && /^[a-z]{3}$/.test(value),+ ))) ||+ res.unit_amount_minor == null ||+ !Number.isFinite(res.unit_amount_minor) ||+ res.unit_amount_minor <= 0+ ) {+ throw new StripeFunctionError(+ res.error ?? "Bundle pricing is unavailable.",+ );+ }+ return {+ currency: res.currency,+ unitAmountMinor: res.unit_amount_minor,+ availableCurrencies: res.available_currencies ?? [res.currency],+ currencyLocked: res.currency_locked ?? true,+ };+}+/** Result of {@link createBundleStripeQuote} — the Stripe-issued quote handles. */export interface BundleStripeQuote {stripeQuoteId: string;stripeQuoteNumber: string | null;+ currency?: string;+ amountSubtotal?: number;+ amountTotal?: number;}interface BundleStripeQuoteRequest {@@ -333,6 +446,9 @@ interface BundleStripeQuoteRequest {}interface BundleStripeQuoteResponse {+ currency?: string;+ amount_subtotal?: number;+ amount_total?: number;success?: boolean;stripe_quote_id?: string;stripe_quote_number?: string | null;@@ -364,6 +480,13 @@ export async function createBundleStripeQuote(return {stripeQuoteId: res.stripe_quote_id,stripeQuoteNumber: res.stripe_quote_number ?? null,+ ...(res.currency+ ? {+ currency: res.currency,+ amountSubtotal: res.amount_subtotal,+ amountTotal: res.amount_total,+ }+ : {}),};}diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsxindex 07d1f2a000..f1ee7333ee 100644--- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsx+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsx@@ -1,5 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { useState } from "react";+import { http, HttpResponse } from "msw";import { Button } from "@app/ui";import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";import {@@ -8,12 +9,41 @@ import {} from "@portal/components/billing/walletFixtures";import "@portal/components/billing/billing.css";-// Direct checkout: no quote round-trip. With no Stripe key in Storybook, the pay step falls back-// to the mock card placeholder + "Complete purchase" button (no network), so no MSW handler needed.const meta: Meta<typeof BundleCheckoutModal> = {title: "Portal/Billing/BundleCheckoutModal",component: BundleCheckoutModal,- parameters: { layout: "fullscreen" },+ parameters: {+ layout: "fullscreen",+ msw: {+ handlers: [+ http.post(+ "http://saas.mock/functions/v1/create-payg-bundle-quote",+ async ({ request }) => {+ const body = (await request.json()) as { preview?: boolean };+ return HttpResponse.json(+ body.preview+ ? {+ success: true,+ currency: "usd",+ unit_amount_minor: 1,+ available_currencies: ["usd"],+ currency_locked: false,+ }+ : {+ success: true,+ stripe_quote_id: "qt_story_bundle",+ stripe_quote_number: "Q-STORY-1",+ },+ );+ },+ ),+ http.post(+ "http://saas.mock/rest/v1/rpc/payg_get_latest_bundle_quote",+ () => HttpResponse.json([]),+ ),+ ],+ },+ },};export default meta;type Story = StoryObj<typeof BundleCheckoutModal>;diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsxindex 69a78c8dd5..42e194beea 100644--- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsx+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsx@@ -34,15 +34,22 @@ vi.mock("react-i18next", () => ({function showCheckout() {return render(- <MantineProvider>+ <MantineProvider env="test"><BundleCheckoutModal open wallet={subscribedWallet} onClose={() => {}} /></MantineProvider>,);}describe("annual credit purchases", () => {+ let restoreLanguages: () => void;beforeEach(() => {vi.clearAllMocks();+ const languages = vi+ .spyOn(navigator, "languages", "get")+ .mockReturnValue(["en-US"]);+ restoreLanguages = () => languages.mockRestore();+ localStorage.clear();+ HTMLElement.prototype.scrollIntoView = vi.fn();sessionStorage.clear();api.getLatestBundleQuote.mockResolvedValue(null);api.fetchBundlePricing.mockResolvedValue({@@ -65,7 +72,163 @@ describe("annual credit purchases", () => {stripeQuoteNumber: "Q-7",});});- afterEach(cleanup);+ afterEach(() => {+ cleanup();+ restoreLanguages();+ });++ it.each([+ {+ locked: false,+ currencies: ["usd", "gbp"],+ saved: false,+ expected: "GBP",+ },+ { locked: true, currencies: ["usd"], saved: false, expected: "USD" },+ { locked: false, currencies: ["usd"], saved: false, expected: "USD" },+ { locked: false, currencies: ["usd", "gbp"], saved: true, expected: "USD" },+ ])(+ "defaults UK browsers to $expected (locked=$locked, saved=$saved, available=$currencies)",+ async ({ locked, currencies, saved, expected }) => {+ vi.spyOn(navigator, "languages", "get").mockReturnValue(["en-GB"]);+ api.fetchBundlePricing.mockImplementation(+ async (_teamId: number, currency = "usd") => ({+ currency,+ unitAmountMinor: 1,+ currencyLocked: locked,+ availableCurrencies: currencies,+ }),+ );+ if (saved) {+ api.getLatestBundleQuote.mockResolvedValue({+ quoteId: 7,+ users: null,+ posturePolicies: 1,+ sizeMult: 1,+ pipelineMult: 1,+ poolCredits: 1_200_000,+ priceMinor: 1_000_000,+ currency: "usd",+ consentedAt: null,+ stripeQuoteId: "qt_saved",+ stripeQuoteNumber: "Q-7",+ stripeRef: null,+ validUntil: "2027-01-01",+ } satisfies LatestBundleQuote);+ }+ showCheckout();+ expect(+ await screen.findByRole("textbox", { name: "Quote currency" }),+ ).toHaveValue(expected);+ expect(+ screen.getByText(expected === "GBP" ? "£10,000.00" : "$10,000.00"),+ ).toBeInTheDocument();+ expect(api.fetchBundlePricing).toHaveBeenCalledTimes(+ expected === "GBP" ? 2 : 1,+ );+ if (expected === "GBP") {+ expect(api.fetchBundlePricing).toHaveBeenLastCalledWith(42, "gbp");+ }+ },+ );++ it("blocks new quotes when saved-quote lookup fails and resumes the existing quote after reopening", async () => {+ api.getLatestBundleQuote.mockRejectedValueOnce(+ new Error("Could not load saved quote"),+ );+ const view = showCheckout();+ expect(+ await screen.findByText("Could not load saved quote"),+ ).toBeInTheDocument();+ const continueButton = screen.getByRole("button", {+ name: "Continue to payment",+ });+ const downloadButton = screen.getByRole("button", {+ name: "Download quote (PDF)",+ });+ expect(continueButton).toBeDisabled();+ expect(downloadButton).toBeDisabled();+ fireEvent.click(continueButton);+ fireEvent.click(downloadButton);+ expect(api.upsertBundleQuote).not.toHaveBeenCalled();+ expect(api.createBundleStripeQuote).not.toHaveBeenCalled();+ expect(sessionStorage.getItem("payg-bundle-calc:42")).toBeNull();++ api.getLatestBundleQuote.mockResolvedValue({+ quoteId: 7,+ users: null,+ posturePolicies: 1,+ sizeMult: 1,+ pipelineMult: 1,+ poolCredits: 1_200_000,+ priceMinor: 1_000_000,+ currency: "usd",+ consentedAt: null,+ stripeQuoteId: "qt_saved",+ stripeQuoteNumber: "Q-7",+ stripeRef: null,+ validUntil: "2027-01-01",+ } satisfies LatestBundleQuote);+ view.rerender(+ <MantineProvider env="test">+ <BundleCheckoutModal+ open={false}+ wallet={subscribedWallet}+ onClose={() => {}}+ />+ </MantineProvider>,+ );+ view.rerender(+ <MantineProvider env="test">+ <BundleCheckoutModal+ open+ wallet={subscribedWallet}+ onClose={() => {}}+ />+ </MantineProvider>,+ );+ await screen.findByText("$10,000.00");+ expect(+ screen.queryByText("Could not load saved quote"),+ ).not.toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.getLatestBundleQuote).toHaveBeenCalledTimes(2);+ expect(api.upsertBundleQuote).not.toHaveBeenCalled();+ expect(api.createBundleStripeQuote).not.toHaveBeenCalled();+ });++ it("remembers a manual currency selection ahead of browser detection", async () => {+ vi.spyOn(navigator, "languages", "get").mockReturnValue(["en-GB"]);+ api.fetchBundlePricing.mockImplementation(+ async (_teamId: number, currency = "usd") => ({+ currency,+ unitAmountMinor: 1,+ currencyLocked: false,+ availableCurrencies: ["usd", "gbp"],+ }),+ );+ const view = showCheckout();+ expect(+ await screen.findByRole("textbox", { name: "Quote currency" }),+ ).toHaveValue("GBP");+ fireEvent.click(screen.getByRole("textbox", { name: "Quote currency" }));+ fireEvent.click(await screen.findByRole("option", { name: "USD" }));+ await waitFor(() =>+ expect(+ screen.getByRole("textbox", { name: "Quote currency" }),+ ).toHaveValue("USD"),+ );+ view.unmount();+ api.fetchBundlePricing.mockClear();+ showCheckout();+ expect(+ await screen.findByRole("textbox", { name: "Quote currency" }),+ ).toHaveValue("USD");+ expect(api.fetchBundlePricing).toHaveBeenCalledTimes(1);+ });it("quotes the chosen credit pool independently of Team seats, without accepting it", async () => {showCheckout();@@ -108,6 +271,127 @@ describe("annual credit purchases", () => {expect(api.createBundleStripeQuote).toHaveBeenCalledTimes(2);});+ it("uses Stripe pricing currency for the spend picker and new quote", async () => {+ api.fetchBundlePricing.mockResolvedValue({+ currency: "gbp",+ unitAmountMinor: 2,+ currencyLocked: true,+ availableCurrencies: ["gbp"],+ });+ showCheckout();+ fireEvent.click(await screen.findByRole("button", { name: "£12,000" }));+ expect(+ screen.getByRole("textbox", { name: "Quote currency" }),+ ).toBeDisabled();+ expect(screen.getByText("£10,000.00")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({+ currency: "gbp",+ poolCredits: 600_000,+ priceMinor: 1_000_000,+ }),+ );+ });++ it.each([+ {+ currency: "jpy",+ initialAmount: "JPY 1200000",+ total: "JPY 10,000",+ customAmount: "12345",+ poolCredits: 12_345,+ priceMinor: 10_287,+ },+ {+ currency: "kwd",+ initialAmount: "KWD 1200",+ total: "KWD 10,000.000",+ customAmount: "12345.678",+ poolCredits: 12_345_678,+ priceMinor: 10_288_065,+ },+ ])(+ "uses $currency units for preset and custom spend amounts",+ async ({+ currency,+ initialAmount,+ total,+ customAmount,+ poolCredits,+ priceMinor,+ }) => {+ api.fetchBundlePricing.mockResolvedValue({+ currency,+ unitAmountMinor: 1,+ currencyLocked: true,+ availableCurrencies: [currency],+ });+ showCheckout();+ expect(+ await screen.findByRole("textbox", { name: "Year size" }),+ ).toHaveValue(initialAmount);+ fireEvent.click(+ screen.getByRole("button", {+ name: `${currency.toUpperCase()} 12,000`,+ }),+ );+ expect(screen.getByText(total)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Other" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Year size" }), {+ target: { value: customAmount },+ });+ expect(screen.getByRole("textbox", { name: "Year size" })).toHaveValue(+ `${currency.toUpperCase()} ${customAmount}`,+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({ currency, poolCredits, priceMinor }),+ );+ },+ );++ it("refreshes the custom spend amount when the quote currency changes", async () => {+ api.fetchBundlePricing.mockResolvedValue({+ currency: "usd",+ unitAmountMinor: 1,+ currencyLocked: false,+ availableCurrencies: ["usd", "gbp"],+ });+ showCheckout();+ fireEvent.click(await screen.findByRole("button", { name: "Other" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Year size" }), {+ target: { value: "7654.32" },+ });+ api.fetchBundlePricing.mockResolvedValue({+ currency: "gbp",+ unitAmountMinor: 2,+ currencyLocked: false,+ availableCurrencies: ["usd", "gbp"],+ });+ fireEvent.click(screen.getByRole("textbox", { name: "Quote currency" }));+ fireEvent.click(await screen.findByRole("option", { name: "GBP" }));+ await waitFor(() =>+ expect(screen.getByRole("textbox", { name: "Year size" })).toHaveValue(+ "£15308.64",+ ),+ );+ expect(api.fetchBundlePricing).toHaveBeenLastCalledWith(42, "gbp");+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({ currency: "gbp", poolCredits: 765_432 }),+ );+ });+it("resumes an old quote's exact pool, amount and currency even if the wallet rate changed", async () => {const latest: LatestBundleQuote = {quoteId: 7,diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsxindex 9eaca9d0d4..a007532211 100644--- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx@@ -8,6 +8,7 @@ import {Input,Modal,NumberInput,+ Select,Skeleton,} from "@app/ui";import {@@ -22,12 +23,19 @@ import {formatMoneyMajor,currencySymbol,} from "@app/billing";-import type { Wallet } from "@portal/api/billing";+import type { Wallet } from "@app/portal/api/billing";+import { stripeMinorUnitScale } from "@app/utils/stripeCurrency";+import {+ getPreferredCurrency,+ setCachedCurrency,+} from "@app/utils/currencyDetection";import {acceptBundleStripeQuote,cancelBundleQuote,createBundleStripeQuote,fetchBundleQuotePdf,+ fetchBundlePricing,+ type BundlePricing,finalizeBundleInvoice,getLatestBundleQuote,StripeFunctionError,@@ -35,9 +43,8 @@ import {type BundleInvoice,type BundleQuote,type BundleStripeQuote,- type LatestBundleQuote,-} from "@portal/billing/stripe";-import "@portal/theme/surface.css";+} from "@app/portal/billing/stripe";+import "@app/portal/theme/surface.css";const DEFAULT_POOL_CREDITS = 1_200_000;const DEFAULT_USERS = 25;@@ -197,7 +204,7 @@ interface Props {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. */+ /** Identifies the team and whether this is a top-up. Stripe supplies pricing. */wallet: Wallet;/** Fired after a completed purchase so the parent can refetch the wallet. */onComplete?: () => void;@@ -214,10 +221,14 @@ export function BundleCheckoutModal({}: Props) {const { t } = useTranslation();const teamId = wallet.teamId;- const walletCurrency = wallet.currency ?? "usd";+ const [pricing, setPricing] = useState<BundlePricing | null>(null);+ const pricingRequest = useRef(0);+ const [persistedSubtotal, setPersistedSubtotal] = useState<number | null>(+ null,+ );// The pool is priced per size-scaled RUN at the prepaid-bundle rate (bundle:processor), NOT the// metered per-document rate — so the estimate matches the amount the checkout edge fn charges.- const ratePerRunMinor = wallet.bundleRatePerCreditMinor;+ const ratePerRunMinor = pricing?.unitAmountMinor ?? null;const [phase, setPhase] = useState<Phase>("calc");const [poolCredits, setPoolCredits] = useState(DEFAULT_POOL_CREDITS);@@ -296,8 +307,10 @@ export function BundleCheckoutModal({setStripeQuoteSig(null);setInvoice(null);setPersistedPriceMinor(null);- setPersistedPoolCredits(null);setPersistedCurrency(null);+ setPersistedSubtotal(null);+ setPricing(null);+ setPersistedPoolCredits(null);setBusy(false);setPdfBusy(false);setActionError(null);@@ -309,13 +322,43 @@ export function BundleCheckoutModal({}let cancelled = false;(async () => {- let latest: LatestBundleQuote | null;- try {- latest = await getLatestBundleQuote(teamId);- } catch {- latest = null; // no backend / not a leader — fall through to local progress- }+ const [pricingResult, quoteResult] = await Promise.allSettled([+ fetchBundlePricing(teamId),+ getLatestBundleQuote(teamId),+ ]);if (cancelled) return;+ if (quoteResult.status === "rejected") {+ const error = quoteResult.reason;+ setActionError(error instanceof Error ? error.message : String(error));+ setPricing(null);+ setResolving(false);+ return;+ }+ const latest = quoteResult.value;+ let resolvedPricing =+ pricingResult.status === "fulfilled" ? pricingResult.value : null;+ const preferredCurrency = latest?.currency ?? getPreferredCurrency();+ if (+ resolvedPricing?.currencyLocked === false &&+ preferredCurrency !== resolvedPricing.currency &&+ resolvedPricing.availableCurrencies.includes(preferredCurrency)+ ) {+ try {+ resolvedPricing = await fetchBundlePricing(teamId, preferredCurrency);+ } catch (error) {+ resolvedPricing = null;+ if (!cancelled)+ setActionError(+ error instanceof Error ? error.message : String(error),+ );+ }+ if (cancelled) return;+ }+ setPricing(resolvedPricing);+ if (pricingResult.status === "rejected" && !latest?.stripeRef) {+ const error = pricingResult.reason;+ setActionError(error instanceof Error ? error.message : String(error));+ }const saved = readCalcSettings(teamId);if (latest) {// Resume the existing quote: restore its sizing + consent + id (landing on the calculator), and@@ -327,13 +370,18 @@ export function BundleCheckoutModal({setPipelineId(pipelineIdFor(latest.pipelineMult));setConsented(latest.consentedAt != null);setQuoteId(latest.quoteId);- setPersistedPriceMinor(latest.priceMinor);+ const sameCurrency = latest.currency === resolvedPricing?.currency;+ setPersistedPriceMinor(+ (sameCurrency && latest.stripeQuoteId) || latest.stripeRef+ ? latest.priceMinor+ : null,+ );setPersistedCurrency(latest.currency);setPersistedPoolCredits(latest.poolCredits);if (saved?.poNumber) setPoNumber(saved.poNumber);if (saved?.companyName) setCompanyName(saved.companyName);if (saved?.accountName) setAccountName(saved.accountName);- if (latest.stripeQuoteId) {+ if (latest.stripeQuoteId && (sameCurrency || latest.stripeRef)) {setStripeQuote({stripeQuoteId: latest.stripeQuoteId,stripeQuoteNumber: latest.stripeQuoteNumber,@@ -382,9 +430,41 @@ export function BundleCheckoutModal({})();return () => {cancelled = true;+ pricingRequest.current += 1;};}, [open, teamId]);+ async function changeCurrency(selected: string) {+ if (+ teamId == null ||+ pricing?.currencyLocked !== false ||+ busy ||+ pdfBusy ||+ invoice+ )+ return;+ const request = ++pricingRequest.current;+ setBusy(true);+ setActionError(null);+ try {+ const next = await fetchBundlePricing(teamId, selected);+ if (request !== pricingRequest.current) return;+ setPricing(next);+ setCachedCurrency(next.currency);+ setPersistedPriceMinor(null);+ setPersistedCurrency(null);+ setPersistedSubtotal(null);+ setStripeQuote(null);+ setStripeQuoteSig(null);+ } catch (error) {+ if (request === pricingRequest.current) {+ setActionError(error instanceof Error ? error.message : String(error));+ }+ } finally {+ if (request === pricingRequest.current) setBusy(false);+ }+ }+// Persist pre-quote calculator progress so close/reload keeps the buyer's place. Held until hydration// completes so it can't clobber restored values.useEffect(() => {@@ -430,9 +510,9 @@ export function BundleCheckoutModal({}, [poolCredits, ratePerRunMinor]);const currency =- persistedPoolCredits === poolCredits- ? (persistedCurrency ?? walletCurrency)- : walletCurrency;+ persistedPriceMinor != null && persistedPoolCredits === quote.poolCredits+ ? (persistedCurrency ?? pricing?.currency ?? "usd")+ : (pricing?.currency ?? "usd");function changePool(credits: number) {const next = Number.isSafeInteger(credits) && credits > 0 ? credits : 0;@@ -441,6 +521,7 @@ export function BundleCheckoutModal({setPersistedPriceMinor(null);setPersistedPoolCredits(null);setPersistedCurrency(null);+ setPersistedSubtotal(null);setPoolCredits(next);setUsers(null);setPostureId("essentials");@@ -459,10 +540,13 @@ export function BundleCheckoutModal({return {...quote,priceMinor: persistedPriceMinor,- listMinor: null,- savingsMinor: null,+ listMinor: persistedSubtotal,+ savingsMinor:+ persistedSubtotal != null+ ? persistedSubtotal - persistedPriceMinor+ : null,};- }, [quote, persistedPriceMinor, persistedPoolCredits]);+ }, [quote, persistedPriceMinor, persistedPoolCredits, persistedSubtotal]);// Flip the loader on synchronously the moment the modal opens (React's "adjust state during render"),// so the resume runs behind a loader from the very first frame — the calculator never shows en route to@@ -476,7 +560,10 @@ export function BundleCheckoutModal({// calc → pay only needs a valid pool; consent + the account-holder name are captured on the payment// step, so they gate the commit (accept + finalize).- const canContinue = quote.poolCredits > 0 && !quote.overEnterprise;+ const canContinue =+ (pricing != null || invoice != null) &&+ quote.poolCredits > 0 &&+ !quote.overEnterprise;const nameProvided = accountName.trim().length > 0;// Once the invoice is issued, the recipient details + consent are already captured on it and the fields// are locked, so on resume Pay/Download just re-open the existing invoice — don't re-gate on the (now@@ -541,6 +628,12 @@ export function BundleCheckoutModal({poNumber: poNumber.trim() || undefined,});setStripeQuote(sq);+ if (sq.currency && sq.amountTotal != null) {+ setPersistedCurrency(sq.currency);+ setPersistedSubtotal(sq.amountSubtotal ?? null);+ setPersistedPriceMinor(sq.amountTotal);+ setPersistedPoolCredits(quote.poolCredits);+ }setStripeQuoteSig(sig);return { quoteId: q.quoteId, stripeQuote: sq };}@@ -573,9 +666,12 @@ export function BundleCheckoutModal({// returns the existing invoice, an already-finalized invoice comes back as-is. Returns the current// (simulated) invoice when there's no SaaS backend.async function acceptAndFinalize(): Promise<BundleInvoice | null> {+ if (invoiceIssued) return invoice;if (teamId == null || quoteId == null) return invoice;- await ensureQuote(); // persists consented=true (pay-step state) so accept can verify it- await acceptBundleStripeQuote({ teamId, quoteId });+ if (!invoice) {+ await ensureQuote();+ await acceptBundleStripeQuote({ teamId, quoteId });+ }const inv = await finalizeBundleInvoice({teamId,quoteId,@@ -645,7 +741,7 @@ export function BundleCheckoutModal({// Download the Stripe-rendered quote PDF. Mints the quote (if not already) — that's what makes the// PDF exist — then streams it. No SaaS backend → nothing to download.async function downloadPdf() {- if (busy || pdfBusy || quote.poolCredits <= 0) return;+ if (busy || pdfBusy || !canContinue) return;setPdfBusy(true);setActionError(null);try {@@ -788,12 +884,16 @@ export function BundleCheckoutModal({)}{!resolving && phase === "calc" && (<CalculatorStep+ key={(pricing?.currency ?? currency) + ":" + ratePerRunMinor}credits={poolCredits}rate={ratePerRunMinor}- selectionCurrency={walletCurrency}+ selectionCurrency={pricing?.currency ?? currency}onCreditsChange={changePool}quote={receiptQuote}currency={currency}+ pricing={pricing}+ onCurrencyChange={(selected) => void changeCurrency(selected)}+ currencyBusy={busy || pdfBusy || !!invoice}onDownload={downloadPdf}downloading={pdfBusy}actionError={actionError}@@ -875,7 +975,9 @@ function QuoteReceipt({<Buttonvariant="quiet"size="sm"- disabled={downloading || quote.poolCredits <= 0}+ disabled={+ downloading || quote.poolCredits <= 0 || quote.priceMinor == null+ }onClick={onDownload}>{downloading@@ -893,6 +995,9 @@ function CalculatorStep({onCreditsChange,quote,currency,+ pricing,+ onCurrencyChange,+ currencyBusy,onDownload,downloading,actionError,@@ -900,6 +1005,9 @@ function CalculatorStep({credits: number;rate: number | null;selectionCurrency: string;+ pricing: BundlePricing | null;+ onCurrencyChange: (currency: string) => void;+ currencyBusy: boolean;onCreditsChange: (credits: number) => void;quote: BundleQuoteBreakdown;currency: string;@@ -909,7 +1017,9 @@ function CalculatorStep({}) {const { t } = useTranslation();const presets = [12_000, 24_000, 48_000];- const yearValue = rate && rate > 0 ? Math.round(credits * rate) / 100 : null;+ const minorUnitScale = stripeMinorUnitScale(selectionCurrency);+ const yearValue =+ rate && rate > 0 ? Math.round(credits * rate) / minorUnitScale : null;const [custom, setCustom] = useState(yearValue == null || !presets.includes(yearValue),);@@ -919,12 +1029,41 @@ function CalculatorStep({const amount = Number(value);onCreditsChange(rate && rate > 0 && Number.isFinite(amount) && amount > 0- ? Math.round((amount * 100) / rate)+ ? Math.round((amount * minorUnitScale) / rate): 0,);};return (<div className="portal-billing__bundle-calc">+ {pricing && (+ <FormField+ label={t("portal.billing.prepaid.calc.currency", "Quote currency")}+ helperText={+ pricing.currencyLocked !== false+ ? t(+ "portal.billing.prepaid.calc.currencyLocked",+ "Uses your existing Stripe billing currency.",+ )+ : undefined+ }+ >+ <Select+ aria-label={t(+ "portal.billing.prepaid.calc.currency",+ "Quote currency",+ )}+ value={currency}+ comboboxProps={{ withinPortal: false }}+ options={(pricing.availableCurrencies ?? [currency]).map(+ (code) => ({ value: code, label: code.toUpperCase() }),+ )}+ disabled={currencyBusy || pricing.currencyLocked !== false}+ onChange={(selected) => {+ if (selected) onCurrencyChange(selected);+ }}+ />+ </FormField>+ )}{actionError && (<Bannertone="danger"@@ -977,7 +1116,7 @@ function CalculatorStep({hideControlsclampBehavior="none"prefix={currencySymbol(selectionCurrency)}- decimalScale={2}+ decimalScale={Math.log10(minorUnitScale)}allowNegative={false}aria-label={t("portal.billing.simple.yearSize", "Year size")}/>diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.test.tsxindex 7bcc11cb16..c8a9e5bf3a 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx@@ -1,6 +1,6 @@import { useState } from "react";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 { MantineProvider } from "@mantine/core";import { FreePlanView } from "@portal/components/billing/FreePlanView";import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";@@ -8,6 +8,8 @@ import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";import type { LatestBundleQuote } from "@portal/billing/stripe";const api = vi.hoisted(() => ({+ fetchBundlePricing: vi.fn(),+ fetchCheckoutPricing: vi.fn(),getLatestBundleQuote: vi.fn(),cancelBundleQuote: vi.fn(),createBundleStripeQuote: vi.fn(),@@ -22,7 +24,10 @@ vi.mock("@portal/billing/stripe", async (importOriginal) => ({}));vi.mock("react-i18next", () => ({useTranslation: () => ({- t: (key: string, fallback?: string) => fallback ?? key,+ t: (key: string, fallback?: string, values?: Record<string, unknown>) =>+ (fallback ?? key).replace(/{{(.*?)}}/g, (_, name: string) =>+ String(values?.[name] ?? ""),+ ),}),}));@@ -53,19 +58,50 @@ function ResumedActivation() {beforeEach(() => {vi.clearAllMocks();+ HTMLElement.prototype.scrollIntoView = vi.fn();sessionStorage.clear();api.getLatestBundleQuote.mockResolvedValue(savedQuote);+ api.fetchCheckoutPricing.mockResolvedValue({+ currency: "usd",+ currencyLocked: false,+ unitAmountMinor: 1,+ });+ api.fetchBundlePricing.mockResolvedValue({+ currency: "usd",+ unitAmountMinor: 1,+ });});describe("Processor activation navigation", () => {+ it("uses the customer currency instead of the wallet display default", async () => {+ api.fetchCheckoutPricing.mockResolvedValue({+ currency: "cad",+ currencyLocked: true,+ unitAmountMinor: 1.5,+ });+ render(+ <MantineProvider env="test">+ <FreePlanView+ wallet={{ ...freeWallet, currency: "usd" }}+ step="payg"+ onStepChange={vi.fn()}+ />+ </MantineProvider>,+ );+ fireEvent.click(await screen.findByRole("button", { name: "Change" }));+ const limit = screen.getByRole("textbox", { name: "Monthly spend limit" });+ fireEvent.change(limit, { target: { value: "100" } });+ expect(limit).toHaveValue("CAD 100");+ });+it("returns from a saved quote to monthly limit selection without cancelling or purchasing", async () => {render(- <MantineProvider>+ <MantineProvider env="test"><ResumedActivation /></MantineProvider>,);fireEvent.click(await screen.findByRole("button", { name: "Back" }));- fireEvent.click(screen.getByRole("button", { name: "Change" }));+ fireEvent.click(await screen.findByRole("button", { name: "Change" }));const limit = screen.getByRole("textbox", { name: "Monthly spend limit" });fireEvent.change(limit, { target: { value: "250" } });expect(limit).toHaveValue("$250");@@ -76,7 +112,7 @@ describe("Processor activation navigation", () => {it("returns from the monthly limit to the same annual quote without minting another", async () => {render(- <MantineProvider>+ <MantineProvider env="test"><ResumedActivation /></MantineProvider>,);@@ -92,7 +128,7 @@ describe("Processor activation navigation", () => {it("keeps Cancel for a subscribed team's standalone top-up", async () => {const onClose = vi.fn();render(- <MantineProvider>+ <MantineProvider env="test"><BundleCheckoutModal open wallet={subscribedWallet} onClose={onClose} /></MantineProvider>,);@@ -102,4 +138,179 @@ describe("Processor activation navigation", () => {screen.queryByRole("button", { name: "Pay as you go" }),).not.toBeInTheDocument();});++ it("reprices an unaccepted USD quote at the customer's GBP rate before checkout", async () => {+ api.fetchBundlePricing.mockResolvedValue({+ currency: "gbp",+ unitAmountMinor: 0.75,+ });+ api.upsertBundleQuote.mockResolvedValue({ quoteId: 7 });+ api.createBundleStripeQuote.mockResolvedValue({+ stripeQuoteId: "qt_gbp",+ stripeQuoteNumber: null,+ });+ render(+ <MantineProvider env="test">+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={vi.fn()} />+ </MantineProvider>,+ );+ expect(await screen.findByText("£3,600.00")).toBeInTheDocument();+ expect(screen.queryByText("$4,800.00")).not.toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await waitFor(() =>+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({+ currency: "gbp",+ priceMinor: 360000,+ poolCredits: 576000,+ }),+ ),+ );+ expect(api.createBundleStripeQuote).toHaveBeenCalledOnce();+ });++ it("lets a new customer select a configured quote currency and reprices before issuing it", async () => {+ api.fetchBundlePricing.mockImplementation(+ (_teamId: number, currency = "usd") =>+ Promise.resolve({+ currency,+ unitAmountMinor: currency === "gbp" ? 0.75 : 1,+ availableCurrencies: ["usd", "gbp"],+ currencyLocked: false,+ }),+ );+ api.upsertBundleQuote.mockResolvedValue({ quoteId: 7 });+ api.createBundleStripeQuote.mockResolvedValue({+ stripeQuoteId: "qt_gbp",+ stripeQuoteNumber: null,+ });+ render(+ <MantineProvider env="test">+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={vi.fn()} />+ </MantineProvider>,+ );+ const selector = await screen.findByRole("textbox", {+ name: "Quote currency",+ });+ expect(selector).toHaveValue("USD");+ fireEvent.click(selector);+ fireEvent.click(await screen.findByRole("option", { name: "GBP" }));+ expect(await screen.findByText("£3,600.00")).toBeInTheDocument();+ expect(api.fetchBundlePricing).toHaveBeenCalledWith(+ subscribedWallet.teamId,+ "gbp",+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await waitFor(() =>+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({+ currency: "gbp",+ priceMinor: 360000,+ }),+ ),+ );+ });++ it("locks the quote selector to the customer's established Stripe currency", async () => {+ api.fetchBundlePricing.mockResolvedValue({+ currency: "gbp",+ unitAmountMinor: 0.75,+ availableCurrencies: ["gbp"],+ currencyLocked: true,+ });+ render(+ <MantineProvider env="test">+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={vi.fn()} />+ </MantineProvider>,+ );+ const selector = await screen.findByRole("textbox", {+ name: "Quote currency",+ });+ expect(selector).toHaveValue("GBP");+ expect(selector).toBeDisabled();+ });++ it("blocks new purchases when authoritative pricing cannot be loaded", async () => {+ api.fetchBundlePricing.mockRejectedValue(new Error("Pricing unavailable"));+ render(+ <MantineProvider env="test">+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={vi.fn()} />+ </MantineProvider>,+ );+ expect(await screen.findByText("Pricing unavailable")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeDisabled();+ expect(api.createBundleStripeQuote).not.toHaveBeenCalled();+ });++ it("keeps an issued GBP invoice accessible even when current pricing is unavailable", async () => {+ api.fetchBundlePricing.mockRejectedValue(new Error("Pricing unavailable"));+ api.getLatestBundleQuote.mockResolvedValue({+ ...savedQuote,+ currency: "gbp",+ stripeRef: "in_existing",+ });+ api.acceptBundleStripeQuote.mockResolvedValue({+ invoiceId: "in_existing",+ status: "open",+ invoicePdf: null,+ hostedInvoiceUrl: null,+ });+ render(+ <MantineProvider env="test">+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={vi.fn()} />+ </MantineProvider>,+ );+ expect(+ await screen.findByRole("button", { name: "Pay online" }),+ ).toBeEnabled();+ expect(screen.getByText("£4,800.00")).toBeInTheDocument();+ expect(screen.queryByText("Pricing unavailable")).not.toBeInTheDocument();+ expect(api.createBundleStripeQuote).not.toHaveBeenCalled();+ expect(api.upsertBundleQuote).not.toHaveBeenCalled();+ });+});++it("blocks payment when the Processor price cannot be resolved", async () => {+ api.fetchCheckoutPricing.mockRejectedValue(new Error("Pricing unavailable"));+ render(+ <MantineProvider env="test">+ <FreePlanView wallet={freeWallet} step="payg" onStepChange={vi.fn()} />+ </MantineProvider>,+ );+ expect(await screen.findByText("Pricing unavailable")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeDisabled();+ expect(api.createCheckoutSession).not.toHaveBeenCalled();+});+it("uses the resolved Processor rate and refreshes currency when reopened", async () => {+ api.fetchCheckoutPricing.mockResolvedValue({+ currency: "gbp",+ currencyLocked: false,+ unitAmountMinor: 2,+ });+ const view = (step: "payg" | null) => (+ <MantineProvider env="test">+ <FreePlanView wallet={freeWallet} step={step} onStepChange={vi.fn()} />+ </MantineProvider>+ );+ const { rerender } = render(view("payg"));+ expect(+ await screen.findByText("£0.02 each · billed as used"),+ ).toBeInTheDocument();+ rerender(view(null));+ api.fetchCheckoutPricing.mockResolvedValue({+ currency: "aud",+ currencyLocked: true,+ unitAmountMinor: 3,+ });+ rerender(view("payg"));+ expect(await screen.findByText(/0.03 each/)).toBeInTheDocument();+ expect(api.fetchCheckoutPricing).toHaveBeenCalledTimes(2);});diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsxindex 787f447630..5b475efcdf 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx@@ -2,7 +2,6 @@ import { useState } from "react";import { useTranslation } from "react-i18next";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 { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";@@ -25,10 +24,6 @@ interface Props {onActivationClosed?: () => void;}-function isSaasCurrency(c: string | null): c is SaasCurrency {- return c === "usd" || c === "eur" || c === "gbp";-}-/*** Owns the activation dialogs; the host supplies the Processor row action that opens them.* Nothing renders here at rest — a held prepaid pool reads on the Processor row itself.@@ -47,9 +42,6 @@ export function FreePlanView({const step = onStepChange ? (controlledStep ?? null) : ownStep;const setStep = onStepChange ?? setOwnStep;- const currency: SaasCurrency = isSaasCurrency(wallet.currency)- ? wallet.currency- : "usd";// Every dialog below needs a team to scope checkout, so an unresolved one would open nothing// at all. Saying so beats a door that silently does nothing.const missingTeam = step != null && wallet.teamId == null;@@ -83,8 +75,6 @@ export function FreePlanView({onClose={closeModals}onPrepay={() => setStep("prepay")}teamId={wallet.teamId}- currency={currency}- pricePerDocMinor={wallet.pricePerDocMinor}initialCapUsd={wallet.capUsd}onComplete={() => onSubscribed?.() ?? Promise.resolve(false)}/>diff --git a/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsx b/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsxindex 06c06bf6b9..05daf88c4b 100644--- a/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsx+++ b/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsx@@ -9,6 +9,11 @@ const updateCap = vi.hoisted(() => vi.fn());vi.mock("@portal/api/billing", () => ({ updateCap }));vi.mock("@portal/billing/stripe", () => ({getStripePublishableKey: () => null,+ fetchCheckoutPricing: async () => ({+ currency: "usd",+ currencyLocked: false,+ unitAmountMinor: 1,+ }),}));vi.mock("react-i18next", () => ({useTranslation: () => ({@@ -75,20 +80,19 @@ describe("Processor spend limit", () => {expect(onClose).not.toHaveBeenCalled();});- it("keeps an explicitly uncapped value when opening Processor signup", () => {+ it("keeps an explicitly uncapped value when opening Processor signup", async () => {render(<MantineProvider><StripeCheckoutModalopenteamId={42}- currency="usd"initialCapUsd={null}onClose={() => {}}onComplete={async () => false}/></MantineProvider>,);- expect(screen.getByText("No cap")).toBeInTheDocument();+ expect(await screen.findByText("No cap")).toBeInTheDocument();expect(updateCap).not.toHaveBeenCalled();});});diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsxindex 32d0695256..e258979f7d 100644--- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsx+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsx@@ -16,8 +16,6 @@ const meta: Meta<typeof StripeCheckoutModal> = {open: true,onClose: () => console.log("close"),teamId: 1,- currency: "usd",- pricePerDocMinor: 1,initialCapUsd: 100,onComplete: () => Promise.resolve(true),},@@ -26,6 +24,14 @@ const meta: Meta<typeof StripeCheckoutModal> = {layout: "fullscreen",msw: {handlers: [+ http.post("http://saas.mock/functions/v1/create-checkout-session", () =>+ HttpResponse.json({+ success: true,+ currency: "usd",+ currency_locked: false,+ unit_amount_minor: 1,+ }),+ ),http.patch("http://saas.mock/api/v1/payg/cap",() => new HttpResponse(null, { status: 204 }),diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsxindex ee896f28f4..4b2a87ead1 100644--- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx@@ -8,9 +8,10 @@ import {import { updateCap } from "@portal/api/billing";import {createCheckoutSession,+ fetchCheckoutPricing,getStripePublishableKey,loadStripeOnce,- type SaasCurrency,+ type CheckoutPricing,} from "@portal/billing/stripe";import { CardPlaceholder } from "@portal/components/billing/CardPlaceholder";import { ProcessorSpendFields } from "@portal/components/billing/ProcessorSpendFields";@@ -22,10 +23,6 @@ interface Props {onPrepay?: () => 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. */- currency: SaasCurrency;- /** Per-credit rate in minor currency units. */- pricePerDocMinor?: number | null;/** Cap to seed the spend-limit step with; defaults to $100/mo. */initialCapUsd?: number | null;/** Optional billing email prefill (Stripe locks the field when set). */@@ -107,8 +104,6 @@ export function StripeCheckoutModal({onClose,onPrepay,teamId,- currency,- pricePerDocMinor,initialCapUsd,billingOwnerEmail,onComplete,@@ -117,6 +112,28 @@ export function StripeCheckoutModal({const [clientSecret, setClientSecret] = useState<string | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);+ const [pricing, setPricing] = useState<CheckoutPricing | null>(null);+ const [pricingError, setPricingError] = useState<string | null>(null);+ const currency = pricing?.currency ?? "usd";+ useEffect(() => {+ setPricing(null);+ setPricingError(null);+ if (!open) return;+ let cancelled = false;+ fetchCheckoutPricing(teamId, "processor")+ .then((value) => {+ if (!cancelled) setPricing(value);+ })+ .catch((cause: unknown) => {+ if (!cancelled)+ setPricingError(+ cause instanceof Error ? cause.message : String(cause),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [open, teamId]);// "cap" = spend-limit step; "checkout" = Stripe card form; "finalizing" =// payment done, waiting for activation (non-dismissable); "activationSlow" =// webhook lagging past the poll window (dismissable).@@ -209,6 +226,7 @@ export function StripeCheckoutModal({// Apply the chosen ceiling, then advance to payment. Applying it up front keeps// "you're never billed past it" true from the first processed PDF.async function handleContinue() {+ if (!pricing) return;// Guard the empty-field sentinel: clearing the input maps to 0, which is neither a real cap nor the// explicit "No limit" (null). Proceeding would set a $0 ceiling (processing immediately paused), so// treat it as incomplete and stay put — the Continue button is disabled in this state too.@@ -302,13 +320,27 @@ export function StripeCheckoutModal({{phase === "cap" && (<div className="portal-billing__checkout-cap"><div className="portal-billing__checkout-scroll">- <ProcessorSpendFields- value={capUsd}- onChange={setCapUsd}- currency={currency}- rate={pricePerDocMinor ?? null}- disabled={capBusy}- />+ {pricing ? (+ <ProcessorSpendFields+ value={capUsd}+ onChange={setCapUsd}+ currency={currency}+ rate={pricing.unitAmountMinor ?? null}+ disabled={capBusy}+ />+ ) : pricingError ? (+ <Banner+ tone="danger"+ title={t(+ "portal.billing.checkout.error.title",+ "Couldn't start checkout",+ )}+ >+ {pricingError}+ </Banner>+ ) : (+ <Skeleton height="8rem" />+ )}<p className="portal-billing__checkout-finePrint">{t("portal.billing.simple.billingNote",@@ -336,7 +368,7 @@ export function StripeCheckoutModal({</Button><Buttonloading={capBusy}- disabled={!capValid}+ disabled={!capValid || !pricing}onClick={handleContinue}rightSection={<span aria-hidden>›</span>}>diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsxindex dea337a1cc..6ffeb8a2f5 100644--- a/frontend/editor/src/portal/views/Usage.test.tsx+++ b/frontend/editor/src/portal/views/Usage.test.tsx@@ -24,6 +24,9 @@ import type { ProcurementSnapshot } from "@app/portal/api/procurement";import type { LegacyBillingState } from "@app/types/legacyBilling";import { formatPeriodDate } from "@app/billing";+const fetchCheckoutPricing = vi.hoisted(() => vi.fn());+vi.mock("@app/portal/billing/stripe", () => ({ fetchCheckoutPricing }));+const legacyBilling: LegacyBillingState = {subscriptions: [],loading: false,@@ -225,7 +228,15 @@ describe("Usage — link-free wallet renderer", () => {it("opens Team once for an over-capacity server and includes the actual allowance", async () => {checkoutEnabled = true;- fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });+ fetchWallet.mockResolvedValue({+ ...walletOf("free"),+ teamId: 42,+ role: "leader",+ });+ fetchCheckoutPricing.mockResolvedValue({+ currency: "gbp",+ currencyLocked: false,+ });renderUsage(<Usage localUsersInUse={7} localUserLimit={5} />,"/settings/billing?upgrade=team",@@ -237,8 +248,11 @@ describe("Usage — link-free wallet renderer", () => {combinedChoose: true,minimumSeats: 7,capacityNotice: { users: 7, limit: 5 },+ resolveCurrency: expect.any(Function),}),);+ await checkout.openCheckout.mock.calls[0][1].resolveCurrency("gbp");+ expect(fetchCheckoutPricing).toHaveBeenCalledWith(42, "currency", "gbp");expect(screen.getByTestId("location")).toHaveTextContent("/settings/billing",);diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsxindex cc1adc29b9..60348c37af 100644--- a/frontend/editor/src/portal/views/Usage.tsx+++ b/frontend/editor/src/portal/views/Usage.tsx@@ -1,4 +1,5 @@import { TeamSubscriptionChange } from "@app/billing/TeamSubscriptionChange";+import { fetchCheckoutPricing } from "@app/portal/billing/stripe";import type { ServerPlan } from "@app/billing/serverPlan";import { fleetUsersInUse } from "@app/billing/fleetSeats";import {@@ -260,12 +261,18 @@ export function Usage({? wallet?.team?.usersInUse: localUsersInUse;const addCapacity = useCallback(() => {+ const teamId = wallet?.teamId;// No email: the only one this instance holds is its local admin record, which is a Spring// username and not an address the buyer owns. The checkout asks for one instead.void checkout?.openCheckout("server", {combinedChoose: true,currentLimit: heldLimit,minimumSeats: usersInUse ?? undefined,+ resolveCurrency:+ teamId != null+ ? (preferredCurrency) =>+ fetchCheckoutPricing(teamId, "currency", preferredCurrency)+ : undefined,capacityNotice:!serverPlan &&!wallet?.team?.held &&@@ -283,6 +290,7 @@ export function Usage({usersInUse,serverPlan,wallet?.team?.held,+ wallet?.teamId,localUsersInUse,localUserLimit,]);diff --git a/frontend/editor/src/proprietary/billing/format.ts b/frontend/editor/src/proprietary/billing/format.tsindex 6b95ced991..abd9ac3072 100644--- a/frontend/editor/src/proprietary/billing/format.ts+++ b/frontend/editor/src/proprietary/billing/format.ts@@ -6,6 +6,11 @@* diverging from the backend when a rate encoding changes.*/+import {+ stripeAmountToMajor,+ stripeMinorUnitScale,+} from "@app/utils/stripeCurrency";+/** Quick-amount cap presets (major currency units) offered everywhere. */export const DEFAULT_CAP_PRESETS = [500, 1000, 2500, 5000] as const;@@ -34,9 +39,9 @@ export function formatMinor(currency: string | null | undefined,): string {const num = new Intl.NumberFormat("en-US", {- minimumFractionDigits: 2,+ minimumFractionDigits: Math.log10(stripeMinorUnitScale(currency)),maximumFractionDigits: 3,- }).format(minor / 100);+ }).format(stripeAmountToMajor(minor, currency));return `${currencySymbol(currency)}${num}`;}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsxindex d0755202e4..068791b36b 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx@@ -23,13 +23,12 @@ import { useLoginRequired } from "@app/hooks/useLoginRequired";import { isSupabaseConfigured } from "@app/services/supabaseClient";const AdminPlanSection: React.FC = () => {- const { t, i18n } = useTranslation();+ const { t } = useTranslation();const { loginEnabled, validateLoginEnabled } = useLoginRequired();const { openCheckout } = useCheckout();const { licenseInfo } = useLicense();const [currency, setCurrency] = useState<string>(() => {- // Initialize with auto-detected currency on first render- return getPreferredCurrency(i18n.language);+ return getPreferredCurrency();});const [useStaticVersion, setUseStaticVersion] = useState(false);const { plans, loading, error, refetch } = usePlans(currency);diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsxindex 1cc9d9742d..507033e521 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx@@ -59,7 +59,7 @@ it("keeps payment language for a first purchase", () => {/></MantineProvider>,);- expect(screen.getByText("Due today")).toBeInTheDocument();+ expect(screen.getByText("Estimated total")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Continue to payment" }),).toBeEnabled();diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsxindex bdc405685e..ec12e2d6cf 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx@@ -253,7 +253,7 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({<Text fw={600}>{currentLimit != null? t("payment.capacityStage.newPlanTotal", "New plan total")- : t("payment.capacityStage.dueToday", "Due today")}+ : t("payment.capacityStage.estimatedTotal", "Estimated total")}</Text><Text size="md" fw={600}>{formatPrice(total, currency)}@@ -276,6 +276,12 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({)}</Text>+ <Text size="xs" c="dimmed">+ {t(+ "payment.capacityStage.currencyAtCheckout",+ "Stripe confirms the final amount and payment currency at checkout.",+ )}+ </Text><Group justify="flex-end" mt="sm"><ButtononClick={onContinue}diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsxindex 81c2268d5e..f1c6ffed5f 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx@@ -5,6 +5,8 @@ import { expectConsole } from "@app/tests/failOnConsole";const mocks = vi.hoisted(() => ({getPlans: vi.fn(),+ pricing: vi.fn(),+ preferred: vi.fn(() => "usd"),getLicenseInfo: vi.fn(),getUsers: vi.fn(),alert: vi.fn(),@@ -27,7 +29,7 @@ vi.mock("@app/contexts/LicenseContext", () => ({}));vi.mock("@app/services/supabaseClient", () => ({ isSupabaseConfigured: true }));vi.mock("@app/utils/currencyDetection", () => ({- getPreferredCurrency: () => "usd",+ getPreferredCurrency: mocks.preferred,}));vi.mock("@app/components/toast", () => ({ alert: mocks.alert }));vi.mock("@app/services/userManagementService", () => ({@@ -46,10 +48,17 @@ vi.mock("@app/components/shared/stripeCheckout", () => ({StripeCheckout: () => <div role="dialog">Checkout</div>,}));-function Buyer() {+function Buyer({ linked = false }: { linked?: boolean }) {const checkout = useCheckout();return (- <button onClick={() => void checkout.openCheckout("server")}>+ <button+ onClick={() =>+ void checkout.openCheckout(+ "server",+ linked ? { resolveCurrency: mocks.pricing } : {},+ )+ }+ >Add capacity</button>);@@ -73,7 +82,7 @@ it("opens on the first click using asynchronously fetched plans", async () => {);fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));- expect(mocks.getPlans).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(mocks.getPlans).toHaveBeenCalledTimes(1));resolvePlans({ plans: [{ id: "server-monthly" }] });expect(await screen.findByRole("dialog")).toBeInTheDocument();expect(mocks.alert).not.toHaveBeenCalled();@@ -100,3 +109,24 @@ it("reports failed price loading visibly and allows a retry", async () => {fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));expect(await screen.findByRole("dialog")).toBeInTheDocument();});++it("resolves a linked customer's currency before fetching Team prices", async () => {+ mocks.preferred.mockReturnValue("gbp");+ mocks.pricing.mockResolvedValue({ currency: "aud", currencyLocked: true });+ mocks.getPlans.mockResolvedValue({ plans: [{ id: "server-monthly" }] });+ render(+ <CheckoutProvider>+ <Buyer linked />+ </CheckoutProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ expect(await screen.findByRole("dialog")).toBeInTheDocument();+ expect(mocks.pricing).toHaveBeenCalledWith("gbp");+ expect(mocks.getPlans).toHaveBeenCalledWith(+ mocks.features,+ mocks.highlights,+ "aud",+ true,+ "server",+ );+});diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsxindex e7c452d869..ce0362dedb 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx@@ -39,8 +39,13 @@ import {} from "@app/constants/planConstants";export interface CheckoutOptions {+ /** Resolves the linked customer's currency using the caller's billing session. */+ resolveCurrency?: (preferredCurrency: string) => Promise<{+ currency: string;+ currencyLocked: boolean;+ }>;minimumSeats?: number; // Override calculated seats for enterprise- currency?: string; // Optional currency override (auto-detected from locale)+ currency?: string; // Explicit display currency; checkout localization is handled by StripeonSuccess?: (sessionId: string) => void; // Callback after successful paymentonError?: (error: string) => void; // Callback on error/** Put the period and capacity choices on one page rather than walking them separately. */@@ -75,7 +80,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({children,defaultCurrency,}) => {- const { t, i18n } = useTranslation();+ const { t } = useTranslation();const { refetchLicense } = useLicense();const planFeatures = usePlanFeatures();const planHighlights = usePlanHighlights();@@ -85,8 +90,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({useState<PlanTierGroup | null>(null);const [minimumSeats, setMinimumSeats] = useState<number>(1);const [currentCurrency, setCurrentCurrency] = useState(() => {- // Use provided default or auto-detect from locale- return defaultCurrency || getPreferredCurrency(i18n.language);+ return defaultCurrency || getPreferredCurrency();});const [currentOptions, setCurrentOptions] = useState<CheckoutOptions>({});const [hostedCheckoutSuccess, setHostedCheckoutSuccess] = useState<{@@ -101,12 +105,18 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({// Lazy fetch plans only when neededconst fetchPlansIfNeeded = useCallback(- async (currency: string) => {+ async (+ currency: string,+ currencyLocked = false,+ tier?: "server" | "enterprise",+ ) => {try {const response = await licenseService.getPlans(planFeatures,planHighlights,currency,+ currencyLocked,+ tier,);setPlans(response.plans);setPlansLoaded(true);@@ -349,17 +359,19 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({);}- // Update currency if provided- const currency = options.currency || currentCurrency;+ const preferredCurrency =+ options.currency || defaultCurrency || getPreferredCurrency();+ const pricing = await options.resolveCurrency?.(preferredCurrency);+ const currency = pricing?.currency ?? preferredCurrency;if (currency !== currentCurrency) {setCurrentCurrency(currency);}- // Fetch plans if not already loaded- const availablePlans =- !plansLoaded || currency !== currentCurrency- ? await fetchPlansIfNeeded(currency)- : plans;+ const availablePlans = await fetchPlansIfNeeded(+ currency,+ pricing?.currencyLocked,+ tier,+ );// Fetch license info and user data for seat calculationslet licenseInfo: LicenseInfo | null = null;@@ -429,7 +441,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({setIsLoading(false);}},- [currentCurrency, plans, plansLoaded, fetchPlansIfNeeded],+ [currentCurrency, defaultCurrency, fetchPlansIfNeeded],);const closeCheckout = useCallback(() => {diff --git a/frontend/editor/src/proprietary/hooks/usePlans.ts b/frontend/editor/src/proprietary/hooks/usePlans.tsindex 45b7d8988e..00957744fa 100644--- a/frontend/editor/src/proprietary/hooks/usePlans.ts+++ b/frontend/editor/src/proprietary/hooks/usePlans.ts@@ -1,4 +1,5 @@import { useState, useEffect, useCallback } from "react";+import { getPreferredCurrency } from "@app/utils/currencyDetection";import licenseService, {PlanTier,PlansResponse,@@ -15,7 +16,9 @@ export interface UsePlansReturn {refetch: () => Promise<void>;}-export const usePlans = (currency: string = "gbp"): UsePlansReturn => {+export const usePlans = (+ currency: string = getPreferredCurrency(),+): UsePlansReturn => {const planFeatures = usePlanFeatures();const planHighlights = usePlanHighlights();const [plans, setPlans] = useState<PlanTier[]>([]);diff --git a/frontend/editor/src/proprietary/services/licenseService.currency.test.ts b/frontend/editor/src/proprietary/services/licenseService.currency.test.tsnew file mode 100644index 0000000000..f80b266b39--- /dev/null+++ b/frontend/editor/src/proprietary/services/licenseService.currency.test.ts@@ -0,0 +1,85 @@+import { expect, it, vi } from "vitest";+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock("@app/services/supabaseClient", () => ({+ supabase: { functions: { invoke } },+ isSupabaseConfigured: () => true,+}));+vi.mock("@app/services/apiClient", () => ({ default: {} }));+import licenseService from "@app/services/licenseService";++it.each([+ ["usd", 9900, "$", 99],+ ["jpy", 15000, "JPY", 15000],+ ["cad", 13900, "CAD", 139],+])(+ "uses Stripe's %s amounts when the requested GBP currency differs",+ async (currency, amount, symbol, expected) => {+ invoke.mockResolvedValue({+ data: {+ prices: {+ "selfhosted:team:monthly": { unit_amount: amount, currency },+ "selfhosted:team:yearly": { unit_amount: amount * 10, currency },+ },+ missing: [],+ },+ error: null,+ });+ const result = await licenseService.getPlans(+ { FREE: [], SERVER: [], ENTERPRISE: [] },+ {+ FREE: [],+ SERVER_MONTHLY: [],+ SERVER_YEARLY: [],+ ENTERPRISE_MONTHLY: [],+ ENTERPRISE_YEARLY: [],+ },+ "gbp",+ );+ expect(+ result.plans.find((p) => p.id === "selfhosted:team:monthly"),+ ).toMatchObject({ currency: symbol, price: expected });+ },+);++it("looks up only Team prices so Enterprise currency support cannot force a USD fallback", async () => {+ invoke.mockResolvedValue({+ data: {+ prices: {+ "selfhosted:team:monthly": { unit_amount: 15000, currency: "aud" },+ "selfhosted:team:yearly": { unit_amount: 150000, currency: "aud" },+ },+ missing: [],+ },+ error: null,+ });+ const result = await licenseService.getPlans(+ { FREE: [], SERVER: [], ENTERPRISE: [] },+ {+ FREE: [],+ SERVER_MONTHLY: [],+ SERVER_YEARLY: [],+ ENTERPRISE_MONTHLY: [],+ ENTERPRISE_YEARLY: [],+ },+ "aud",+ true,+ "server",+ );+ expect(invoke).toHaveBeenLastCalledWith("stripe-price-lookup", {+ body: {+ lookup_keys: ["selfhosted:team:monthly", "selfhosted:team:yearly"],+ currency: "aud",+ },+ });+ expect(+ result.plans.find((p) => p.id === "selfhosted:team:monthly"),+ ).toMatchObject({ currency: "AUD", price: 150 });+ expect(result.plans.map((plan) => plan.id)).toEqual([+ "free",+ "selfhosted:team:monthly",+ "selfhosted:team:yearly",+ ]);+ expect(+ licenseService.groupPlansByTier(result.plans).map((group) => group.tier),+ ).toEqual(["free", "server"]);+});diff --git a/frontend/editor/src/proprietary/services/licenseService.ts b/frontend/editor/src/proprietary/services/licenseService.tsindex 1c9945a5cc..fc1aaeee9b 100644--- a/frontend/editor/src/proprietary/services/licenseService.ts+++ b/frontend/editor/src/proprietary/services/licenseService.ts@@ -1,4 +1,5 @@import apiClient from "@app/services/apiClient";+import { stripeAmountToMajor } from "@app/utils/stripeCurrency";import { supabase, isSupabaseConfigured } from "@app/services/supabaseClient";import type {PlanFeaturesMap,@@ -98,6 +99,8 @@ const licenseService = {planFeatures: PlanFeaturesMap,planHighlights: PlanHighlightsMap,currency: string = "usd",+ currencyLocked = false,+ tier?: "server" | "enterprise",): Promise<PlansResponse> {try {// Check if Supabase is configured@@ -120,7 +123,12 @@ const licenseService = {missing: string[];}>("stripe-price-lookup", {body: {- lookup_keys: SELF_HOSTED_LOOKUP_KEYS,+ lookup_keys:+ tier === "server"+ ? SELF_HOSTED_LOOKUP_KEYS.filter((key) =>+ key.startsWith("selfhosted:team:"),+ )+ : SELF_HOSTED_LOOKUP_KEYS,currency,},});@@ -149,18 +157,27 @@ const licenseService = {{ unit_amount: number; currency: string }>();for (const [lookupKey, priceData] of Object.entries(data.prices)) {+ if (currencyLocked && priceData.currency !== currency) {+ throw new Error(+ `The plan is not configured for ${currency.toUpperCase()}.`,+ );+ }priceMap.set(lookupKey, {unit_amount: priceData.unit_amount,currency: priceData.currency,});}- const currencySymbol = getCurrencySymbol(currency);+ const currencySymbol = getCurrencySymbol("usd");+ const priceCurrency = (key: string) =>+ getCurrencySymbol(priceMap.get(key)?.currency ?? "usd");// Helper to get price infoconst getPriceInfo = (lookupKey: string, fallback: number = 0) => {const priceData = priceMap.get(lookupKey);- return priceData ? priceData.unit_amount / 100 : fallback;+ return priceData+ ? stripeAmountToMajor(priceData.unit_amount, priceData.currency)+ : fallback;};// Build plan tiers@@ -170,7 +187,7 @@ const licenseService = {lookupKey: "selfhosted:team:monthly",name: "Team - Monthly",price: getPriceInfo("selfhosted:team:monthly"),- currency: currencySymbol,+ currency: priceCurrency("selfhosted:team:monthly"),period: "/month",popular: false,features: planFeatures.SERVER,@@ -181,39 +198,42 @@ const licenseService = {lookupKey: "selfhosted:team:yearly",name: "Team - Yearly",price: getPriceInfo("selfhosted:team:yearly"),- currency: currencySymbol,+ currency: priceCurrency("selfhosted:team:yearly"),period: "/year",popular: true,features: planFeatures.SERVER,highlights: planHighlights.SERVER_YEARLY,},- {- id: "selfhosted:enterprise:monthly",- lookupKey: "selfhosted:team:monthly",- name: "Enterprise - Monthly",- price: getPriceInfo("selfhosted:team:monthly"),- seatPrice: getPriceInfo("selfhosted:enterpriseseat:monthly"),- currency: currencySymbol,- period: "/month",- popular: false,- requiresSeats: true,- features: planFeatures.ENTERPRISE,- highlights: planHighlights.ENTERPRISE_MONTHLY,- },- {- id: "selfhosted:enterprise:yearly",- lookupKey: "selfhosted:team:yearly",- name: "Enterprise - Yearly",- price: getPriceInfo("selfhosted:team:yearly"),- seatPrice: getPriceInfo("selfhosted:enterpriseseat:yearly"),- currency: currencySymbol,- period: "/year",- popular: false,- requiresSeats: true,- features: planFeatures.ENTERPRISE,- highlights: planHighlights.ENTERPRISE_YEARLY,- },];+ if (tier !== "server")+ plans.push(+ {+ id: "selfhosted:enterprise:monthly",+ lookupKey: "selfhosted:team:monthly",+ name: "Enterprise - Monthly",+ price: getPriceInfo("selfhosted:team:monthly"),+ seatPrice: getPriceInfo("selfhosted:enterpriseseat:monthly"),+ currency: priceCurrency("selfhosted:team:monthly"),+ period: "/month",+ popular: false,+ requiresSeats: true,+ features: planFeatures.ENTERPRISE,+ highlights: planHighlights.ENTERPRISE_MONTHLY,+ },+ {+ id: "selfhosted:enterprise:yearly",+ lookupKey: "selfhosted:team:yearly",+ name: "Enterprise - Yearly",+ price: getPriceInfo("selfhosted:team:yearly"),+ seatPrice: getPriceInfo("selfhosted:enterpriseseat:yearly"),+ currency: priceCurrency("selfhosted:team:yearly"),+ period: "/year",+ popular: false,+ requiresSeats: true,+ features: planFeatures.ENTERPRISE,+ highlights: planHighlights.ENTERPRISE_YEARLY,+ },+ );// Filter out plans with missing prices (price === 0 means Stripe price not found)const validPlans = plans.filter((plan) => plan.price > 0);diff --git a/frontend/editor/src/proprietary/utils/currencyDetection.test.ts b/frontend/editor/src/proprietary/utils/currencyDetection.test.tsnew file mode 100644index 0000000000..ddb9c04442--- /dev/null+++ b/frontend/editor/src/proprietary/utils/currencyDetection.test.ts@@ -0,0 +1,47 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import {+ getPreferredCurrency,+ setCachedCurrency,+} from "@app/utils/currencyDetection";++beforeEach(() => localStorage.clear());+afterEach(() => vi.unstubAllGlobals());++it.each([+ ["en-GB", "gbp"],+ ["de-DE", "eur"],+ ["fr-CA", "cad"],+ ["de-CH", "chf"],+ ["zh-Hant-TW", "twd"],+ ["ja-JP", "jpy"],+ ["en-AU", "aud"],+ ["unknown", "usd"],+ ["invalid_locale", "usd"],+])("uses %s as a display hint for %s", (language, currency) => {+ vi.stubGlobal("navigator", { languages: [language] });+ expect(getPreferredCurrency()).toBe(currency);+ expect(localStorage.length).toBe(0);+});++it("uses the next browser locale when the first has no known region", () => {+ vi.stubGlobal("navigator", { languages: ["en", "en-GB"] });+ expect(getPreferredCurrency()).toBe("gbp");+});++it("ignores previously cached guesses and detects the current browser region", () => {+ localStorage.setItem("preferredCurrency", "usd");+ vi.stubGlobal("navigator", { language: "en-GB" });+ expect(getPreferredCurrency()).toBe("gbp");+});++it("keeps an explicit pricing preference ahead of the browser hint", () => {+ vi.stubGlobal("navigator", { languages: ["en-GB"] });+ setCachedCurrency("eur");+ expect(getPreferredCurrency()).toBe("eur");+});++it("falls back to USD when neither storage nor browser provides a currency", () => {+ localStorage.setItem("explicitPricingCurrency", "not-a-currency");+ vi.stubGlobal("navigator", undefined);+ expect(getPreferredCurrency()).toBe("usd");+});diff --git a/frontend/editor/src/proprietary/utils/currencyDetection.ts b/frontend/editor/src/proprietary/utils/currencyDetection.tsindex e5a059b790..4cc8a8dc1b 100644--- a/frontend/editor/src/proprietary/utils/currencyDetection.ts+++ b/frontend/editor/src/proprietary/utils/currencyDetection.ts@@ -1,142 +1,106 @@-/**- * Currency detection utility- * Auto-detects user's preferred currency from browser locale- */--const STORAGE_KEY = "preferredCurrency";--/**- * Map of locale codes to currency codes- * Covers all major locales and their corresponding currencies- */-const LOCALE_TO_CURRENCY_MAP: Record<string, string> = {- // English variants- "en-US": "usd",- "en-CA": "usd",- "en-AU": "usd",- "en-NZ": "usd",- "en-GB": "gbp",- "en-IE": "eur",-- // European locales - Euro- "de-DE": "eur",- "de-AT": "eur",- "de-CH": "eur",- "fr-FR": "eur",- "fr-BE": "eur",- "fr-CH": "eur",- "it-IT": "eur",- "es-ES": "eur",- "pt-PT": "eur",- "nl-NL": "eur",- "nl-BE": "eur",- "pl-PL": "eur",- "ro-RO": "eur",- "el-GR": "eur",- "fi-FI": "eur",- "sv-SE": "eur",- "da-DK": "eur",- "no-NO": "eur",-- // Chinese variants- "zh-CN": "cny",- "zh-TW": "cny",- "zh-HK": "cny",- "zh-SG": "cny",-- // Indian locales- "hi-IN": "inr",- "en-IN": "inr",- "bn-IN": "inr",- "te-IN": "inr",- "ta-IN": "inr",- "mr-IN": "inr",-- // Brazilian Portuguese- "pt-BR": "brl",-- // Indonesian- "id-ID": "idr",- "jv-ID": "idr",-- // Other major locales defaulting to USD- "ja-JP": "usd",- "ko-KR": "usd",- "ru-RU": "usd",- "ar-SA": "usd",- "th-TH": "usd",- "vi-VN": "usd",- "tr-TR": "usd",+const STORAGE_KEY = "explicitPricingCurrency";++const REGION_CURRENCIES: Record<string, string> = {+ US: "usd",+ GB: "gbp",+ CA: "cad",+ AU: "aud",+ NZ: "nzd",+ CN: "cny",+ TW: "twd",+ HK: "hkd",+ SG: "sgd",+ IN: "inr",+ BR: "brl",+ ID: "idr",+ JP: "jpy",+ KR: "krw",+ CH: "chf",+ SE: "sek",+ DK: "dkk",+ NO: "nok",+ PL: "pln",+ RO: "ron",+ CZ: "czk",+ HU: "huf",+ MX: "mxn",+ ZA: "zar",+ TH: "thb",+ VN: "vnd",+ TR: "try",+ AE: "aed",+ SA: "sar",+ MY: "myr",+ PH: "php",+ IL: "ils",};--/**- * Detect currency from browser locale- * @param locale - Browser locale string (e.g., 'en-US', 'de-DE')- * @returns Currency code ('usd', 'gbp', 'eur', etc.)- */-export function detectCurrencyFromLocale(locale: string): string {- // Try exact match first- if (LOCALE_TO_CURRENCY_MAP[locale]) {- return LOCALE_TO_CURRENCY_MAP[locale];- }-- // Try matching just the language code (e.g., 'en' from 'en-US')- const languageCode = locale.split("-")[0];- const matchingLocale = Object.keys(LOCALE_TO_CURRENCY_MAP).find((key) =>- key.startsWith(languageCode),- );-- if (matchingLocale) {- return LOCALE_TO_CURRENCY_MAP[matchingLocale];- }-- // Default fallback to USD- return "usd";-}--/**- * Get cached currency preference from localStorage- * @returns Cached currency code or null if not set- */+const EURO_REGIONS = new Set([+ "AD",+ "AT",+ "BE",+ "CY",+ "DE",+ "EE",+ "ES",+ "FI",+ "FR",+ "GR",+ "HR",+ "IE",+ "IT",+ "LT",+ "LU",+ "LV",+ "MC",+ "ME",+ "MT",+ "NL",+ "PT",+ "SI",+ "SK",+ "SM",+ "VA",+]);++/** A display preference only; Stripe owns checkout currency selection. */export function getCachedCurrency(): string | null {try {- return localStorage.getItem(STORAGE_KEY);- } catch (error) {- console.warn("Failed to read currency from localStorage:", error);+ const currency = localStorage.getItem(STORAGE_KEY);+ return currency && /^[a-z]{3}$/.test(currency) ? currency : null;+ } catch {return null;}}-/**- * Save currency preference to localStorage- * @param currency - Currency code to cache- */+/** Stores an explicit selection, never a browser-language guess. */export function setCachedCurrency(currency: string): void {try {- localStorage.setItem(STORAGE_KEY, currency);- } catch (error) {- console.warn("Failed to save currency to localStorage:", error);+ if (/^[a-z]{3}$/.test(currency))+ localStorage.setItem(STORAGE_KEY, currency);+ } catch {+ // Private browsing may disable storage.}}-/**- * Get preferred currency with auto-detection fallback- * Priority: localStorage > locale detection > default (USD)- * @param currentLocale - Current browser/i18n locale- * @returns Currency code- */-export function getPreferredCurrency(currentLocale: string): string {- // 1. Check localStorage (user has previously selected)- const cached = getCachedCurrency();- if (cached) {- return cached;+/** Uses browser regions as price-lookup hints; unknown regions fall back to USD. */+export function getPreferredCurrency(): string {+ const explicit = getCachedCurrency();+ if (explicit) return explicit;+ const languages =+ typeof navigator === "undefined"+ ? []+ : navigator.languages?.length+ ? navigator.languages+ : [navigator.language];+ for (const language of languages) {+ try {+ const region = new Intl.Locale(language).region;+ if (!region) continue;+ if (EURO_REGIONS.has(region)) return "eur";+ if (REGION_CURRENCIES[region]) return REGION_CURRENCIES[region];+ } catch {+ // A malformed locale must not prevent checkout.+ }}-- // 2. Auto-detect from locale- const detected = detectCurrencyFromLocale(currentLocale);-- // 3. Cache the detection for future visits- setCachedCurrency(detected);-- return detected;+ return "usd";}diff --git a/frontend/editor/src/proprietary/utils/stripeCurrency.ts b/frontend/editor/src/proprietary/utils/stripeCurrency.tsnew file mode 100644index 0000000000..815deb944f--- /dev/null+++ b/frontend/editor/src/proprietary/utils/stripeCurrency.ts@@ -0,0 +1,21 @@+/** Stripe charge units differ from ISO defaults for ISK, UGX and MGA. */+export function stripeMinorUnitScale(+ currency: string | null | undefined,+): number {+ const code = (currency || "usd").toLowerCase();+ if (code === "isk" || code === "ugx") return 100;+ if (code === "mga") return 1;+ const digits = new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: code,+ }).resolvedOptions().maximumFractionDigits;+ return 10 ** (digits ?? 2);+}++/** Converts Stripe amounts, including fractional per-unit prices, without changing currency. */+export function stripeAmountToMajor(+ amount: number,+ currency: string | null | undefined,+): number {+ return amount / stripeMinorUnitScale(currency);+}diff --git a/frontend/editor/src/saas/hooks/usePlans.ts b/frontend/editor/src/saas/hooks/usePlans.tsindex 62dd64bf90..a5d299affe 100644--- a/frontend/editor/src/saas/hooks/usePlans.ts+++ b/frontend/editor/src/saas/hooks/usePlans.ts@@ -2,6 +2,8 @@ import { useState, useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";import { supabase } from "@app/auth/supabase";import { useAuth } from "@app/auth/UseSession";+import { getPreferredCurrency } from "@app/utils/currencyDetection";+import { stripeAmountToMajor } from "@app/utils/stripeCurrency";// Currency mappingconst getCurrencySymbol = (currency: string): string => {@@ -51,7 +53,7 @@ export interface PlansData {activeSince?: string;}-export const usePlans = (currency: string = "gbp") => {+export const usePlans = (currency: string = getPreferredCurrency()) => {const { t } = useTranslation();const { isPro, refreshProStatus } = useAuth();const [loading, setLoading] = useState(false);@@ -167,11 +169,14 @@ export const usePlans = (currency: string = "gbp") => {id: "pro",name: t("plan.pro.name", "Pro"),price: dynamicPrices.get("pro")- ? dynamicPrices.get("pro")!.unit_amount / 100+ ? stripeAmountToMajor(+ dynamicPrices.get("pro")!.unit_amount,+ dynamicPrices.get("pro")!.currency,+ ): 8,currency: dynamicPrices.get("pro")? getCurrencySymbol(dynamicPrices.get("pro")!.currency)- : getCurrencySymbol(currency),+ : getCurrencySymbol("usd"),period: t("plan.period.month", "/month"),popular: true,highlights: [@@ -244,10 +249,12 @@ export const usePlans = (currency: string = "gbp") => {// Helper function to get price infoconst getPriceInfo = (key: string, fallbackPrice: number) => {const priceObj = dynamicPrices.get(key);- const price = priceObj ? priceObj.unit_amount / 100 : fallbackPrice;+ const price = priceObj+ ? stripeAmountToMajor(priceObj.unit_amount, priceObj.currency)+ : fallbackPrice;const currencySymbol = priceObj? getCurrencySymbol(priceObj.currency)- : getCurrencySymbol(currency);+ : getCurrencySymbol("usd");return { price, currencySymbol };};diff --git a/frontend/editor/src/saas/services/billing.ts b/frontend/editor/src/saas/services/billing.tsindex ae7245d56a..c2198deb1a 100644--- a/frontend/editor/src/saas/services/billing.ts+++ b/frontend/editor/src/saas/services/billing.ts@@ -36,7 +36,7 @@ export async function createCheckoutSession(}>("create-checkout-session", {body: {team_id: params.teamId,- currency: params.currency ?? "gbp",+ currency: params.currency ?? "usd",success_url: returnUrl,cancel_url: returnUrl,...(params.billingOwnerEmail