Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6175: 修复 Billing UI 未展示 Workspace 订阅价格 (#6955)
Multica Eve6806dcbea900
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 4358804604..8b10f33090 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -977,4 +977,14 @@ describe("workspace subscription contract", () => {});expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();});++ it("rejects a prices response whose interval count is not one", async () => {+ stubFetchJson({+ month: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 3 },+ year: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },+ });+ const client = new ApiClient("https://api.example.test");++ expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();+ });});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 826a326c4a..bebdceee05 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2260,7 +2260,7 @@ const WorkspaceSubscriptionPriceSchema = (// quote a yearly amount as a monthly one — the schema is an independent// boundary, so it checks the correspondence itself.interval: z.literal(expected),- interval_count: z.number().int().positive(),+ interval_count: z.literal(1),}).loose().transform(diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 53ef0fd176..cd40346c0c 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -146,6 +146,10 @@"yearly": "Yearly","pro_for_team_one": "Pro for {{count}} human seat","pro_for_team_other": "Pro for {{count}} human seats",+ "price_loading": "Loading subscription prices",+ "unit_price": "{{price}} per human seat",+ "estimated_monthly_total": "Estimated monthly total: {{price}}",+ "estimated_yearly_total": "Estimated yearly total: {{price}}","price_at_checkout": "The server re-counts human members before purchase. Stripe Checkout shows the authoritative per-seat price and total before you pay."},"management": {diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 56b6b57757..b573eb66dd 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -144,6 +144,10 @@"monthly": "月払い","yearly": "年払い","pro_for_team_other": "{{count}}席で Pro を利用",+ "price_loading": "サブスクリプション価格を読み込んでいます",+ "unit_price": "1席あたり {{price}}",+ "estimated_monthly_total": "月払いの見積合計:{{price}}",+ "estimated_yearly_total": "年払いの見積合計:{{price}}","price_at_checkout": "購入前にサーバーがユーザーメンバーを再集計します。お支払い前に Stripe Checkout で正式な席単価と合計金額を確認できます。"},"management": {diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex dab75184df..9cd2db22d8 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -144,6 +144,10 @@"monthly": "월간","yearly": "연간","pro_for_team_other": "사용자 좌석 {{count}}개에 Pro 적용",+ "price_loading": "구독 가격을 불러오는 중",+ "unit_price": "사용자 좌석당 {{price}}",+ "estimated_monthly_total": "예상 월간 합계: {{price}}",+ "estimated_yearly_total": "예상 연간 합계: {{price}}","price_at_checkout": "구매 전에 서버가 사용자 멤버를 다시 계산합니다. 결제 전 Stripe Checkout에서 공식 좌석당 가격과 총액을 확인할 수 있습니다."},"management": {diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex a398b013a8..d040ed3253 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -144,6 +144,10 @@"monthly": "月付","yearly": "年付","pro_for_team_other": "为 {{count}} 个成员席位升级 Pro",+ "price_loading": "正在加载订阅价格",+ "unit_price": "每个成员席位 {{price}}",+ "estimated_monthly_total": "预计月付总额:{{price}}",+ "estimated_yearly_total": "预计年付总额:{{price}}","price_at_checkout": "购买前,服务端会重新统计成员。付款前,Stripe Checkout 会显示权威的单席位价格和总额。"},"management": {diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex c665eb413a..bb535461a9 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -14,6 +14,23 @@ const mocks = vi.hoisted(() => ({refetch: vi.fn(),openExternal: vi.fn(),role: "owner" as "owner" | "admin" | "member",+ workspaceId: "workspace-1",+ prices: null as {+ month: {+ currency: string;+ unitAmount: number;+ interval: "month";+ intervalCount: number;+ };+ year: {+ currency: string;+ unitAmount: number;+ interval: "year";+ intervalCount: number;+ };+ } | null,+ pricesLoading: false,+ pricesError: false,entitlements: {workspaceId: "workspace-1",plan: "free",@@ -35,6 +52,9 @@ vi.mock("@multica/core/billing", () => ({workspaceSubscriptionEntitlementsOptions: (wsId: string) => ({queryKey: ["workspace-subscriptions", wsId, "entitlements"],}),+ workspaceSubscriptionPricesOptions: (wsId: string) => ({+ queryKey: ["workspace-subscriptions", wsId, "prices"],+ }),useCreateWorkspaceSubscriptionCheckout: () => ({mutateAsync: mocks.checkout,isPending: false,@@ -51,7 +71,7 @@ vi.mock("@multica/core/billing", () => ({vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({- id: "workspace-1",+ id: mocks.workspaceId,slug: "acme",name: "Acme",}),@@ -78,13 +98,30 @@ vi.mock("../../navigation", () => ({vi.mock("../../platform", () => ({ openExternal: mocks.openExternal }));-import { BillingTab } from "./billing-tab";+import { BillingTab, formatStripeMinorAmount } from "./billing-tab";describe("BillingTab", () => {beforeEach(() => {vi.clearAllMocks();navigationState.search = "tab=billing";mocks.role = "owner";+ mocks.workspaceId = "workspace-1";+ mocks.prices = {+ month: {+ currency: "usd",+ unitAmount: 1000,+ interval: "month",+ intervalCount: 1,+ },+ year: {+ currency: "usd",+ unitAmount: 9600,+ interval: "year",+ intervalCount: 1,+ },+ };+ mocks.pricesLoading = false;+ mocks.pricesError = false;Object.assign(mocks.entitlements, {plan: "free",status: "inactive",@@ -95,11 +132,21 @@ describe("BillingTab", () => {snapshotExpiresAt: null,version: 0,});- mocks.useQuery.mockReturnValue({- data: mocks.entitlements,- isPending: false,- isError: false,- refetch: mocks.refetch,+ mocks.useQuery.mockImplementation((options: unknown) => {+ const queryKey = (options as { queryKey?: readonly unknown[] }).queryKey;+ if (queryKey?.[queryKey.length - 1] === "prices") {+ return {+ data: mocks.prices,+ isLoading: mocks.pricesLoading,+ isError: mocks.pricesError,+ };+ }+ return {+ data: mocks.entitlements,+ isPending: false,+ isError: false,+ refetch: mocks.refetch,+ };});mocks.checkout.mockResolvedValue({requestId: "request-1",@@ -129,16 +176,122 @@ describe("BillingTab", () => {expect(mocks.useQuery).not.toHaveBeenCalled();});- it("shows an honest Free plan without inventing prices or usage totals", () => {+ it("shows server prices and keeps the selected interval in sync", async () => {+ const user = userEvent.setup();renderWithI18n(<BillingTab />);expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();expect(screen.getByText("1,000")).toBeInTheDocument();expect(screen.getByText("100 / month")).toBeInTheDocument();+ expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();+ expect(+ screen.getByText("Estimated monthly total: $30.00"),+ ).toBeInTheDocument();+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryKey: ["workspace-subscriptions", "workspace-1", "prices"],+ }),+ );++ await user.click(screen.getByRole("button", { name: "Yearly" }));++ expect(screen.getByText("$96.00 per human seat")).toBeInTheDocument();+ expect(+ screen.getByText("Estimated yearly total: $288.00"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Estimated monthly total: $30.00"),+ ).not.toBeInTheDocument();+ });++ it("formats Stripe minor units for decimal, zero-decimal, and special currencies", () => {+ expect(formatStripeMinorAmount(1234, "usd", "en-US")).toBe("$12.34");+ expect(formatStripeMinorAmount(1234, "jpy", "en-US")).toBe("¥1,234");+ expect(+ formatStripeMinorAmount(1234, "bhd", "en-US")?.replace(/\s/g, " "),+ ).toBe("BHD 1.234");+ expect(+ formatStripeMinorAmount(500, "ugx", "en-US")?.replace(/\s/g, " "),+ ).toBe("UGX 5");+ expect(+ formatStripeMinorAmount(1234, "huf", "en-US")?.replace(/\s/g, " "),+ ).toBe("HUF 12.34");+ });++ it("shows a local price skeleton without blocking Checkout while prices load", () => {+ mocks.prices = null;+ mocks.pricesLoading = true;++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByRole("status", { name: "Loading subscription prices" }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Upgrade to Pro" }),+ ).toBeEnabled();+ });++ it.each([+ ["query error", true],+ ["malformed response", false],+ ])(+ "falls back safely after a prices %s without blocking Checkout",+ async (_case, isError) => {+ const user = userEvent.setup();+ mocks.prices = null;+ mocks.pricesError = isError;++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText(+ /Stripe Checkout shows the authoritative per-seat price/,+ ),+ ).toBeInTheDocument();+ expect(screen.queryByText(/\$0/)).not.toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(+ screen.getByRole("button", { name: "Continue to Stripe" }),+ );++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledOnce());+ },+ );++ it("uses workspace-scoped price query keys after a workspace switch", () => {+ const { rerender } = renderWithI18n(<BillingTab />);++ mocks.workspaceId = "workspace-2";+ rerender(<BillingTab />);++ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryKey: ["workspace-subscriptions", "workspace-2", "prices"],+ }),+ );+ });++ it("shows the unit price without a zero estimated total when seats are unavailable", () => {+ mocks.entitlements.seats = 0;++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();+ expect(screen.queryByText(/Estimated monthly total/)).not.toBeInTheDocument();+ expect(screen.queryByText(/\$0/)).not.toBeInTheDocument();+ });++ it("does not display a price whose recurrence is not every one interval", () => {+ if (mocks.prices) mocks.prices.month.intervalCount = 3;++ renderWithI18n(<BillingTab />);++ expect(screen.queryByText("$10.00 per human seat")).not.toBeInTheDocument();expect(screen.getByText(/Stripe Checkout shows the authoritative per-seat price/),).toBeInTheDocument();- expect(screen.queryByText("$10")).not.toBeInTheDocument();});it("creates Checkout with a client idempotency key and opens Stripe externally", async () => {@@ -157,6 +310,7 @@ describe("BillingTab", () => {};expect(request.interval).toBe("month");expect(request.idempotencyKey).toMatch(/^workspace-checkout-workspace-1-/);+ expect(Object.keys(request).sort()).toEqual(["idempotencyKey", "interval"]);expect(mocks.openExternal).toHaveBeenCalledWith("https://checkout.stripe.com/test-session",{ webTarget: "same-tab" },@@ -281,6 +435,7 @@ describe("BillingTab", () => {expect(screen.getByText("Read-only billing access")).toBeInTheDocument();expect(screen.getAllByText("3 members")).toHaveLength(2);+ expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),).not.toBeInTheDocument();@@ -308,6 +463,12 @@ describe("BillingTab", () => {expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),).not.toBeInTheDocument();+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryKey: ["workspace-subscriptions", "workspace-1", "prices"],+ enabled: false,+ }),+ );});it("keeps the billing portal available for a canceled Pro period", () => {diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 5893060d0b..328f42808b 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -17,6 +17,7 @@ import {useCreateWorkspaceSubscriptionPortal,useReconcileWorkspaceSubscriptionSeats,workspaceSubscriptionEntitlementsOptions,+ workspaceSubscriptionPricesOptions,} from "@multica/core/billing";import { useFeatureEnabled } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";@@ -53,6 +54,32 @@ import {const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;+const STRIPE_ZERO_DECIMAL_CURRENCIES = new Set([+ "BIF",+ "CLP",+ "DJF",+ "GNF",+ "JPY",+ "KMF",+ "KRW",+ "MGA",+ "PYG",+ "RWF",+ "VND",+ "VUV",+ "XAF",+ "XOF",+ "XPF",+]);+const STRIPE_TWO_DECIMAL_COMPAT_CURRENCIES = new Set(["ISK", "UGX"]);+const STRIPE_THREE_DECIMAL_CURRENCIES = new Set([+ "BHD",+ "JOD",+ "KWD",+ "OMR",+ "TND",+]);+type WorkspaceBillingReturnResult = "success" | "cancel" | "portal";function parseReturnResult(@@ -82,6 +109,49 @@ function formatDate(value: string | null, locale: string): string | null {return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(date);}+/**+ * Stripe API amounts use its own minor-unit contract: two decimals by default,+ * an explicit zero-decimal list, five three-decimal currencies, and ISK/UGX in+ * a backwards-compatible two-decimal representation. Intl localizes the+ * already-converted major amount; it must not decide the divisor.+ */+export function formatStripeMinorAmount(+ amount: number,+ currency: string,+ locale: string,+): string | null {+ if (!Number.isSafeInteger(amount) || amount < 0) return null;+ const normalizedCurrency = currency.trim().toUpperCase();+ if (!normalizedCurrency) return null;++ try {+ const fractionDigits = STRIPE_TWO_DECIMAL_COMPAT_CURRENCIES.has(+ normalizedCurrency,+ )+ ? 2+ : STRIPE_ZERO_DECIMAL_CURRENCIES.has(normalizedCurrency)+ ? 0+ : STRIPE_THREE_DECIMAL_CURRENCIES.has(normalizedCurrency)+ ? 3+ : 2;+ const majorAmount = amount / 10 ** fractionDigits;+ const showStripeFraction = !Number.isInteger(majorAmount);+ const formatter = new Intl.NumberFormat(locale, {+ style: "currency",+ currency: normalizedCurrency,+ ...(showStripeFraction+ ? {+ minimumFractionDigits: fractionDigits,+ maximumFractionDigits: fractionDigits,+ }+ : {}),+ });+ return formatter.format(majorAmount);+ } catch {+ return null;+ }+}+function planBadgeVariant(plan: string): "default" | "secondary" | "outline" {if (plan === "pro") return "default";if (plan === "free") return "secondary";@@ -207,10 +277,19 @@ function BillingTabContent() {...workspaceSubscriptionEntitlementsOptions(wsId),refetchInterval: isSyncingCheckout ? 2_000 : false,});+ const entitlements = entitlementQuery.data;+ const canUpgrade =+ entitlements?.plan === "free" &&+ entitlements.status !== "active" &&+ entitlements.status !== "trialing" &&+ entitlements.status !== "past_due";+ const pricesQuery = useQuery({+ ...workspaceSubscriptionPricesOptions(wsId),+ enabled: wsId.length > 0 && canUpgrade,+ });const checkoutMutation = useCreateWorkspaceSubscriptionCheckout(wsId);const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);const reconcileMutation = useReconcileWorkspaceSubscriptionSeats(wsId);- const entitlements = entitlementQuery.data;const refetchEntitlements = entitlementQuery.refetch;useEffect(() => {@@ -408,7 +487,6 @@ function BillingTabContent() {}const periodEnd = formatDate(entitlements.currentPeriodEnd, locale);- const isFree = entitlements.plan === "free";const isPro = entitlements.plan === "pro";const hasManagedSubscription =isPro ||@@ -419,6 +497,26 @@ function BillingTabContent() {checkoutMutation.isPending ||portalMutation.isPending ||reconcileMutation.isPending;+ const selectedPrice = pricesQuery.data?.[interval] ?? null;+ const formattedUnitPrice = selectedPrice+ ? formatStripeMinorAmount(+ selectedPrice.unitAmount,+ selectedPrice.currency,+ locale,+ )+ : null;+ const formattedEstimatedTotal =+ selectedPrice && entitlements.seats > 0+ ? formatStripeMinorAmount(+ selectedPrice.unitAmount * entitlements.seats,+ selectedPrice.currency,+ locale,+ )+ : null;+ const hasDisplayableUnitPrice =+ selectedPrice?.intervalCount === 1 && formattedUnitPrice !== null;+ const hasDisplayableEstimatedTotal =+ hasDisplayableUnitPrice && formattedEstimatedTotal !== null;return (<SettingsTab@@ -537,7 +635,7 @@ function BillingTabContent() {</SettingsCard></SettingsSection>- {isFree && !hasManagedSubscription ? (+ {canUpgrade ? (<SettingsSectiontitle={t(($) => $.workspace.upgrade.title)}description={t(($) => $.workspace.upgrade.description)}@@ -566,12 +664,40 @@ function BillingTabContent() {</button>))}</div>- <div className="space-y-1">+ <div className="space-y-2"><p className="text-body font-medium">{t(($) => $.workspace.upgrade.pro_for_team, {count: entitlements.seats,})}</p>+ {pricesQuery.isLoading ? (+ <div+ className="space-y-2 motion-reduce:[&_[data-slot=skeleton]]:animate-none"+ role="status"+ aria-label={t(($) => $.workspace.upgrade.price_loading)}+ >+ <Skeleton className="h-5 w-48" />+ <Skeleton className="h-4 w-64 max-w-full" />+ </div>+ ) : hasDisplayableUnitPrice ? (+ <div className="space-y-1">+ <p className="text-body font-semibold tabular-nums">+ {t(($) => $.workspace.upgrade.unit_price, {+ price: formattedUnitPrice,+ })}+ </p>+ {hasDisplayableEstimatedTotal ? (+ <p className="text-caption leading-5 text-muted-foreground tabular-nums">+ {t(+ interval === "month"+ ? ($) => $.workspace.upgrade.estimated_monthly_total+ : ($) => $.workspace.upgrade.estimated_yearly_total,+ { price: formattedEstimatedTotal },+ )}+ </p>+ ) : null}+ </div>+ ) : null}<p className="max-w-[65ch] text-caption leading-5 text-muted-foreground">{t(($) => $.workspace.upgrade.price_at_checkout)}</p>