Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(billing): Free / Pro / Business plans, checkout by plan, and plan switching (MUL-9484) (#10885)
Multica Eve38442ead47dc
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 1ab8e68523..9ad2fda51e 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -290,6 +290,10 @@ import type {WorkspaceSeatPurchasePreview,PurchaseWorkspaceSeatsRequest,PurchaseWorkspaceSeatsResponse,+ PreviewWorkspacePlanChangeRequest,+ WorkspacePlanChangePreview,+ ChangeWorkspacePlanRequest,+ ChangeWorkspacePlanResponse,CreateWorkspaceSubscriptionPortalResponse,SourceContextPreview,CreateCommentSubIssueManualRequest,@@ -445,6 +449,8 @@ import {WorkspaceSubscriptionSeatReconcileResultSchema,WorkspaceSeatPurchasePreviewSchema,PurchaseWorkspaceSeatsResponseSchema,+ WorkspacePlanChangePreviewSchema,+ ChangeWorkspacePlanResponseSchema,CreateWorkspaceSubscriptionPortalResponseSchema,DingTalkInstallationSchema,ListDingTalkInstallationsResponseSchema,@@ -2630,6 +2636,7 @@ export class ApiClient {{method: "POST",body: JSON.stringify({+ plan: data.plan,interval: data.interval,idempotency_key: data.idempotencyKey,}),@@ -2713,6 +2720,53 @@ export class ApiClient {);}+ async previewWorkspacePlanChange(+ data: PreviewWorkspacePlanChangeRequest,+ ): Promise<WorkspacePlanChangePreview | null> {+ const res = await this.fetchRaw(+ "/api/cloud-subscriptions/plan-changes/preview",+ {+ method: "POST",+ body: JSON.stringify({ plan: data.plan }),+ extraHeaders: { "Content-Type": "application/json" },+ },+ );+ const raw = (await res.json()) as unknown;+ return parseWithFallback<WorkspacePlanChangePreview | null>(+ raw,+ WorkspacePlanChangePreviewSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/plan-changes/preview" },+ );+ }++ async changeWorkspacePlan(+ data: ChangeWorkspacePlanRequest,+ ): Promise<ChangeWorkspacePlanResponse | null> {+ const res = await this.fetchRaw("/api/cloud-subscriptions/plan-changes", {+ method: "POST",+ body: JSON.stringify({+ plan: data.plan,+ expected_subscription_version: data.expectedSubscriptionVersion,+ quoted_at: data.quotedAt,+ accepted_proration_amount: data.acceptedProrationAmount,+ currency: data.currency,+ idempotency_key: data.idempotencyKey,+ }),+ extraHeaders: {+ "Content-Type": "application/json",+ "Idempotency-Key": data.idempotencyKey,+ },+ });+ const raw = (await res.json()) as unknown;+ return parseWithFallback<ChangeWorkspacePlanResponse | null>(+ raw,+ ChangeWorkspacePlanResponseSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/plan-changes" },+ );+ }+async createWorkspaceSubscriptionPortal(idempotencyKey: string,): Promise<CreateWorkspaceSubscriptionPortalResponse | null> {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 3b59ec61f1..cf10aa2ea6 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -1462,6 +1462,7 @@ describe("ApiClient schema fallback", () => {await expect(client.createWorkspaceSubscriptionCheckout({+ plan: "business",interval: "year",idempotencyKey: "checkout-intent-1",}),@@ -1477,6 +1478,7 @@ describe("ApiClient schema fallback", () => {};expect(init.headers["Idempotency-Key"]).toBe("checkout-intent-1");expect(JSON.parse(String(init.body))).toEqual({+ plan: "business",interval: "year",idempotency_key: "checkout-intent-1",});@@ -1495,6 +1497,7 @@ describe("ApiClient schema fallback", () => {await expect(client.createWorkspaceSubscriptionCheckout({+ plan: "pro",interval: "month",idempotencyKey: "checkout-intent-1",}),@@ -1595,6 +1598,7 @@ describe("workspace subscription contract", () => {checkout: false,portal: true,purchase_seats: false,+ change_plan: true,},});const client = new ApiClient("https://api.example.test");@@ -1624,7 +1628,82 @@ describe("workspace subscription contract", () => {checkout: false,portal: true,purchaseSeats: false,+ changePlan: true,+ checkPlanChange: false,});+ expect(summary?.planChange).toBeNull();+ });++ it("reads a plan change that still holds the subscription", async () => {+ stubFetchJson({+ entitlement,+ billing_interval: "month",+ human_members: 3,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: true,+ available_actions: {+ checkout: false,+ portal: true,+ purchase_seats: false,+ change_plan: false,+ check_plan_change: true,+ },+ plan_change: {+ target_plan: "business",+ state: "confirming",+ since: "2026-11-18T08:00:00Z",+ },+ });+ const client = new ApiClient("https://api.example.test");+ const summary = await client.getWorkspaceSubscriptionSummary();++ expect(summary?.availableActions.checkPlanChange).toBe(true);+ expect(summary?.planChange).toEqual({+ targetPlan: "business",+ state: "confirming",+ since: "2026-11-18T08:00:00Z",+ });+ });++ it.each([+ ["an unknown state", { target_plan: "business", state: "settling", since: "2026-11-18T08:00:00Z" }, "confirming"],+ ["a malformed hold", { state: "unresolved" }, null],+ ])("tolerates %s in plan_change", async (_name, planChange, expected) => {+ stubFetchJson({+ entitlement,+ billing_interval: "month",+ human_members: 3,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: true,+ available_actions: { checkout: false, portal: true, purchase_seats: false },+ plan_change: planChange,+ });+ const client = new ApiClient("https://api.example.test");+ const summary = await client.getWorkspaceSubscriptionSummary();++ expect(summary).not.toBeNull();+ expect(summary?.planChange?.state ?? null).toBe(expected);+ });++ it("offers no plan switch when cloud does not report change_plan", async () => {+ stubFetchJson({+ entitlement,+ billing_interval: "month",+ human_members: 3,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: true,+ available_actions: { checkout: false, portal: true, purchase_seats: false },+ });+ const client = new ApiClient("https://api.example.test");+ const summary = await client.getWorkspaceSubscriptionSummary();++ expect(summary?.availableActions.changePlan).toBe(false);});it("represents canceled subscriptions without current seat capacity", async () => {@@ -1722,21 +1801,32 @@ describe("workspace subscription contract", () => {).toBe("pro");});- it("maps validated prices and rejects a non-positive amount", async () => {- stubFetchJson({- month: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 1 },- year: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },- });+ const planPrices = (monthAmount: number, yearAmount: number) => ({+ month: { currency: "usd", unit_amount: monthAmount, interval: "month", interval_count: 1 },+ year: { currency: "usd", unit_amount: yearAmount, interval: "year", interval_count: 1 },+ });++ it("maps validated per-plan prices and rejects a non-positive amount", async () => {+ stubFetchJson({ pro: planPrices(1500, 14400), business: planPrices(3000, 28800) });const client = new ApiClient("https://api.example.test");const prices = await client.getWorkspaceSubscriptionPrices();- expect(prices?.month.unitAmount).toBe(2000);- expect(prices?.year.interval).toBe("year");+ expect(prices?.pro.month.unitAmount).toBe(1500);+ expect(prices?.pro.year.interval).toBe("year");+ expect(prices?.business.month.unitAmount).toBe(3000);+ expect(prices?.business.year.unitAmount).toBe(28800);// A zero or missing amount must not be rendered next to a purchase button.- stubFetchJson({- month: { currency: "usd", unit_amount: 0, interval: "month", interval_count: 1 },- year: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },- });+ stubFetchJson({ pro: planPrices(0, 14400), business: planPrices(3000, 28800) });+ expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();+ });++ it("rejects prices that omit a paid plan or use the retired flat shape", async () => {+ const client = new ApiClient("https://api.example.test");++ stubFetchJson({ pro: planPrices(1500, 14400) });+ expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();++ stubFetchJson(planPrices(1500, 14400));expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();});@@ -1745,30 +1835,163 @@ describe("workspace subscription contract", () => {// An interval outside the contract.stubFetchJson({- month: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 1 },- year: { currency: "usd", unit_amount: 20000, interval: "week", interval_count: 1 },+ pro: {+ month: { currency: "usd", unit_amount: 1500, interval: "month", interval_count: 1 },+ year: { currency: "usd", unit_amount: 14400, interval: "week", interval_count: 1 },+ },+ business: planPrices(3000, 28800),});expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();// Valid intervals in the wrong slots. Accepting this would let the UI quote// a yearly amount as the monthly price.stubFetchJson({- month: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },- year: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 1 },+ pro: planPrices(1500, 14400),+ business: {+ month: { currency: "usd", unit_amount: 28800, interval: "year", interval_count: 1 },+ year: { currency: "usd", unit_amount: 3000, interval: "month", interval_count: 1 },+ },});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 },+ pro: {+ month: { currency: "usd", unit_amount: 1500, interval: "month", interval_count: 3 },+ year: { currency: "usd", unit_amount: 14400, interval: "year", interval_count: 1 },+ },+ business: planPrices(3000, 28800),});const client = new ApiClient("https://api.example.test");expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();});+ it("maps plan change previews, including a downgrade credit", async () => {+ stubFetchJson({+ current_plan: "business",+ target_plan: "pro",+ interval: "year",+ seats: 4,+ subscription_version: 7,+ currency: "usd",+ proration_amount: -28800,+ next_invoice_amount: 57600,+ invoice_now: false,+ quoted_at: "2026-11-18T08:00:00Z",+ });+ const client = new ApiClient("https://api.example.test");+ await expect(+ client.previewWorkspacePlanChange({ plan: "pro" }),+ ).resolves.toEqual({+ currentPlan: "business",+ targetPlan: "pro",+ interval: "year",+ seats: 4,+ subscriptionVersion: 7,+ currency: "usd",+ prorationAmount: -28800,+ nextInvoiceAmount: 57600,+ invoiceNow: false,+ quotedAt: "2026-11-18T08:00:00Z",+ });+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(+ "https://api.example.test/api/cloud-subscriptions/plan-changes/preview",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ plan: "pro" }),+ }),+ );+ });++ it("returns null for a malformed plan change preview", async () => {+ const client = new ApiClient("https://api.example.test");+ const valid = {+ current_plan: "pro",+ target_plan: "business",+ interval: "month",+ seats: 3,+ subscription_version: 7,+ currency: "usd",+ proration_amount: 4500,+ next_invoice_amount: 9000,+ invoice_now: true,+ quoted_at: "2026-11-18T08:00:00Z",+ };++ for (const malformed of [+ { ...valid, target_plan: "enterprise" },+ { ...valid, target_plan: "pro" },+ { ...valid, proration_amount: 45.5 },+ { ...valid, invoice_now: undefined },+ { ...valid, currency: "USD" },+ ]) {+ stubFetchJson(malformed);+ expect(+ await client.previewWorkspacePlanChange({ plan: "business" }),+ ).toBeNull();+ }+ });++ it("confirms a plan change with the accepted quote and idempotency key", async () => {+ stubFetchJson({+ plan: "business",+ previous_plan: "pro",+ interval: "month",+ seats: 3,+ currency: "usd",+ proration_amount: 4500,+ invoice_now: true,+ });+ const client = new ApiClient("https://api.example.test");+ await expect(+ client.changeWorkspacePlan({+ plan: "business",+ expectedSubscriptionVersion: 7,+ quotedAt: "2026-11-18T08:00:00Z",+ acceptedProrationAmount: 4500,+ currency: "usd",+ idempotencyKey: "plan-change-1",+ }),+ ).resolves.toEqual({+ plan: "business",+ previousPlan: "pro",+ interval: "month",+ seats: 3,+ currency: "usd",+ prorationAmount: 4500,+ invoiceNow: true,+ });+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(+ "https://api.example.test/api/cloud-subscriptions/plan-changes",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ plan: "business",+ expected_subscription_version: 7,+ quoted_at: "2026-11-18T08:00:00Z",+ accepted_proration_amount: 4500,+ currency: "usd",+ idempotency_key: "plan-change-1",+ }),+ headers: expect.objectContaining({ "Idempotency-Key": "plan-change-1" }),+ }),+ );++ stubFetchJson({ plan: "free", previous_plan: "pro" });+ await expect(+ client.changeWorkspacePlan({+ plan: "business",+ expectedSubscriptionVersion: 7,+ quotedAt: "2026-11-18T08:00:00Z",+ acceptedProrationAmount: 4500,+ currency: "usd",+ idempotencyKey: "plan-change-2",+ }),+ ).resolves.toBeNull();+ });+it("maps seat purchase previews and confirmations without trusting client totals", async () => {stubFetchJson({current_seats: 5,diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 9260c242b1..f05ab6b81d 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -40,8 +40,11 @@ import type {WorkspaceFeatures,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,+ WorkspaceSubscriptionPlanPrices,WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutResponse,+ WorkspacePlanChangePreview,+ ChangeWorkspacePlanResponse,WorkspaceSubscriptionSeatReconcileResult,WorkspaceSeatPurchasePreview,PurchaseWorkspaceSeatsResponse,@@ -3574,6 +3577,7 @@ export const EMPTY_CREATE_BILLING_PORTAL_SESSION_RESPONSE: CreateBillingPortalSe// surface as unknown rather than be coerced into a known one.const WorkspaceSubscriptionIntervalSchema = z.enum(["month", "year"]);+const WorkspaceSubscriptionPaidPlanSchema = z.enum(["pro", "business"]);// Stripe hosts Checkout and Portal, so those URLs leave the app. `z.string()// .url()` is not enough on its own — `new URL("javascript:...")` parses — and@@ -3667,7 +3671,24 @@ export const WorkspaceSubscriptionSummarySchema = zcheckout: z.boolean(),portal: z.boolean(),purchase_seats: z.boolean(),+ // Absent on a cloud that predates plan switching: no switch is offered.+ change_plan: z.boolean().optional(),+ check_plan_change: z.boolean().optional(),}).loose(),+ // Absent on an older cloud, and a malformed value reads as no hold: the+ // server still refuses the operations a hold blocks.+ plan_change: z+ .object({+ target_plan: z.string().min(1),+ // An unknown state from a newer cloud is shown as still confirming,+ // the state that asks the user to wait rather than act.+ state: z.enum(["confirming", "unresolved"]).catch("confirming"),+ since: z.string().min(1),+ })+ .loose()+ .nullable()+ .optional()+ .catch(null),}).loose().transform(@@ -3704,7 +3725,16 @@ export const WorkspaceSubscriptionSummarySchema = zcheckout: value.available_actions.checkout,portal: value.available_actions.portal,purchaseSeats: value.available_actions.purchase_seats,+ changePlan: value.available_actions.change_plan ?? false,+ checkPlanChange: value.available_actions.check_plan_change ?? false,},+ planChange: value.plan_change+ ? {+ targetPlan: value.plan_change.target_plan,+ state: value.plan_change.state,+ since: value.plan_change.since,+ }+ : null,}),);@@ -3784,19 +3814,34 @@ const WorkspaceSubscriptionPriceSchema = (}),);-export const WorkspaceSubscriptionPricesSchema = z+const WorkspaceSubscriptionPlanPricesSchema = z.object({month: WorkspaceSubscriptionPriceSchema("month"),year: WorkspaceSubscriptionPriceSchema("year"),}).loose().transform(- (value): WorkspaceSubscriptionPrices => ({+ (value): WorkspaceSubscriptionPlanPrices => ({month: value.month,year: value.year,}),);+// Every paid plan must be priced: a response missing one plan reads as "prices+// unavailable" as a whole rather than offering one plan without the other.+export const WorkspaceSubscriptionPricesSchema = z+ .object({+ pro: WorkspaceSubscriptionPlanPricesSchema,+ business: WorkspaceSubscriptionPlanPricesSchema,+ })+ .loose()+ .transform(+ (value): WorkspaceSubscriptionPrices => ({+ pro: value.pro,+ business: value.business,+ }),+ );+// An unknown state from a newer server reads as available: the server still// enforces on write, so the worst case is an upgrade prompt after the attempt// instead of before it. A malformed entry is dropped the same way.@@ -3897,6 +3942,62 @@ export const PurchaseWorkspaceSeatsResponseSchema = z}),);+export const WorkspacePlanChangePreviewSchema = z+ .object({+ current_plan: WorkspaceSubscriptionPaidPlanSchema,+ target_plan: WorkspaceSubscriptionPaidPlanSchema,+ interval: WorkspaceSubscriptionIntervalSchema,+ seats: z.number().int().positive(),+ subscription_version: z.number().int().positive(),+ currency: z.string().regex(/^[a-z]{3}$/),+ // Negative for a downgrade: the unused difference is a credit.+ proration_amount: z.number().int(),+ next_invoice_amount: z.number().int().nonnegative(),+ invoice_now: z.boolean(),+ quoted_at: z.string().min(1),+ })+ .loose()+ .refine((value) => value.current_plan !== value.target_plan, {+ message: "plan change preview must name two different plans",+ })+ .transform(+ (value): WorkspacePlanChangePreview => ({+ currentPlan: value.current_plan,+ targetPlan: value.target_plan,+ interval: value.interval,+ seats: value.seats,+ subscriptionVersion: value.subscription_version,+ currency: value.currency,+ prorationAmount: value.proration_amount,+ nextInvoiceAmount: value.next_invoice_amount,+ invoiceNow: value.invoice_now,+ quotedAt: value.quoted_at,+ }),+ );++export const ChangeWorkspacePlanResponseSchema = z+ .object({+ plan: WorkspaceSubscriptionPaidPlanSchema,+ previous_plan: WorkspaceSubscriptionPaidPlanSchema,+ interval: WorkspaceSubscriptionIntervalSchema,+ seats: z.number().int().positive(),+ currency: z.string().regex(/^[a-z]{3}$/),+ proration_amount: z.number().int(),+ invoice_now: z.boolean(),+ })+ .loose()+ .transform(+ (value): ChangeWorkspacePlanResponse => ({+ plan: value.plan,+ previousPlan: value.previous_plan,+ interval: value.interval,+ seats: value.seats,+ currency: value.currency,+ prorationAmount: value.proration_amount,+ invoiceNow: value.invoice_now,+ }),+ );+export const CreateWorkspaceSubscriptionPortalResponseSchema = z.object({url: StripeHostedURLSchema,diff --git a/packages/core/billing/recovery.test.ts b/packages/core/billing/recovery.test.tsindex 4278e09a5d..7295f92764 100644--- a/packages/core/billing/recovery.test.ts+++ b/packages/core/billing/recovery.test.ts@@ -6,8 +6,17 @@ const actions = (checkout: boolean;portal: boolean;purchaseSeats: boolean;+ changePlan: boolean;+ checkPlanChange: boolean;}> = {},-) => ({ checkout: false, portal: false, purchaseSeats: false, ...overrides });+) => ({+ checkout: false,+ portal: false,+ purchaseSeats: false,+ changePlan: false,+ checkPlanChange: false,+ ...overrides,+});describe("resolveBillingRecovery", () => {it("fails closed when workspace billing is disabled", () => {diff --git a/packages/core/billing/workspace-subscription-mutations.ts b/packages/core/billing/workspace-subscription-mutations.tsindex 7f693965d1..55a8ef331a 100644--- a/packages/core/billing/workspace-subscription-mutations.ts+++ b/packages/core/billing/workspace-subscription-mutations.ts@@ -1,7 +1,9 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { api } from "../api";import type {+ ChangeWorkspacePlanRequest,CreateWorkspaceSubscriptionCheckoutRequest,+ PreviewWorkspacePlanChangeRequest,PreviewWorkspaceSeatPurchaseRequest,PurchaseWorkspaceSeatsRequest,} from "../types";@@ -52,6 +54,31 @@ export function usePurchaseWorkspaceSeats(wsId: string) {});}+export function usePreviewWorkspacePlanChange() {+ return useMutation({+ mutationFn: (data: PreviewWorkspacePlanChangeRequest) =>+ api.previewWorkspacePlanChange(data),+ });+}++/**+ * Cloud persists the new plan before answering, so refreshing the whole+ * workspace subscription scope (summary and anything keyed under it) shows the+ * switched plan without waiting for Stripe's webhook.+ */+export function useChangeWorkspacePlan(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (data: ChangeWorkspacePlanRequest) =>+ api.changeWorkspacePlan(data),+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: workspaceSubscriptionKeys.all(wsId),+ });+ },+ });+}+export function useCreateWorkspaceSubscriptionPortal(wsId: string) {const queryClient = useQueryClient();return useMutation({diff --git a/packages/core/billing/workspace-subscription-queries.test.ts b/packages/core/billing/workspace-subscription-queries.test.tsindex 274ec42a3d..f13a8ec06a 100644--- a/packages/core/billing/workspace-subscription-queries.test.ts+++ b/packages/core/billing/workspace-subscription-queries.test.ts@@ -4,20 +4,26 @@ import {workspaceSubscriptionPricesStaleTime,} from "./workspace-subscription-queries";+const planPrices = (monthAmount: number, yearAmount: number) =>+ ({+ month: {+ currency: "usd",+ unitAmount: monthAmount,+ interval: "month",+ intervalCount: 1,+ },+ year: {+ currency: "usd",+ unitAmount: yearAmount,+ interval: "year",+ intervalCount: 1,+ },+ }) as const;+const validPrices = {- month: {- currency: "usd",- unitAmount: 1_000,- interval: "month",- intervalCount: 1,- },- year: {- currency: "usd",- unitAmount: 9_600,- interval: "year",- intervalCount: 1,- },-} as const;+ pro: planPrices(1_500, 14_400),+ business: planPrices(3_000, 28_800),+};describe("workspace subscription price query", () => {it("keeps missing price responses stale so the UI can recover", () => {diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex cef631d863..33e6d8b9b0 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -194,6 +194,13 @@ export interface CreateBillingPortalSessionResponse {export type WorkspaceSubscriptionInterval = "month" | "year";+/**+ * A plan a workspace can buy or switch to. Free is not purchasable: it is what+ * a workspace has without an active subscription. `entitlement.plan` stays an+ * open string because Cloud may report plans this client does not know.+ */+export type WorkspaceSubscriptionPaidPlan = "pro" | "business";+export type WorkspaceEntitlementLimit =| { mode: "limited"; limit: number }| { mode: "unlimited"; limit: null };@@ -237,7 +244,26 @@ export interface WorkspaceSubscriptionSummary {checkout: boolean;portal: boolean;purchaseSeats: boolean;+ /** Switch the active subscription between Pro and Business. */+ changePlan: boolean;+ /** Ask Cloud to settle a plan change that is still confirming. */+ checkPlanChange: boolean;};+ /**+ * A plan change that still holds the subscription. While present, seat+ * purchases and other plan changes are unavailable.+ */+ planChange: WorkspacePlanChangeHold | null;+}++export interface WorkspacePlanChangeHold {+ targetPlan: string;+ /**+ * "confirming": Cloud is establishing Stripe's outcome. "unresolved": Cloud+ * could not, and support has to settle it.+ */+ state: "confirming" | "unresolved";+ since: string;}export interface WorkspaceSeatCapacity {@@ -270,12 +296,18 @@ export interface WorkspaceSubscriptionPrice {intervalCount: number;}-export interface WorkspaceSubscriptionPrices {+export interface WorkspaceSubscriptionPlanPrices {month: WorkspaceSubscriptionPrice;year: WorkspaceSubscriptionPrice;}+export type WorkspaceSubscriptionPrices = Record<+ WorkspaceSubscriptionPaidPlan,+ WorkspaceSubscriptionPlanPrices+>;+export interface CreateWorkspaceSubscriptionCheckoutRequest {+ plan: WorkspaceSubscriptionPaidPlan;interval: WorkspaceSubscriptionInterval;idempotencyKey: string;}@@ -323,6 +355,52 @@ export interface PurchaseWorkspaceSeatsResponse {status: "pending" | "submitted" | "confirmed";}+export interface PreviewWorkspacePlanChangeRequest {+ plan: WorkspaceSubscriptionPaidPlan;+}++/**+ * Cloud's quote for switching the active subscription to another plan. Seats+ * and the billing interval stay the same.+ */+export interface WorkspacePlanChangePreview {+ currentPlan: WorkspaceSubscriptionPaidPlan;+ targetPlan: WorkspaceSubscriptionPaidPlan;+ interval: WorkspaceSubscriptionInterval;+ seats: number;+ subscriptionVersion: number;+ currency: string;+ /**+ * Proration in minor currency units. Positive for an upgrade, charged now;+ * negative for a downgrade, credited against the next invoice.+ */+ prorationAmount: number;+ /** Next full recurring invoice on the target plan, in minor units. */+ nextInvoiceAmount: number;+ /** True when the proration is invoiced immediately (upgrades). */+ invoiceNow: boolean;+ quotedAt: string;+}++export interface ChangeWorkspacePlanRequest {+ plan: WorkspaceSubscriptionPaidPlan;+ expectedSubscriptionVersion: number;+ quotedAt: string;+ acceptedProrationAmount: number;+ currency: string;+ idempotencyKey: string;+}++export interface ChangeWorkspacePlanResponse {+ plan: WorkspaceSubscriptionPaidPlan;+ previousPlan: WorkspaceSubscriptionPaidPlan;+ interval: WorkspaceSubscriptionInterval;+ seats: number;+ currency: string;+ prorationAmount: number;+ invoiceNow: boolean;+}+export interface WorkspaceSubscriptionSeatReconcileResult {workspaceId: string;action: string;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 29ea25d004..c8b66740c7 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -406,6 +406,7 @@ export type {BillingCheckoutSessionStatus,CreateBillingPortalSessionResponse,WorkspaceSubscriptionInterval,+ WorkspaceSubscriptionPaidPlan,WorkspaceEntitlementLimitMode,WorkspaceEntitlementLimit,WorkspaceSubscriptionEntitlements,@@ -413,13 +414,19 @@ export type {WorkspaceSeatCapacity,WorkspaceSeatPurchaseSummary,WorkspaceSubscriptionPrice,+ WorkspaceSubscriptionPlanPrices,WorkspaceSubscriptionPrices,+ WorkspacePlanChangeHold,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,PreviewWorkspaceSeatPurchaseRequest,WorkspaceSeatPurchasePreview,PurchaseWorkspaceSeatsRequest,PurchaseWorkspaceSeatsResponse,+ PreviewWorkspacePlanChangeRequest,+ WorkspacePlanChangePreview,+ ChangeWorkspacePlanRequest,+ ChangeWorkspacePlanResponse,WorkspaceSubscriptionSeatReconcileResult,CreateWorkspaceSubscriptionPortalResponse,PaidFeature,diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex d8e9cceed6..42fc0106cf 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Free","pro": "Pro",+ "business": "Business","unknown": "Unknown plan"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "Retry","retry_autopilots": "Retry automation usage",- "upgrade": "Upgrade to Pro",+ "upgrade_to": "Upgrade to {{plan}}",+ "switch_to": "Switch to {{plan}}","manage": "Manage billing","add_seats": "Add seats","cancel": "Cancel",- "continue_to_stripe": "Continue to Stripe"+ "continue_to_stripe": "Continue to Stripe",+ "check_status": "Check status"},"errors": {"action_title": "Billing action failed",@@ -52,13 +55,13 @@"syncing_title": "Activating your subscription","syncing_description": "Payment is complete. We're waiting for Stripe to confirm the plan change.","timeout_description": "Payment was received, but the subscription is still syncing. Refresh this page in a moment.",- "active_title": "Pro is active",- "active_description": "This workspace now has Pro access."+ "active_title": "{{plan}} is active",+ "active_description": "This workspace now has {{plan}} access."},"past_due": {"title": "Payment needs attention","description": "Update your payment method in billing management.",- "grace_description": "Update your payment method by {{date}} to keep Pro access."+ "grace_description": "Update your payment method by {{date}} to keep your paid plan."},"subscription_notice": {"canceling_title": "Cancellation is scheduled",@@ -67,7 +70,7 @@"incomplete_title": "Subscription setup is incomplete","incomplete_description": "Open billing management to finish or review the payment setup.","incomplete_expired_title": "Subscription setup expired",- "incomplete_expired_description": "The previous payment setup expired without activating Pro. Start a new upgrade when ready.",+ "incomplete_expired_description": "The previous payment setup expired before the subscription started. Start a new upgrade when ready.","paused_title": "Subscription is paused","paused_description": "Open billing management to review the pause and available recovery options.","unpaid_title": "Subscription is unpaid",@@ -82,19 +85,37 @@"member_count_one": "{{count}} member","member_count_other": "{{count}} members","billing_interval": "Billing interval",- "period_end": "Current period ends"+ "period_end": "Current period ends",+ "change_plan": "Change plan",+ "business_adds": "Business adds private projects, member-level access, team app accounts, and higher automation limits.",+ "plan_change_hold": "Plan change",+ "plan_change_confirming": "Switching to {{plan}}. Waiting for Stripe to confirm; seats and the plan can't be changed until then.",+ "plan_change_unresolved": "The switch to {{plan}} could not be confirmed. Contact support to settle it; seats and the plan can't be changed until then.",+ "plan_change_state_confirming": "Confirming",+ "plan_change_state_unresolved": "Needs support"},"upgrade": {- "title": "Upgrade to Pro",- "description": "Choose a billing interval, then confirm the current seats and final amount in Stripe Checkout.",+ "title": "Upgrade","interval_label": "Billing interval","monthly": "Monthly","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",- "price_at_checkout": "The server re-counts human members before purchase. Stripe Checkout shows the authoritative per-seat price and total before you pay."+ "unit_price_month": "{{price}} per human seat / month",+ "unit_price_year_monthly": "{{price}} per human seat / month, billed yearly",+ "unit_price_year": "{{price}} per human seat / year",+ "price_at_checkout": "The server re-counts human members before purchase. Stripe Checkout shows the authoritative per-seat price and total before you pay.",+ "recommended": "Recommended",+ "features": {+ "pro_members": "Unlimited members",+ "pro_autopilots": "1,000 automation runs per member each month",+ "pro_storage": "10 GB of attachment storage per member",+ "pro_dashboard": "90 days of dashboard history",+ "business_everything": "Everything in Pro",+ "business_access": "Private projects and member-level access",+ "business_apps": "Team app accounts and approval rules",+ "business_autopilots": "3,000 automation runs per member each month",+ "business_reports": "Usage and cost reports by member"+ }},"management": {"title": "Subscription management",@@ -153,6 +174,7 @@"preview_failed": "The estimate is temporarily unavailable. Retry in a moment.","capacity_out_of_sync": "The seat count in Stripe does not match the billing record. Contact support before retrying this purchase.","in_progress": "Another seat purchase is being processed. Wait for it to finish; contact support if it remains here.",+ "plan_change_in_progress": "A plan change is still being processed. Try again in a few minutes.","purchase_unreadable": "The purchase response could not be read. Retry this quote; the same purchase request will be reused.","purchase_failed": "Seats could not be added. Retry with the same quote, or refresh if it has expired.","payment_failed": "Payment could not be completed. Update the payment method in Stripe, then request a new quote.",@@ -171,11 +193,36 @@"delayed_description_with_expiry": "Automatic checking has stopped. If the attempt is still pending after {{date}}, reload this page before requesting another quote; contact support if it remains pending.","submitted_one": "A purchase for {{count}} seat was submitted. The new capacity appears after Stripe confirms it.","submitted_other": "A purchase for {{count}} seats was submitted. The new capacity appears after Stripe confirms it.",- "error_title": "Could not update the estimate"+ "error_title": "Could not update the estimate",+ "plan_change_unresolved": "A plan change could not be confirmed. Contact support before adding seats."+ },+ "plan_change": {+ "upgrade_description": "Takes effect immediately. The difference for the rest of this billing period is charged now.",+ "downgrade_description": "Takes effect immediately. The unused difference is credited to your next invoice. Business settings you already configured keep working but become read-only.",+ "seats": "Seats",+ "charge_today": "Charged today",+ "credit": "Credit on next invoice",+ "next_invoice": "Next renewal",+ "tax_notice": "Stripe determines taxes, credits, and final invoice details.",+ "preview_loading": "Loading quote...",+ "preview_failed": "The quote is temporarily unavailable. Retry in a moment.",+ "rate_limited": "Too many quote requests. Wait a moment, then retry.",+ "in_progress": "A seat purchase is being processed. Try again after it finishes.",+ "change_in_progress": "A plan change is still being processed. Try again in a few minutes.",+ "not_active": "This subscription can't change plans right now. The current plan has been refreshed.",+ "quote_changed": "The subscription or price changed. Review the refreshed quote before confirming again.",+ "payment_failed": "Payment could not be completed. Update the payment method in billing management, then try again.",+ "failed": "The plan could not be changed. Retry with the same quote.",+ "unreadable": "The response could not be read. Retry; the same request will be reused.",+ "error_title": "Could not change the plan",+ "success_title": "Plan changed",+ "success_description": "This workspace is now on {{plan}}.",+ "unresolved": "The previous plan change could not be confirmed. Contact support before changing plans.",+ "check_failed": "Could not check the plan change. Try again."},"confirm": {"title": "Continue to Stripe Checkout?",- "description": "Billing interval: {{interval}}. Current human members: {{count}}. Stripe will re-count seats and show the final amount before payment."+ "description": "Plan: {{plan}}. Billing interval: {{interval}}. Current human members: {{count}}. Stripe will re-count seats and show the final amount before payment."}},"return_page": {diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 65f62fcc4a..400d3ca569 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Gratis","pro": "Pro",+ "business": "Business","unknown": "Plan desconocido"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "Reintentar","retry_autopilots": "Reintentar el uso de automatización",- "upgrade": "Actualizar a Pro",+ "upgrade_to": "Actualizar a {{plan}}",+ "switch_to": "Cambiar a {{plan}}","manage": "Gestionar facturación","add_seats": "Añadir puestos","cancel": "Cancelar",- "continue_to_stripe": "Continuar a Stripe"+ "continue_to_stripe": "Continuar a Stripe",+ "check_status": "Comprobar estado"},"errors": {"action_title": "La acción de facturación falló",@@ -52,13 +55,13 @@"syncing_title": "Activando tu suscripción","syncing_description": "El pago se ha completado. Estamos esperando a que Stripe confirme el cambio de plan.","timeout_description": "Se recibió el pago, pero la suscripción aún se está sincronizando. Actualiza esta página en un momento.",- "active_title": "Pro está activo",- "active_description": "Este espacio de trabajo ya tiene acceso a Pro."+ "active_title": "{{plan}} está activo",+ "active_description": "Este espacio de trabajo ya tiene acceso a {{plan}}."},"past_due": {"title": "El pago necesita atención","description": "Actualiza tu método de pago en la gestión de facturación.",- "grace_description": "Actualiza tu método de pago antes del {{date}} para mantener el acceso a Pro."+ "grace_description": "Actualiza tu método de pago antes del {{date}} para mantener tu plan de pago."},"subscription_notice": {"canceling_title": "La cancelación está programada",@@ -67,7 +70,7 @@"incomplete_title": "La configuración de la suscripción está incompleta","incomplete_description": "Abre la gestión de facturación para terminar o revisar la configuración del pago.","incomplete_expired_title": "La configuración de la suscripción caducó",- "incomplete_expired_description": "La configuración de pago anterior caducó sin activar Pro. Inicia una nueva actualización cuando quieras.",+ "incomplete_expired_description": "La configuración de pago anterior caducó antes de que empezara la suscripción. Inicia una nueva actualización cuando quieras.","paused_title": "La suscripción está en pausa","paused_description": "Abre la gestión de facturación para revisar la pausa y las opciones de recuperación disponibles.","unpaid_title": "La suscripción está sin pagar",@@ -82,19 +85,37 @@"member_count_one": "{{count}} miembro","member_count_other": "{{count}} miembros","billing_interval": "Intervalo de facturación",- "period_end": "El periodo actual termina"+ "period_end": "El periodo actual termina",+ "change_plan": "Cambiar de plan",+ "business_adds": "Business añade proyectos privados, acceso por miembro, cuentas de apps del equipo y límites de automatización más altos.",+ "plan_change_hold": "Cambio de plan",+ "plan_change_confirming": "Cambiando a {{plan}}. Esperando la confirmación de Stripe; hasta entonces no se pueden cambiar los puestos ni el plan.",+ "plan_change_unresolved": "No se ha podido confirmar el cambio a {{plan}}. Contacta con soporte para resolverlo; hasta entonces no se pueden cambiar los puestos ni el plan.",+ "plan_change_state_confirming": "Confirmando",+ "plan_change_state_unresolved": "Requiere soporte"},"upgrade": {- "title": "Actualizar a Pro",- "description": "Elige un intervalo de facturación y luego confirma los puestos actuales y el importe final en Stripe Checkout.",+ "title": "Actualizar","interval_label": "Intervalo de facturación","monthly": "Mensual","yearly": "Anual",- "pro_for_team_one": "Pro para {{count}} puesto humano",- "pro_for_team_other": "Pro para {{count}} puestos humanos","price_loading": "Cargando precios de suscripción",- "unit_price": "{{price}} por puesto humano",- "price_at_checkout": "El servidor vuelve a contar los miembros humanos antes de la compra. Stripe Checkout muestra el precio por puesto y el total autorizados antes de que pagues."+ "unit_price_month": "{{price}} por puesto humano / mes",+ "unit_price_year_monthly": "{{price}} por puesto humano / mes, facturado anualmente",+ "unit_price_year": "{{price}} por puesto humano / año",+ "price_at_checkout": "El servidor vuelve a contar los miembros humanos antes de la compra. Stripe Checkout muestra el precio por puesto y el total autorizados antes de que pagues.",+ "recommended": "Recomendado",+ "features": {+ "pro_members": "Miembros ilimitados",+ "pro_autopilots": "1.000 ejecuciones de automatización por miembro al mes",+ "pro_storage": "10 GB de almacenamiento de adjuntos por miembro",+ "pro_dashboard": "90 días de historial en el panel",+ "business_everything": "Todo lo incluido en Pro",+ "business_access": "Proyectos privados y acceso por miembro",+ "business_apps": "Cuentas de apps del equipo y reglas de aprobación",+ "business_autopilots": "3.000 ejecuciones de automatización por miembro al mes",+ "business_reports": "Informes de uso y coste por miembro"+ }},"management": {"title": "Gestión de la suscripción",@@ -153,6 +174,7 @@"preview_failed": "El cálculo no está disponible temporalmente. Reintenta en un momento.","capacity_out_of_sync": "El número de puestos en Stripe no coincide con el registro de facturación. Contacta con soporte antes de reintentar esta compra.","in_progress": "Se está procesando otra compra de puestos. Espera a que termine; contacta con soporte si sigue así.",+ "plan_change_in_progress": "Todavía se está procesando un cambio de plan. Vuelve a intentarlo en unos minutos.","purchase_unreadable": "No se ha podido leer la respuesta de la compra. Reintenta este presupuesto; se reutilizará la misma solicitud de compra.","purchase_failed": "No se han podido añadir los puestos. Reintenta con el mismo presupuesto, o actualiza si ha caducado.","payment_failed": "No se ha podido completar el pago. Actualiza el método de pago en Stripe y solicita un presupuesto nuevo.",@@ -171,11 +193,36 @@"delayed_description_with_expiry": "La comprobación automática se ha detenido. Si el intento sigue pendiente después del {{date}}, recarga esta página antes de solicitar otro presupuesto; contacta con soporte si sigue pendiente.","submitted_one": "Se ha enviado una compra de {{count}} puesto. La nueva capacidad aparecerá cuando Stripe la confirme.","submitted_other": "Se ha enviado una compra de {{count}} puestos. La nueva capacidad aparecerá cuando Stripe la confirme.",- "error_title": "No se ha podido actualizar el cálculo"+ "error_title": "No se ha podido actualizar el cálculo",+ "plan_change_unresolved": "No se ha podido confirmar un cambio de plan. Contacta con soporte antes de añadir puestos."+ },+ "plan_change": {+ "upgrade_description": "Se aplica de inmediato. La diferencia del resto de este periodo de facturación se cobra ahora.",+ "downgrade_description": "Se aplica de inmediato. La diferencia no utilizada se abona en tu próxima factura. La configuración de Business que ya tienes sigue funcionando, pero pasa a ser de solo lectura.",+ "seats": "Puestos",+ "charge_today": "Cobro de hoy",+ "credit": "Abono en la próxima factura",+ "next_invoice": "Próxima renovación",+ "tax_notice": "Stripe determina los impuestos, créditos y detalles finales de la factura.",+ "preview_loading": "Cargando el presupuesto...",+ "preview_failed": "El presupuesto no está disponible temporalmente. Vuelve a intentarlo en un momento.",+ "rate_limited": "Demasiadas solicitudes de presupuesto. Espera un momento y vuelve a intentarlo.",+ "in_progress": "Se está procesando una compra de puestos. Vuelve a intentarlo cuando termine.",+ "change_in_progress": "Todavía se está procesando un cambio de plan. Vuelve a intentarlo en unos minutos.",+ "not_active": "Esta suscripción no puede cambiar de plan ahora. Se ha actualizado el plan actual.",+ "quote_changed": "La suscripción o el precio han cambiado. Revisa el presupuesto actualizado antes de confirmar de nuevo.",+ "payment_failed": "No se ha podido completar el pago. Actualiza el método de pago en la gestión de facturación y vuelve a intentarlo.",+ "failed": "No se ha podido cambiar el plan. Vuelve a intentarlo con el mismo presupuesto.",+ "unreadable": "No se ha podido leer la respuesta. Vuelve a intentarlo; se reutilizará la misma solicitud.",+ "error_title": "No se ha podido cambiar el plan",+ "success_title": "Plan cambiado",+ "success_description": "Este espacio de trabajo ahora usa {{plan}}.",+ "unresolved": "No se ha podido confirmar el cambio de plan anterior. Contacta con soporte antes de cambiar de plan.",+ "check_failed": "No se ha podido comprobar el cambio de plan. Vuelve a intentarlo."},"confirm": {"title": "¿Continuar a Stripe Checkout?",- "description": "Intervalo de facturación: {{interval}}. Miembros humanos actuales: {{count}}. Stripe volverá a contar los puestos y mostrará el importe final antes del pago."+ "description": "Plan: {{plan}}. Intervalo de facturación: {{interval}}. Miembros humanos actuales: {{count}}. Stripe volverá a contar los puestos y mostrará el importe final antes del pago."}},"return_page": {diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex 53c1dd04cf..f3b6ac9e7e 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Gratuit","pro": "Pro",+ "business": "Business","unknown": "Forfait inconnu"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "Réessayer","retry_autopilots": "Réessayer le chargement de la consommation des automatisations",- "upgrade": "Passer à Pro",+ "upgrade_to": "Passer à {{plan}}",+ "switch_to": "Basculer vers {{plan}}","manage": "Gérer la facturation","add_seats": "Ajouter des sièges","cancel": "Annuler",- "continue_to_stripe": "Continuer vers Stripe"+ "continue_to_stripe": "Continuer vers Stripe",+ "check_status": "Vérifier l'état"},"errors": {"action_title": "Échec de l'action de facturation",@@ -52,13 +55,13 @@"syncing_title": "Activation de votre abonnement","syncing_description": "Le paiement est terminé. Nous attendons que Stripe confirme le changement de forfait.","timeout_description": "Le paiement a été reçu, mais l'abonnement est encore en cours de synchronisation. Actualisez cette page dans un instant.",- "active_title": "Pro est actif",- "active_description": "Cet espace de travail a désormais accès à Pro."+ "active_title": "{{plan}} est actif",+ "active_description": "Cet espace de travail a désormais accès à {{plan}}."},"past_due": {"title": "Le paiement demande votre attention","description": "Mettez à jour votre moyen de paiement dans la gestion de la facturation.",- "grace_description": "Mettez à jour votre moyen de paiement avant le {{date}} pour conserver l'accès Pro."+ "grace_description": "Mettez à jour votre moyen de paiement avant le {{date}} pour conserver votre forfait payant."},"subscription_notice": {"canceling_title": "Résiliation programmée",@@ -67,7 +70,7 @@"incomplete_title": "La configuration de l'abonnement est incomplète","incomplete_description": "Ouvrez la gestion de la facturation pour terminer ou vérifier la configuration du paiement.","incomplete_expired_title": "La configuration de l'abonnement a expiré",- "incomplete_expired_description": "La configuration du paiement précédente a expiré sans activer Pro. Lancez une nouvelle mise à niveau lorsque vous serez prêt.",+ "incomplete_expired_description": "La configuration du paiement précédente a expiré avant le début de l'abonnement. Lancez une nouvelle mise à niveau lorsque vous serez prêt.","paused_title": "L'abonnement est en pause","paused_description": "Ouvrez la gestion de la facturation pour vérifier la pause et les options de rétablissement disponibles.","unpaid_title": "L'abonnement est impayé",@@ -82,19 +85,37 @@"member_count_one": "{{count}} membre","member_count_other": "{{count}} membres","billing_interval": "Intervalle de facturation",- "period_end": "Fin de la période en cours"+ "period_end": "Fin de la période en cours",+ "change_plan": "Changer de forfait",+ "business_adds": "Business ajoute les projets privés, l'accès par membre, les comptes d'applications d'équipe et des limites d'automatisation plus élevées.",+ "plan_change_hold": "Changement de forfait",+ "plan_change_confirming": "Passage à {{plan}} en cours. En attente de la confirmation de Stripe ; les sièges et le forfait ne peuvent pas être modifiés d'ici là.",+ "plan_change_unresolved": "Le passage à {{plan}} n'a pas pu être confirmé. Contactez l'assistance pour le régler ; les sièges et le forfait ne peuvent pas être modifiés d'ici là.",+ "plan_change_state_confirming": "Confirmation en cours",+ "plan_change_state_unresolved": "Assistance requise"},"upgrade": {- "title": "Passer à Pro",- "description": "Choisissez un intervalle de facturation, puis confirmez le nombre de sièges et le montant final dans Stripe Checkout.",+ "title": "Mettre à niveau","interval_label": "Intervalle de facturation","monthly": "Mensuel","yearly": "Annuel",- "pro_for_team_one": "Pro pour {{count}} siège humain",- "pro_for_team_other": "Pro pour {{count}} sièges humains","price_loading": "Chargement des tarifs d'abonnement",- "unit_price": "{{price}} par siège humain",- "price_at_checkout": "Le serveur recompte les membres humains avant l'achat. Stripe Checkout affiche le tarif par siège et le total faisant foi avant le paiement."+ "unit_price_month": "{{price}} par siège humain / mois",+ "unit_price_year_monthly": "{{price}} par siège humain / mois, facturé annuellement",+ "unit_price_year": "{{price}} par siège humain / an",+ "price_at_checkout": "Le serveur recompte les membres humains avant l'achat. Stripe Checkout affiche le tarif par siège et le total faisant foi avant le paiement.",+ "recommended": "Recommandé",+ "features": {+ "pro_members": "Membres illimités",+ "pro_autopilots": "1 000 exécutions d'automatisation par membre et par mois",+ "pro_storage": "10 Go de stockage de pièces jointes par membre",+ "pro_dashboard": "90 jours d'historique dans le tableau de bord",+ "business_everything": "Tout ce qui est inclus dans Pro",+ "business_access": "Projets privés et accès par membre",+ "business_apps": "Comptes d'applications d'équipe et règles d'approbation",+ "business_autopilots": "3 000 exécutions d'automatisation par membre et par mois",+ "business_reports": "Rapports d'utilisation et de coût par membre"+ }},"management": {"title": "Gestion de l'abonnement",@@ -153,6 +174,7 @@"preview_failed": "L'estimation est temporairement indisponible. Réessayez dans un instant.","capacity_out_of_sync": "Le nombre de sièges dans Stripe ne correspond pas au relevé de facturation. Contactez l'assistance avant de réessayer cet achat.","in_progress": "Un autre achat de sièges est en cours de traitement. Attendez qu'il se termine ; contactez l'assistance si cet état persiste.",+ "plan_change_in_progress": "Un changement de forfait est encore en cours de traitement. Réessayez dans quelques minutes.","purchase_unreadable": "Impossible de lire la réponse à l'achat. Réessayez avec ce devis : la même demande d'achat sera réutilisée.","purchase_failed": "Impossible d'ajouter les sièges. Réessayez avec le même devis ou actualisez s'il a expiré.","payment_failed": "Le paiement n'a pas pu être effectué. Mettez à jour le moyen de paiement dans Stripe, puis demandez un nouveau devis.",@@ -171,11 +193,36 @@"delayed_description_with_expiry": "La vérification automatique s'est arrêtée. Si la tentative est encore en attente après {{date}}, rechargez cette page avant de demander un autre devis ; contactez l'assistance si l'attente persiste.","submitted_one": "Un achat de {{count}} siège a été soumis. La nouvelle capacité apparaîtra après confirmation par Stripe.","submitted_other": "Un achat de {{count}} sièges a été soumis. La nouvelle capacité apparaîtra après confirmation par Stripe.",- "error_title": "Impossible de mettre à jour l'estimation"+ "error_title": "Impossible de mettre à jour l'estimation",+ "plan_change_unresolved": "Un changement de forfait n'a pas pu être confirmé. Contactez l'assistance avant d'ajouter des sièges."+ },+ "plan_change": {+ "upgrade_description": "Prend effet immédiatement. La différence pour le reste de la période de facturation est facturée maintenant.",+ "downgrade_description": "Prend effet immédiatement. La différence non utilisée est créditée sur votre prochaine facture. Les paramètres Business déjà configurés continuent de fonctionner, mais passent en lecture seule.",+ "seats": "Sièges",+ "charge_today": "Montant facturé aujourd'hui",+ "credit": "Crédit sur la prochaine facture",+ "next_invoice": "Prochain renouvellement",+ "tax_notice": "Stripe détermine les taxes, les crédits et les détails définitifs de la facture.",+ "preview_loading": "Chargement du devis...",+ "preview_failed": "Le devis est temporairement indisponible. Réessayez dans un instant.",+ "rate_limited": "Trop de demandes de devis. Patientez un instant, puis réessayez.",+ "in_progress": "Un achat de sièges est en cours de traitement. Réessayez une fois qu'il sera terminé.",+ "change_in_progress": "Un changement de forfait est encore en cours de traitement. Réessayez dans quelques minutes.",+ "not_active": "Cet abonnement ne peut pas changer de forfait pour le moment. Le forfait actuel a été actualisé.",+ "quote_changed": "L'abonnement ou le tarif a changé. Consultez le devis actualisé avant de confirmer à nouveau.",+ "payment_failed": "Le paiement n'a pas pu être effectué. Mettez à jour le moyen de paiement dans la gestion de la facturation, puis réessayez.",+ "failed": "Le forfait n'a pas pu être changé. Réessayez avec le même devis.",+ "unreadable": "La réponse est illisible. Réessayez ; la même demande sera réutilisée.",+ "error_title": "Impossible de changer de forfait",+ "success_title": "Forfait changé",+ "success_description": "Cet espace de travail utilise désormais {{plan}}.",+ "unresolved": "Le changement de forfait précédent n'a pas pu être confirmé. Contactez l'assistance avant de changer de forfait.",+ "check_failed": "Impossible de vérifier le changement de forfait. Réessayez."},"confirm": {"title": "Continuer vers Stripe Checkout ?",- "description": "Intervalle de facturation : {{interval}}. Membres humains actuels : {{count}}. Stripe recomptera les sièges et affichera le montant final avant le paiement."+ "description": "Forfait : {{plan}}. Intervalle de facturation : {{interval}}. Membres humains actuels : {{count}}. Stripe recomptera les sièges et affichera le montant final avant le paiement."}},"return_page": {diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 8e224a6929..e41bea0a45 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Free","pro": "Pro",+ "business": "Business","unknown": "不明なプラン"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "再試行","retry_autopilots": "自動化の使用量を再取得",- "upgrade": "Pro にアップグレード",+ "upgrade_to": "{{plan}} にアップグレード",+ "switch_to": "{{plan}} に切り替え","manage": "請求を管理","add_seats": "席を追加","cancel": "キャンセル",- "continue_to_stripe": "Stripe に進む"+ "continue_to_stripe": "Stripe に進む",+ "check_status": "状態を確認"},"errors": {"action_title": "請求操作に失敗しました",@@ -52,13 +55,13 @@"syncing_title": "サブスクリプションを有効化しています","syncing_description": "支払いが完了しました。Stripe によるプラン変更の確認を待っています。","timeout_description": "支払いは受領済みですが、サブスクリプションは同期中です。しばらくしてからページを更新してください。",- "active_title": "Pro が有効になりました",- "active_description": "このワークスペースで Pro を利用できます。"+ "active_title": "{{plan}} が有効になりました",+ "active_description": "このワークスペースで {{plan}} を利用できます。"},"past_due": {"title": "お支払い方法の確認が必要です","description": "請求管理で支払い方法を更新してください。",- "grace_description": "Pro を継続するには {{date}} までにお支払い方法を更新してください。"+ "grace_description": "有料プランを継続するには {{date}} までにお支払い方法を更新してください。"},"subscription_notice": {"canceling_title": "キャンセルが予定されています",@@ -67,7 +70,7 @@"incomplete_title": "サブスクリプション設定が未完了です","incomplete_description": "請求管理を開き、お支払い設定を完了または確認してください。","incomplete_expired_title": "サブスクリプション設定の期限が切れました",- "incomplete_expired_description": "以前のお支払い設定は Pro を有効化せず期限切れになりました。必要なときに再度アップグレードしてください。",+ "incomplete_expired_description": "以前のお支払い設定はサブスクリプション開始前に期限切れになりました。必要なときに再度アップグレードしてください。","paused_title": "サブスクリプションは一時停止中です","paused_description": "請求管理を開き、一時停止と再開方法を確認してください。","unpaid_title": "サブスクリプションは未払いです",@@ -81,18 +84,37 @@"members_description": "エージェントと保留中の招待は席数に含まれません。","member_count_other": "{{count}}名","billing_interval": "請求期間",- "period_end": "現在の期間終了日"+ "period_end": "現在の期間終了日",+ "change_plan": "プランを変更",+ "business_adds": "Business では、非公開プロジェクト、メンバー単位のアクセス設定、チームのアプリアカウント、より多い自動化の上限を利用できます。",+ "plan_change_hold": "プラン変更",+ "plan_change_confirming": "{{plan}} に切り替えています。Stripe の確認を待っています。確認されるまで席数とプランは変更できません。",+ "plan_change_unresolved": "{{plan}} への切り替えを確認できませんでした。サポートにお問い合わせください。解決するまで席数とプランは変更できません。",+ "plan_change_state_confirming": "確認中",+ "plan_change_state_unresolved": "サポートが必要"},"upgrade": {- "title": "Pro にアップグレード",- "description": "請求期間を選び、Stripe Checkout で現在の席数と最終金額を確認します。",+ "title": "アップグレード","interval_label": "請求期間","monthly": "月払い","yearly": "年払い",- "pro_for_team_other": "{{count}}席で Pro を利用","price_loading": "サブスクリプション価格を読み込んでいます",- "unit_price": "1席あたり {{price}}",- "price_at_checkout": "購入前にサーバーがユーザーメンバーを再集計します。お支払い前に Stripe Checkout で正式な席単価と合計金額を確認できます。"+ "unit_price_month": "ユーザー席 1 席あたり月 {{price}}",+ "unit_price_year_monthly": "ユーザー席 1 席あたり月 {{price}}(年払い)",+ "unit_price_year": "ユーザー席 1 席あたり年 {{price}}",+ "price_at_checkout": "購入前にサーバーがユーザーメンバーを再集計します。お支払い前に Stripe Checkout で正式な席単価と合計金額を確認できます。",+ "recommended": "おすすめ",+ "features": {+ "pro_members": "メンバー数無制限",+ "pro_autopilots": "メンバー 1 人あたり毎月 1,000 回の自動化実行",+ "pro_storage": "メンバー 1 人あたり 10 GB の添付ファイル容量",+ "pro_dashboard": "ダッシュボードで過去 90 日間を表示",+ "business_everything": "Pro のすべての機能",+ "business_access": "非公開プロジェクトとメンバー単位のアクセス設定",+ "business_apps": "チームのアプリアカウントと承認ルール",+ "business_autopilots": "メンバー 1 人あたり毎月 3,000 回の自動化実行",+ "business_reports": "メンバー別の使用量とコストのレポート"+ }},"management": {"title": "サブスクリプション管理",@@ -149,6 +171,7 @@"preview_failed": "見積もりは一時的に利用できません。しばらくしてから再試行してください。","capacity_out_of_sync": "Stripe の席数が請求記録と一致していません。再度購入する前にサポートへお問い合わせください。","in_progress": "別の席購入を処理中です。完了をお待ちください。長時間完了しない場合はサポートにお問い合わせください。",+ "plan_change_in_progress": "プラン変更をまだ処理中です。数分後に再度お試しください。","purchase_unreadable": "購入レスポンスを読み取れませんでした。この見積もりを再試行すると、同じ購入リクエストが再利用されます。","purchase_failed": "席を追加できませんでした。同じ見積もりで再試行するか、期限切れの場合は更新してください。","payment_failed": "支払いを完了できませんでした。Stripe で支払い方法を更新してから、新しい見積もりを取得してください。",@@ -164,11 +187,36 @@"delayed_description": "自動確認を停止しました。購入はまだ完了する可能性があります。別の購入を始める前に、後でもう一度確認するかサポートへお問い合わせください。","delayed_description_with_expiry": "自動確認を停止しました。{{date}} を過ぎても保留中の場合は、ページを再読み込みしてから新しい見積もりを取得してください。保留状態が続く場合はサポートへお問い合わせください。","submitted_other": "{{count}}席の購入を送信しました。Stripe の確認後に新しい容量が表示されます。",- "error_title": "見積もりを更新できません"+ "error_title": "見積もりを更新できません",+ "plan_change_unresolved": "プラン変更を確認できませんでした。席を追加する前にサポートにお問い合わせください。"+ },+ "plan_change": {+ "upgrade_description": "すぐに反映されます。現在の請求期間の残り分の差額を今すぐ請求します。",+ "downgrade_description": "すぐに反映されます。未使用分の差額は次回の請求から差し引かれます。設定済みの Business の設定は引き続き有効ですが、読み取り専用になります。",+ "seats": "席数",+ "charge_today": "本日の請求額",+ "credit": "次回の請求から差し引く額",+ "next_invoice": "次回更新時の金額",+ "tax_notice": "税金、クレジット、最終請求内容は Stripe が決定します。",+ "preview_loading": "見積もりを取得中...",+ "preview_failed": "見積もりは一時的に利用できません。しばらくしてから再試行してください。",+ "rate_limited": "見積もりのリクエストが多すぎます。しばらく待ってから再試行してください。",+ "in_progress": "席の購入を処理中です。完了してから再度お試しください。",+ "change_in_progress": "プラン変更をまだ処理中です。数分後に再度お試しください。",+ "not_active": "このサブスクリプションは現在プランを変更できません。現在のプランを更新しました。",+ "quote_changed": "サブスクリプションまたは価格が変更されました。更新後の見積もりを確認してから確定してください。",+ "payment_failed": "支払いを完了できませんでした。請求管理で支払い方法を更新してから、もう一度お試しください。",+ "failed": "プランを変更できませんでした。同じ見積もりで再試行してください。",+ "unreadable": "レスポンスを読み取れませんでした。再試行すると、同じリクエストが再利用されます。",+ "error_title": "プランを変更できませんでした",+ "success_title": "プランを変更しました",+ "success_description": "このワークスペースは {{plan}} になりました。",+ "unresolved": "前回のプラン変更を確認できませんでした。プランを変更する前にサポートにお問い合わせください。",+ "check_failed": "プラン変更を確認できませんでした。再度お試しください。"},"confirm": {"title": "Stripe Checkout に進みますか?",- "description": "請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。"+ "description": "プラン: {{plan}}。請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。"}},"return_page": {diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 6693b0000c..1e253a87a7 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Free","pro": "Pro",+ "business": "Business","unknown": "알 수 없는 요금제"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "다시 시도","retry_autopilots": "자동화 사용량 다시 시도",- "upgrade": "Pro로 업그레이드",+ "upgrade_to": "{{plan}}로 업그레이드",+ "switch_to": "{{plan}}로 전환","manage": "결제 관리","add_seats": "좌석 추가","cancel": "취소",- "continue_to_stripe": "Stripe로 이동"+ "continue_to_stripe": "Stripe로 이동",+ "check_status": "상태 확인"},"errors": {"action_title": "결제 작업 실패",@@ -52,13 +55,13 @@"syncing_title": "구독 활성화 중","syncing_description": "결제가 완료되었습니다. Stripe의 요금제 변경 확인을 기다리고 있습니다.","timeout_description": "결제는 접수되었지만 구독이 아직 동기화 중입니다. 잠시 후 페이지를 새로고침하세요.",- "active_title": "Pro 활성화됨",- "active_description": "이 워크스페이스에서 이제 Pro를 사용할 수 있습니다."+ "active_title": "{{plan}} 활성화됨",+ "active_description": "이제 이 워크스페이스에서 {{plan}}를 사용할 수 있습니다."},"past_due": {"title": "결제 정보를 확인해야 합니다","description": "결제 관리에서 결제 수단을 업데이트하세요.",- "grace_description": "Pro 이용을 유지하려면 {{date}}까지 결제 수단을 업데이트하세요."+ "grace_description": "유료 요금제를 유지하려면 {{date}}까지 결제 수단을 업데이트하세요."},"subscription_notice": {"canceling_title": "구독 취소가 예정되어 있습니다",@@ -67,7 +70,7 @@"incomplete_title": "구독 설정이 완료되지 않았습니다","incomplete_description": "결제 관리를 열어 결제 설정을 완료하거나 확인하세요.","incomplete_expired_title": "구독 설정이 만료되었습니다",- "incomplete_expired_description": "이전 결제 설정은 Pro를 활성화하지 못한 채 만료되었습니다. 필요할 때 다시 업그레이드하세요.",+ "incomplete_expired_description": "이전 결제 설정은 구독이 시작되기 전에 만료되었습니다. 필요할 때 다시 업그레이드하세요.","paused_title": "구독이 일시 중지되었습니다","paused_description": "결제 관리를 열어 일시 중지 상태와 복구 방법을 확인하세요.","unpaid_title": "구독이 미결제 상태입니다",@@ -81,18 +84,37 @@"members_description": "에이전트와 대기 중인 초대는 좌석에 포함되지 않습니다.","member_count_other": "멤버 {{count}}명","billing_interval": "결제 주기",- "period_end": "현재 결제 기간 종료일"+ "period_end": "현재 결제 기간 종료일",+ "change_plan": "요금제 변경",+ "business_adds": "Business에서는 비공개 프로젝트, 멤버별 접근 권한, 팀 앱 계정, 더 높은 자동화 한도를 사용할 수 있습니다.",+ "plan_change_hold": "요금제 변경",+ "plan_change_confirming": "{{plan}}(으)로 전환하는 중입니다. Stripe의 확인을 기다리고 있으며, 확인될 때까지 좌석과 요금제를 변경할 수 없습니다.",+ "plan_change_unresolved": "{{plan}}(으)로의 전환을 확인할 수 없습니다. 지원팀에 문의하세요. 해결될 때까지 좌석과 요금제를 변경할 수 없습니다.",+ "plan_change_state_confirming": "확인 중",+ "plan_change_state_unresolved": "지원 필요"},"upgrade": {- "title": "Pro로 업그레이드",- "description": "결제 주기를 선택한 다음 Stripe Checkout에서 현재 좌석과 최종 금액을 확인하세요.",+ "title": "업그레이드","interval_label": "결제 주기","monthly": "월간","yearly": "연간",- "pro_for_team_other": "사용자 좌석 {{count}}개에 Pro 적용","price_loading": "구독 가격을 불러오는 중",- "unit_price": "사용자 좌석당 {{price}}",- "price_at_checkout": "구매 전에 서버가 사용자 멤버를 다시 계산합니다. 결제 전 Stripe Checkout에서 공식 좌석당 가격과 총액을 확인할 수 있습니다."+ "unit_price_month": "사용자 좌석당 월 {{price}}",+ "unit_price_year_monthly": "사용자 좌석당 월 {{price}}, 연간 결제",+ "unit_price_year": "사용자 좌석당 연 {{price}}",+ "price_at_checkout": "구매 전에 서버가 사용자 멤버를 다시 계산합니다. 결제 전 Stripe Checkout에서 공식 좌석당 가격과 총액을 확인할 수 있습니다.",+ "recommended": "추천",+ "features": {+ "pro_members": "멤버 수 무제한",+ "pro_autopilots": "멤버당 매월 자동화 실행 1,000회",+ "pro_storage": "멤버당 첨부 파일 저장 공간 10GB",+ "pro_dashboard": "대시보드 최근 90일 조회",+ "business_everything": "Pro의 모든 기능",+ "business_access": "비공개 프로젝트와 멤버별 접근 권한",+ "business_apps": "팀 앱 계정과 승인 규칙",+ "business_autopilots": "멤버당 매월 자동화 실행 3,000회",+ "business_reports": "멤버별 사용량 및 비용 보고서"+ }},"management": {"title": "구독 관리",@@ -149,6 +171,7 @@"preview_failed": "예상 금액을 일시적으로 불러올 수 없습니다. 잠시 후 다시 시도하세요.","capacity_out_of_sync": "Stripe 좌석 수가 결제 기록과 일치하지 않습니다. 구매를 다시 시도하기 전에 지원팀에 문의하세요.","in_progress": "다른 좌석 구매가 처리 중입니다. 완료될 때까지 기다리세요. 오래 지속되면 지원팀에 문의하세요.",+ "plan_change_in_progress": "요금제 변경을 아직 처리하는 중입니다. 몇 분 후에 다시 시도하세요.","purchase_unreadable": "구매 응답을 읽지 못했습니다. 이 견적을 다시 시도하면 같은 구매 요청이 재사용됩니다.","purchase_failed": "좌석을 추가하지 못했습니다. 같은 견적으로 다시 시도하거나 만료된 경우 새로고침하세요.","payment_failed": "결제를 완료하지 못했습니다. Stripe에서 결제 수단을 업데이트한 후 새 견적을 요청하세요.",@@ -164,11 +187,36 @@"delayed_description": "자동 확인이 중지되었습니다. 구매는 계속 완료될 수 있습니다. 다른 구매를 시작하기 전에 나중에 다시 확인하거나 지원팀에 문의하세요.","delayed_description_with_expiry": "자동 확인이 중지되었습니다. {{date}} 이후에도 대기 중이면 페이지를 다시 불러온 후 새 견적을 요청하세요. 대기 상태가 계속되면 지원팀에 문의하세요.","submitted_other": "좌석 {{count}}개 구매를 제출했습니다. Stripe 확인 후 새 용량이 표시됩니다.",- "error_title": "예상 금액을 업데이트할 수 없습니다"+ "error_title": "예상 금액을 업데이트할 수 없습니다",+ "plan_change_unresolved": "요금제 변경을 확인할 수 없습니다. 좌석을 추가하기 전에 지원팀에 문의하세요."+ },+ "plan_change": {+ "upgrade_description": "즉시 적용됩니다. 현재 결제 기간의 남은 기간에 대한 차액이 지금 청구됩니다.",+ "downgrade_description": "즉시 적용됩니다. 사용하지 않은 차액은 다음 청구서에서 차감됩니다. 이미 구성한 Business 설정은 계속 작동하지만 읽기 전용이 됩니다.",+ "seats": "좌석",+ "charge_today": "오늘 청구액",+ "credit": "다음 청구서 차감액",+ "next_invoice": "다음 갱신 금액",+ "tax_notice": "세금, 크레딧 및 최종 청구 세부 정보는 Stripe가 결정합니다.",+ "preview_loading": "견적을 불러오는 중...",+ "preview_failed": "견적을 일시적으로 가져올 수 없습니다. 잠시 후 다시 시도하세요.",+ "rate_limited": "견적 요청이 너무 많습니다. 잠시 기다린 후 다시 시도하세요.",+ "in_progress": "좌석 구매를 처리하는 중입니다. 완료된 후 다시 시도하세요.",+ "change_in_progress": "요금제 변경을 아직 처리하는 중입니다. 몇 분 후에 다시 시도하세요.",+ "not_active": "이 구독은 지금 요금제를 변경할 수 없습니다. 현재 요금제를 새로 고쳤습니다.",+ "quote_changed": "구독 또는 가격이 변경되었습니다. 새로 고친 견적을 확인한 후 다시 확정하세요.",+ "payment_failed": "결제를 완료하지 못했습니다. 결제 관리에서 결제 수단을 업데이트한 후 다시 시도하세요.",+ "failed": "요금제를 변경하지 못했습니다. 같은 견적으로 다시 시도하세요.",+ "unreadable": "응답을 읽을 수 없습니다. 다시 시도하면 같은 요청이 재사용됩니다.",+ "error_title": "요금제를 변경할 수 없음",+ "success_title": "요금제가 변경됨",+ "success_description": "이제 이 워크스페이스는 {{plan}} 요금제를 사용합니다.",+ "unresolved": "이전 요금제 변경을 확인할 수 없습니다. 요금제를 변경하기 전에 지원팀에 문의하세요.",+ "check_failed": "요금제 변경을 확인할 수 없습니다. 다시 시도하세요."},"confirm": {"title": "Stripe Checkout으로 이동할까요?",- "description": "결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다."+ "description": "요금제: {{plan}}. 결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다."}},"return_page": {diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex b22cb2f2e5..4389d0550a 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Free","pro": "Pro",+ "business": "Business","unknown": "Неизвестный тариф"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "Повторить","retry_autopilots": "Повторить получение использования автоматизации",- "upgrade": "Перейти на Pro",+ "upgrade_to": "Перейти на {{plan}}",+ "switch_to": "Переключиться на {{plan}}","manage": "Управление биллингом","add_seats": "Добавить места","cancel": "Отменить",- "continue_to_stripe": "Перейти в Stripe"+ "continue_to_stripe": "Перейти в Stripe",+ "check_status": "Проверить статус"},"errors": {"action_title": "Не удалось выполнить действие с биллингом",@@ -52,13 +55,13 @@"syncing_title": "Активация подписки","syncing_description": "Оплата прошла. Ожидаем подтверждения изменения тарифа от Stripe.","timeout_description": "Оплата получена, но подписка ещё синхронизируется. Обновите страницу через некоторое время.",- "active_title": "Pro активирован",- "active_description": "Это рабочее пространство теперь имеет доступ Pro."+ "active_title": "{{plan}} активирован",+ "active_description": "Теперь у этого рабочего пространства есть доступ к {{plan}}."},"past_due": {"title": "Требуется внимание к оплате","description": "Обновите способ оплаты в разделе управления биллингом.",- "grace_description": "Обновите способ оплаты до {{date}}, чтобы сохранить доступ Pro."+ "grace_description": "Обновите способ оплаты до {{date}}, чтобы сохранить платный тариф."},"subscription_notice": {"canceling_title": "Отмена запланирована",@@ -67,7 +70,7 @@"incomplete_title": "Настройка подписки не завершена","incomplete_description": "Откройте управление биллингом, чтобы завершить или проверить настройку оплаты.","incomplete_expired_title": "Настройка подписки истекла",- "incomplete_expired_description": "Предыдущая настройка оплаты истекла без активации Pro. Начните новое обновление, когда будете готовы.",+ "incomplete_expired_description": "Предыдущая настройка оплаты истекла до начала подписки. Начните новое обновление, когда будете готовы.","paused_title": "Подписка приостановлена","paused_description": "Откройте управление биллингом, чтобы просмотреть причину приостановки и доступные варианты восстановления.","unpaid_title": "Подписка не оплачена",@@ -84,21 +87,37 @@"billing_interval": "Интервал оплаты","period_end": "Текущий период заканчивается","member_count_few": "{{count}} участника",- "member_count_many": "{{count}} участников"+ "member_count_many": "{{count}} участников",+ "change_plan": "Сменить тариф",+ "business_adds": "Business добавляет приватные проекты, доступ по участникам, командные аккаунты приложений и более высокие лимиты автоматизации.",+ "plan_change_hold": "Смена тарифа",+ "plan_change_confirming": "Переход на {{plan}}. Ожидается подтверждение от Stripe; до этого нельзя изменить места и тариф.",+ "plan_change_unresolved": "Не удалось подтвердить переход на {{plan}}. Обратитесь в поддержку; до решения нельзя изменить места и тариф.",+ "plan_change_state_confirming": "Подтверждается",+ "plan_change_state_unresolved": "Нужна поддержка"},"upgrade": {- "title": "Перейти на Pro",- "description": "Выберите интервал оплаты, затем подтвердите текущее количество мест и итоговую сумму в Stripe Checkout.",+ "title": "Повысить тариф","interval_label": "Интервал оплаты","monthly": "Ежемесячно","yearly": "Ежегодно",- "pro_for_team_one": "Pro для {{count}} места (человек)",- "pro_for_team_other": "Pro для {{count}} мест (людей)","price_loading": "Загрузка цен подписки",- "unit_price": "{{price}} за место (человека)",+ "unit_price_month": "{{price}} за место (человека) в месяц",+ "unit_price_year_monthly": "{{price}} за место (человека) в месяц при оплате за год",+ "unit_price_year": "{{price}} за место (человека) в год","price_at_checkout": "Сервер пересчитывает количество участников-людей перед покупкой. Stripe Checkout показывает достоверную цену за место и итоговую сумму перед оплатой.",- "pro_for_team_few": "Pro для {{count}} мест (людей)",- "pro_for_team_many": "Pro для {{count}} мест (людей)"+ "recommended": "Рекомендуем",+ "features": {+ "pro_members": "Неограниченное число участников",+ "pro_autopilots": "1 000 запусков автоматизации на участника в месяц",+ "pro_storage": "10 ГБ для вложений на участника",+ "pro_dashboard": "История на панели статистики за 90 дней",+ "business_everything": "Всё, что есть в Pro",+ "business_access": "Приватные проекты и доступ по участникам",+ "business_apps": "Командные аккаунты приложений и правила согласования",+ "business_autopilots": "3 000 запусков автоматизации на участника в месяц",+ "business_reports": "Отчёты об использовании и расходах по участникам"+ }},"management": {"title": "Управление подпиской",@@ -161,6 +180,7 @@"preview_failed": "Оценка временно недоступна. Повторите попытку через некоторое время.","capacity_out_of_sync": "Количество мест в Stripe не совпадает с записью биллинга. Обратитесь в поддержку перед повторной попыткой покупки.","in_progress": "Обрабатывается другая покупка мест. Дождитесь её завершения; обратитесь в поддержку, если она не завершается.",+ "plan_change_in_progress": "Смена тарифа ещё обрабатывается. Повторите попытку через несколько минут.","purchase_unreadable": "Не удалось прочитать ответ на покупку. Повторите с той же котировкой; будет использован тот же запрос на покупку.","purchase_failed": "Не удалось добавить места. Повторите с той же котировкой или обновите её, если она истекла.","payment_failed": "Не удалось выполнить оплату. Обновите способ оплаты в Stripe, затем запросите новую котировку.",@@ -185,11 +205,36 @@"pending_description_few": "Stripe подтверждает обновление подписки до {{count}} мест.","pending_description_many": "Stripe подтверждает обновление подписки до {{count}} мест.","submitted_few": "Покупка {{count}} мест отправлена. Новая ёмкость появится после подтверждения от Stripe.",- "submitted_many": "Покупка {{count}} мест отправлена. Новая ёмкость появится после подтверждения от Stripe."+ "submitted_many": "Покупка {{count}} мест отправлена. Новая ёмкость появится после подтверждения от Stripe.",+ "plan_change_unresolved": "Не удалось подтвердить смену тарифа. Обратитесь в поддержку, прежде чем добавлять места."+ },+ "plan_change": {+ "upgrade_description": "Вступает в силу сразу. Разница за оставшуюся часть расчётного периода списывается сейчас.",+ "downgrade_description": "Вступает в силу сразу. Неиспользованная разница будет зачтена в следующем счёте. Уже настроенные параметры Business продолжат работать, но станут доступны только для чтения.",+ "seats": "Места",+ "charge_today": "Списание сегодня",+ "credit": "Зачёт в следующем счёте",+ "next_invoice": "Следующее продление",+ "tax_notice": "Stripe определяет налоги, кредиты и итоговые детали счёта.",+ "preview_loading": "Получение котировки…",+ "preview_failed": "Котировка временно недоступна. Повторите попытку чуть позже.",+ "rate_limited": "Слишком много запросов котировки. Подождите немного и повторите попытку.",+ "in_progress": "Обрабатывается покупка мест. Повторите попытку после её завершения.",+ "change_in_progress": "Смена тарифа ещё обрабатывается. Повторите попытку через несколько минут.",+ "not_active": "Сейчас у этой подписки нельзя сменить тариф. Текущий тариф обновлён.",+ "quote_changed": "Подписка или цена изменились. Проверьте обновлённую котировку, прежде чем подтвердить снова.",+ "payment_failed": "Не удалось выполнить оплату. Обновите способ оплаты в управлении биллингом и повторите попытку.",+ "failed": "Не удалось сменить тариф. Повторите попытку с той же котировкой.",+ "unreadable": "Не удалось прочитать ответ. Повторите попытку; будет использован тот же запрос.",+ "error_title": "Не удалось сменить тариф",+ "success_title": "Тариф изменён",+ "success_description": "Теперь это рабочее пространство использует {{plan}}.",+ "unresolved": "Не удалось подтвердить предыдущую смену тарифа. Обратитесь в поддержку, прежде чем менять тариф.",+ "check_failed": "Не удалось проверить смену тарифа. Повторите попытку."},"confirm": {"title": "Перейти к оформлению в Stripe Checkout?",- "description": "Интервал оплаты: {{interval}}. Текущее число участников-людей: {{count}}. Stripe пересчитает места и покажет итоговую сумму перед оплатой."+ "description": "Тариф: {{plan}}. Интервал оплаты: {{interval}}. Текущее число участников-людей: {{count}}. Stripe пересчитает места и покажет итоговую сумму перед оплатой."}},"return_page": {diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex beda8f6170..a6b6a6c869 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Free","pro": "Pro",+ "business": "Business","unknown": "未知套餐"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "重试","retry_autopilots": "重试加载自动化用量",- "upgrade": "升级到 Pro",+ "upgrade_to": "升级到 {{plan}}",+ "switch_to": "切换到 {{plan}}","manage": "管理账单","add_seats": "添加席位","cancel": "取消",- "continue_to_stripe": "前往 Stripe"+ "continue_to_stripe": "前往 Stripe",+ "check_status": "检查状态"},"errors": {"action_title": "账单操作失败",@@ -52,13 +55,13 @@"syncing_title": "正在启用订阅","syncing_description": "付款已完成,正在等待 Stripe 确认套餐变化。","timeout_description": "付款已收到,但订阅仍在同步。请稍后刷新页面。",- "active_title": "Pro 已启用",- "active_description": "这个工作区现在可以使用 Pro。"+ "active_title": "{{plan}} 已启用",+ "active_description": "这个工作区现在可以使用 {{plan}}。"},"past_due": {"title": "付款信息需要处理","description": "请前往账单管理更新付款方式。",- "grace_description": "请在 {{date}} 前更新付款方式,以继续使用 Pro。"+ "grace_description": "请在 {{date}} 前更新付款方式,以继续使用付费套餐。"},"subscription_notice": {"canceling_title": "订阅已安排取消",@@ -67,7 +70,7 @@"incomplete_title": "订阅开通尚未完成","incomplete_description": "打开账单管理,完成或检查付款设置。","incomplete_expired_title": "订阅开通已过期",- "incomplete_expired_description": "上一次付款设置未能启用 Pro 且已过期,需要时请重新发起升级。",+ "incomplete_expired_description": "上一次付款设置在订阅生效前已过期,需要时请重新发起升级。","paused_title": "订阅已暂停","paused_description": "打开账单管理,查看暂停原因和可用的恢复方式。","unpaid_title": "订阅款项尚未支付",@@ -81,18 +84,37 @@"members_description": "智能体和待接受的邀请不计入席位。","member_count_other": "{{count}} 位成员","billing_interval": "付款周期",- "period_end": "当前周期结束时间"+ "period_end": "当前周期结束时间",+ "change_plan": "更换套餐",+ "business_adds": "Business 增加私有项目、按成员授权、团队应用账号,以及更高的自动化额度。",+ "plan_change_hold": "套餐变更",+ "plan_change_confirming": "正在切换到 {{plan}},等待 Stripe 确认。确认之前不能更换套餐或增加席位。",+ "plan_change_unresolved": "切换到 {{plan}} 的结果没有确认。请联系支持处理;处理完成之前不能更换套餐或增加席位。",+ "plan_change_state_confirming": "确认中",+ "plan_change_state_unresolved": "需要支持处理"},"upgrade": {- "title": "升级到 Pro",- "description": "选择付款周期,然后在 Stripe Checkout 确认当前席位和最终金额。",+ "title": "升级","interval_label": "付款周期","monthly": "月付","yearly": "年付",- "pro_for_team_other": "为 {{count}} 个成员席位升级 Pro","price_loading": "正在加载订阅价格",- "unit_price": "每个成员席位 {{price}}",- "price_at_checkout": "购买前,服务端会重新统计成员。付款前,Stripe Checkout 会显示权威的单席位价格和总额。"+ "unit_price_month": "每个成员席位每月 {{price}}",+ "unit_price_year_monthly": "每个成员席位每月 {{price}},按年付费",+ "unit_price_year": "每个成员席位每年 {{price}}",+ "price_at_checkout": "购买前,服务端会重新统计成员。付款前,Stripe Checkout 会显示权威的单席位价格和总额。",+ "recommended": "推荐",+ "features": {+ "pro_members": "成员不限",+ "pro_autopilots": "自动化每人每月 1,000 次",+ "pro_storage": "每人 10 GB 附件存储",+ "pro_dashboard": "统计查看最近 90 天",+ "business_everything": "Pro 的全部功能",+ "business_access": "私有项目和按成员授权",+ "business_apps": "团队应用账号和审批规则",+ "business_autopilots": "自动化每人每月 3,000 次",+ "business_reports": "按成员的用量和成本报表"+ }},"management": {"title": "订阅管理",@@ -149,6 +171,7 @@"preview_failed": "暂时无法获取估算金额,请稍后重试。","capacity_out_of_sync": "Stripe 席位数与计费记录不一致。再次购买前,请联系支持人员。","in_progress": "另一笔席位购买正在处理中。请等待其完成;若长时间未完成,请联系支持人员。",+ "plan_change_in_progress": "套餐变更还在处理中,请几分钟后再试。","purchase_unreadable": "无法读取购买响应。请重试当前报价;系统会复用同一购买请求。","purchase_failed": "无法添加席位。可使用同一报价重试;报价过期时请刷新。","payment_failed": "付款未能完成。请在 Stripe 更新付款方式,然后重新获取报价。",@@ -164,11 +187,36 @@"delayed_description": "自动检查已停止,购买仍可能完成。开始另一笔购买前,请稍后再查看或联系支持人员。","delayed_description_with_expiry": "自动检查已停止。若到 {{date}} 仍在等待,请重新加载页面后再获取报价;若状态仍未更新,请联系支持人员。","submitted_other": "购买 {{count}} 个席位的请求已提交。Stripe 确认后会显示新容量。",- "error_title": "无法更新估算金额"+ "error_title": "无法更新估算金额",+ "plan_change_unresolved": "有一次套餐变更的结果没有确认。请先联系支持,再增加席位。"+ },+ "plan_change": {+ "upgrade_description": "立即生效。本计费周期剩余时间的差价现在扣款。",+ "downgrade_description": "立即生效。未用完的差价会抵扣下一期账单。已经配置好的 Business 设置继续生效,但变为只读。",+ "seats": "席位",+ "charge_today": "今天扣款",+ "credit": "抵扣下期账单",+ "next_invoice": "下次续费",+ "tax_notice": "税费、抵扣和最终账单明细由 Stripe 确定。",+ "preview_loading": "正在获取报价...",+ "preview_failed": "暂时无法获取报价,请稍后重试。",+ "rate_limited": "报价请求过于频繁,请稍等后重试。",+ "in_progress": "有一笔席位购买正在处理中,请等它完成后再试。",+ "change_in_progress": "套餐变更还在处理中,请几分钟后再试。",+ "not_active": "这个订阅现在无法更换套餐。当前套餐已刷新。",+ "quote_changed": "订阅或价格已变化,请查看刷新后的报价再确认。",+ "payment_failed": "付款未能完成。请在账单管理中更新付款方式后重试。",+ "failed": "无法更换套餐。可使用同一报价重试。",+ "unreadable": "无法读取响应。请重试;系统会复用同一请求。",+ "error_title": "无法更换套餐",+ "success_title": "套餐已更换",+ "success_description": "这个工作区现在使用 {{plan}}。",+ "unresolved": "上一次套餐变更的结果没有确认。请先联系支持,再更换套餐。",+ "check_failed": "无法检查套餐变更,请重试。"},"confirm": {"title": "前往 Stripe Checkout?",- "description": "付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。"+ "description": "套餐:{{plan}}。付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。"}},"return_page": {diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex d773949b50..38955f97ae 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -6,6 +6,7 @@"plan": {"free": "Free","pro": "Pro",+ "business": "Business","unknown": "未知套餐"},"status": {@@ -27,11 +28,13 @@"actions": {"retry": "重試","retry_autopilots": "重試載入自動化用量",- "upgrade": "升級到 Pro",+ "upgrade_to": "升級到 {{plan}}",+ "switch_to": "切換到 {{plan}}","manage": "管理帳單","add_seats": "新增席位","cancel": "取消",- "continue_to_stripe": "前往 Stripe"+ "continue_to_stripe": "前往 Stripe",+ "check_status": "檢查狀態"},"errors": {"action_title": "帳單操作失敗",@@ -52,13 +55,13 @@"syncing_title": "正在啟用訂閱","syncing_description": "付款已完成,正在等待 Stripe 確認套餐變化。","timeout_description": "付款已收到,但訂閱仍在同步。請稍後重新整理頁面。",- "active_title": "Pro 已啟用",- "active_description": "這個工作區現在可以使用 Pro。"+ "active_title": "{{plan}} 已啟用",+ "active_description": "這個工作區現在可以使用 {{plan}}。"},"past_due": {"title": "付款資訊需要處理","description": "請前往帳單管理更新付款方式。",- "grace_description": "請在 {{date}} 前更新付款方式,以繼續使用 Pro。"+ "grace_description": "請在 {{date}} 前更新付款方式,以繼續使用付費套餐。"},"subscription_notice": {"canceling_title": "訂閱已安排取消",@@ -67,7 +70,7 @@"incomplete_title": "訂閱開通尚未完成","incomplete_description": "開啟帳單管理,完成或檢查付款設定。","incomplete_expired_title": "訂閱開通已過期",- "incomplete_expired_description": "上一次付款設定未能啟用 Pro 且已過期,需要時請重新發起升級。",+ "incomplete_expired_description": "上一次付款設定在訂閱生效前已過期,需要時請重新發起升級。","paused_title": "訂閱已暫停","paused_description": "開啟帳單管理,檢視暫停原因和可用的恢復方式。","unpaid_title": "訂閱款項尚未支付",@@ -81,18 +84,37 @@"members_description": "AI 代理和待接受的邀請不計入席位。","member_count_other": "{{count}} 位成員","billing_interval": "付款週期",- "period_end": "當前週期結束時間"+ "period_end": "當前週期結束時間",+ "change_plan": "更換套餐",+ "business_adds": "Business 增加私有專案、按成員授權、團隊應用帳號,以及更高的自動化額度。",+ "plan_change_hold": "套餐變更",+ "plan_change_confirming": "正在切換到 {{plan}},等待 Stripe 確認。確認之前不能更換套餐或增加席位。",+ "plan_change_unresolved": "切換到 {{plan}} 的結果沒有確認。請聯絡支援處理;處理完成之前不能更換套餐或增加席位。",+ "plan_change_state_confirming": "確認中",+ "plan_change_state_unresolved": "需要支援處理"},"upgrade": {- "title": "升級到 Pro",- "description": "選擇付款週期,然後在 Stripe Checkout 確認當前席位和最終金額。",+ "title": "升級","interval_label": "付款週期","monthly": "月付","yearly": "年付",- "pro_for_team_other": "為 {{count}} 個成員席位升級 Pro","price_loading": "正在載入訂閱價格",- "unit_price": "每個成員席位 {{price}}",- "price_at_checkout": "購買前,服務端會重新統計成員。付款前,Stripe Checkout 會顯示權威的單席位價格和總額。"+ "unit_price_month": "每個成員席位每月 {{price}}",+ "unit_price_year_monthly": "每個成員席位每月 {{price}},按年付費",+ "unit_price_year": "每個成員席位每年 {{price}}",+ "price_at_checkout": "購買前,服務端會重新統計成員。付款前,Stripe Checkout 會顯示權威的單席位價格和總額。",+ "recommended": "推薦",+ "features": {+ "pro_members": "成員不限",+ "pro_autopilots": "自動化每人每月 1,000 次",+ "pro_storage": "每人 10 GB 附件儲存",+ "pro_dashboard": "統計查看最近 90 天",+ "business_everything": "Pro 的全部功能",+ "business_access": "私有專案和按成員授權",+ "business_apps": "團隊應用帳號和審批規則",+ "business_autopilots": "自動化每人每月 3,000 次",+ "business_reports": "按成員的用量和成本報表"+ }},"management": {"title": "訂閱管理",@@ -149,6 +171,7 @@"preview_failed": "暫時無法獲取估算金額,請稍後重試。","capacity_out_of_sync": "Stripe 席位數與計費記錄不一致。再次購買前,請聯絡支援人員。","in_progress": "另一筆席位購買正在處理中。請等待其完成;若長時間未完成,請聯絡支援人員。",+ "plan_change_in_progress": "套餐變更還在處理中,請幾分鐘後再試。","purchase_unreadable": "無法讀取購買響應。請重試當前報價;系統會複用同一購買請求。","purchase_failed": "無法新增席位。可使用同一報價重試;報價過期時請重新整理。","payment_failed": "付款未能完成。請在 Stripe 更新付款方式,然後重新獲取報價。",@@ -164,11 +187,36 @@"delayed_description": "自動檢查已停止,購買仍可能完成。開始另一筆購買前,請稍後再檢視或聯絡支援人員。","delayed_description_with_expiry": "自動檢查已停止。若到 {{date}} 仍在等待,請重新載入頁面後再獲取報價;若狀態仍未更新,請聯絡支援人員。","submitted_other": "購買 {{count}} 個席位的請求已提交。Stripe 確認後會顯示新容量。",- "error_title": "無法更新估算金額"+ "error_title": "無法更新估算金額",+ "plan_change_unresolved": "有一次套餐變更的結果沒有確認。請先聯絡支援,再增加席位。"+ },+ "plan_change": {+ "upgrade_description": "立即生效。本計費週期剩餘時間的差價現在扣款。",+ "downgrade_description": "立即生效。未用完的差價會抵扣下一期帳單。已經設定好的 Business 設定繼續生效,但變為唯讀。",+ "seats": "席位",+ "charge_today": "今天扣款",+ "credit": "抵扣下期帳單",+ "next_invoice": "下次續費",+ "tax_notice": "稅費、抵扣和最終帳單明細由 Stripe 確定。",+ "preview_loading": "正在取得報價...",+ "preview_failed": "暫時無法取得報價,請稍後重試。",+ "rate_limited": "報價請求過於頻繁,請稍等後重試。",+ "in_progress": "有一筆席位購買正在處理中,請等它完成後再試。",+ "change_in_progress": "套餐變更還在處理中,請幾分鐘後再試。",+ "not_active": "這個訂閱現在無法更換套餐。當前套餐已重新整理。",+ "quote_changed": "訂閱或價格已變化,請查看重新整理後的報價再確認。",+ "payment_failed": "付款未能完成。請在帳單管理中更新付款方式後重試。",+ "failed": "無法更換套餐。可使用同一報價重試。",+ "unreadable": "無法讀取回應。請重試;系統會重複使用同一請求。",+ "error_title": "無法更換套餐",+ "success_title": "套餐已更換",+ "success_description": "這個工作區現在使用 {{plan}}。",+ "unresolved": "上一次套餐變更的結果沒有確認。請先聯絡支援,再更換套餐。",+ "check_failed": "無法檢查套餐變更,請重試。"},"confirm": {"title": "前往 Stripe Checkout?",- "description": "付款週期:{{interval}}。當前成員:{{count}}。Stripe 會重新統計席位,並在付款前顯示最終金額。"+ "description": "套餐:{{plan}}。付款週期:{{interval}}。當前成員:{{count}}。Stripe 會重新統計席位,並在付款前顯示最終金額。"}},"return_page": {diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsindex b4c3ecb5ed..ca3cf1a622 100644--- a/packages/views/settings/components/billing-state.test.ts+++ b/packages/views/settings/components/billing-state.test.ts@@ -9,6 +9,8 @@ import type {import {hasActiveWorkspaceSeatCapacity,resolveAutopilotUsage,+ resolvePlanChangeTarget,+ yearlyPriceMonthlyEquivalent,} from "./billing-state";const freeEntitlements: WorkspaceSubscriptionEntitlements = {@@ -140,7 +142,10 @@ describe("billing subscription state", () => {checkout: true,portal: true,purchaseSeats: false,+ changePlan: false,+ checkPlanChange: false,},+ planChange: null,} satisfies WorkspaceSubscriptionSummary;expect(hasActiveWorkspaceSeatCapacity(canceledSummary)).toBe(false);@@ -161,3 +166,70 @@ describe("billing subscription state", () => {expect(hasActiveWorkspaceSeatCapacity(activeSummary)).toBe(true);});});++describe("resolvePlanChangeTarget", () => {+ const summary = (+ plan: string,+ changePlan: boolean,+ ): WorkspaceSubscriptionSummary => ({+ entitlement: { ...freeEntitlements, plan, status: "active" },+ billingInterval: "month",+ humanMembers: 3,+ seatCapacity: null,+ cancelAtPeriodEnd: false,+ graceUntil: null,+ hasStripeCustomer: true,+ availableActions: {+ checkout: false,+ portal: true,+ purchaseSeats: true,+ changePlan,+ checkPlanChange: false,+ },+ planChange: null,+ });++ it("switches between Pro and Business only when Cloud offers it", () => {+ expect(resolvePlanChangeTarget(summary("pro", true))).toBe("business");+ expect(resolvePlanChangeTarget(summary("business", true))).toBe("pro");+ expect(resolvePlanChangeTarget(summary("pro", false))).toBeNull();+ });++ it("offers no switch for Free, an unknown plan, or a missing summary", () => {+ expect(resolvePlanChangeTarget(summary("free", true))).toBeNull();+ expect(resolvePlanChangeTarget(summary("enterprise", true))).toBeNull();+ expect(resolvePlanChangeTarget(null)).toBeNull();+ });+});++describe("yearlyPriceMonthlyEquivalent", () => {+ it("divides a yearly price that splits evenly into months", () => {+ expect(+ yearlyPriceMonthlyEquivalent({+ currency: "usd",+ unitAmount: 14400,+ interval: "year",+ intervalCount: 1,+ }),+ ).toBe(1200);+ });++ it("returns null instead of rounding or converting a monthly price", () => {+ expect(+ yearlyPriceMonthlyEquivalent({+ currency: "usd",+ unitAmount: 10000,+ interval: "year",+ intervalCount: 1,+ }),+ ).toBeNull();+ expect(+ yearlyPriceMonthlyEquivalent({+ currency: "usd",+ unitAmount: 1500,+ interval: "month",+ intervalCount: 1,+ }),+ ).toBeNull();+ });+});diff --git a/packages/views/settings/components/billing-state.ts b/packages/views/settings/components/billing-state.tsindex dacf38afbb..890872d5cf 100644--- a/packages/views/settings/components/billing-state.ts+++ b/packages/views/settings/components/billing-state.ts@@ -1,6 +1,8 @@import type {AutopilotQuotaUsage,WorkspaceSubscriptionEntitlements,+ WorkspaceSubscriptionPaidPlan,+ WorkspaceSubscriptionPrice,WorkspaceSubscriptionSummary,} from "@multica/core/types";@@ -76,3 +78,34 @@ export function hasActiveWorkspaceSeatCapacity(): boolean {return summary?.seatCapacity != null;}++/**+ * The plan an active subscription can switch to, or null when Cloud does not+ * offer a switch. Cloud's `changePlan` action is the gate; the current plan+ * only decides the direction, so an unknown plan never offers a switch.+ */+export function resolvePlanChangeTarget(+ summary: WorkspaceSubscriptionSummary | null | undefined,+): WorkspaceSubscriptionPaidPlan | null {+ if (summary?.availableActions.changePlan !== true) return null;+ switch (summary.entitlement.plan) {+ case "pro":+ return "business";+ case "business":+ return "pro";+ default:+ return null;+ }+}++/**+ * A yearly per-seat price expressed per month, in minor units. Returns null+ * when the yearly amount does not divide evenly into twelve minor-unit+ * months, so the caller shows the yearly amount instead of a rounded one.+ */+export function yearlyPriceMonthlyEquivalent(+ price: WorkspaceSubscriptionPrice,+): number | null {+ if (price.interval !== "year" || price.intervalCount !== 1) return null;+ return price.unitAmount % 12 === 0 ? price.unitAmount / 12 : null;+}diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 3ca3c1fc4d..3228ee5e9b 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -1,4 +1,4 @@-import { act, screen, waitFor } from "@testing-library/react";+import { act, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { ApiError } from "@multica/core/api";@@ -7,6 +7,7 @@ import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flagimport type {AutopilotQuotaUsage,WorkspaceSubscriptionEntitlements,+ WorkspaceSubscriptionPrices,WorkspaceSubscriptionSummary,} from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";@@ -17,26 +18,17 @@ const mocks = vi.hoisted(() => ({portal: vi.fn(),previewSeats: vi.fn(),purchaseSeats: vi.fn(),+ previewPlanChange: vi.fn(),+ changePlan: vi.fn(),+ checkPlanChange: vi.fn(),+ changePlanPending: false,refetch: vi.fn(),refetchSummary: vi.fn(),refetchUsage: vi.fn(),refetchPrices: vi.fn(),openExternal: vi.fn(),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,+ prices: null as WorkspaceSubscriptionPrices | null,pricesLoading: false,pricesFetching: false,pricesError: false,@@ -87,7 +79,10 @@ const mocks = vi.hoisted(() => ({checkout: true,portal: false,purchaseSeats: false,+ changePlan: false,+ checkPlanChange: false,},+ planChange: null as WorkspaceSubscriptionSummary["planChange"],} as WorkspaceSubscriptionSummary,usage: {action: "enforce" as "off" | "observe" | "enforce",@@ -130,6 +125,18 @@ vi.mock("@multica/core/billing", () => ({mutateAsync: mocks.purchaseSeats,isPending: mocks.purchasePending,}),+ usePreviewWorkspacePlanChange: () => ({+ mutateAsync: mocks.previewPlanChange,+ isPending: false,+ }),+ useChangeWorkspacePlan: () => ({+ mutateAsync: mocks.changePlan,+ isPending: mocks.changePlanPending,+ }),+ useReconcileWorkspaceSubscriptionSeats: () => ({+ mutateAsync: mocks.checkPlanChange,+ isPending: false,+ }),}));vi.mock("@multica/core/autopilots", () => ({@@ -223,19 +230,36 @@ describe("BillingTab", () => {navigationState.search = "tab=billing";mocks.workspaceId = "workspace-1";mocks.prices = {- month: {- currency: "usd",- unitAmount: 1000,- interval: "month",- intervalCount: 1,+ pro: {+ month: {+ currency: "usd",+ unitAmount: 1500,+ interval: "month",+ intervalCount: 1,+ },+ year: {+ currency: "usd",+ unitAmount: 14400,+ interval: "year",+ intervalCount: 1,+ },},- year: {- currency: "usd",- unitAmount: 9600,- interval: "year",- intervalCount: 1,+ business: {+ month: {+ currency: "usd",+ unitAmount: 3000,+ interval: "month",+ intervalCount: 1,+ },+ year: {+ currency: "usd",+ unitAmount: 28800,+ interval: "year",+ intervalCount: 1,+ },},};+ mocks.changePlanPending = false;mocks.pricesLoading = false;mocks.pricesFetching = false;mocks.pricesError = false;@@ -272,7 +296,10 @@ describe("BillingTab", () => {checkout: true,portal: false,purchaseSeats: false,+ changePlan: false,+ checkPlanChange: false,},+ planChange: null,});Object.assign(mocks.usage, {action: "enforce",@@ -357,6 +384,27 @@ describe("BillingTab", () => {nextInvoiceAmount: 6000,status: "submitted",});+ mocks.previewPlanChange.mockResolvedValue({+ currentPlan: "pro",+ targetPlan: "business",+ interval: "month",+ seats: 4,+ subscriptionVersion: 7,+ currency: "usd",+ prorationAmount: 3000,+ nextInvoiceAmount: 12000,+ invoiceNow: true,+ quotedAt: "2030-01-15T00:00:00Z",+ });+ mocks.changePlan.mockResolvedValue({+ plan: "business",+ previousPlan: "pro",+ interval: "month",+ seats: 4,+ currency: "usd",+ prorationAmount: 3000,+ invoiceNow: true,+ });configStore.getState().setFeatureFlags({[BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG]: true,});@@ -378,7 +426,12 @@ describe("BillingTab", () => {expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();expect(screen.getByText("5 / 7")).toBeInTheDocument();expect(screen.getByText("3 completed · 2 in progress")).toBeInTheDocument();- expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();+ expect(+ screen.getByText("$15.00 per human seat / month"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("$30.00 per human seat / month"),+ ).toBeInTheDocument();expect(mocks.useQuery).toHaveBeenCalledWith(expect.objectContaining({queryKey: ["workspace-subscriptions", "workspace-1", "prices"],@@ -387,7 +440,12 @@ describe("BillingTab", () => {await user.click(screen.getByRole("button", { name: "Yearly" }));- expect(screen.getByText("$96.00 per human seat")).toBeInTheDocument();+ expect(+ screen.getByText("$12.00 per human seat / month, billed yearly"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("$24.00 per human seat / month, billed yearly"),+ ).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Retry" }),).not.toBeInTheDocument();@@ -496,7 +554,9 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);- expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();+ expect(+ screen.getByText("$15.00 per human seat / month"),+ ).toBeInTheDocument();expect(screen.queryByText(/Estimated monthly total/)).not.toBeInTheDocument();expect(screen.queryByText(/\$0/)).not.toBeInTheDocument();});@@ -512,12 +572,18 @@ describe("BillingTab", () => {expect(mocks.checkout).toHaveBeenCalledTimes(1);});const request = mocks.checkout.mock.calls[0]?.[0] as {+ plan: string;interval: string;idempotencyKey: string;};+ expect(request.plan).toBe("pro");expect(request.interval).toBe("month");expect(request.idempotencyKey).toMatch(/^workspace-checkout-workspace-1-/);- expect(Object.keys(request).sort()).toEqual(["idempotencyKey", "interval"]);+ expect(Object.keys(request).sort()).toEqual([+ "idempotencyKey",+ "interval",+ "plan",+ ]);expect(mocks.openExternal).toHaveBeenCalledWith("https://checkout.stripe.com/test-session",{ webTarget: "same-tab" },@@ -729,7 +795,7 @@ describe("BillingTab", () => {expect(screen.getAllByText("3 members")).toHaveLength(1);expect(screen.queryByText("Purchased seats")).not.toBeInTheDocument();- expect(screen.queryByText("$10.00 per human seat")).not.toBeInTheDocument();+ expect(screen.queryByText(/per human seat/)).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),).not.toBeInTheDocument();@@ -1019,6 +1085,10 @@ describe("BillingTab", () => {"seat_purchase_in_progress","Another seat purchase is being processed. Wait for it to finish; contact support if it remains here.",],+ [+ "plan_change_in_progress",+ "A plan change is still being processed. Try again in a few minutes.",+ ],])("maps purchase conflict %s to actionable copy", async (code, copy) => {const user = userEvent.setup();Object.assign(mocks.entitlements, {@@ -1490,4 +1560,460 @@ describe("BillingTab", () => {screen.queryByRole("button", { name: "Upgrade to Pro" }),).not.toBeInTheDocument();});++ it("checks out Business for the selected interval", async () => {+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Yearly" }));+ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ expect(screen.getByText(/^Plan: Business\./)).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledOnce());+ expect(mocks.checkout.mock.calls[0]?.[0]).toMatchObject({+ plan: "business",+ interval: "year",+ });+ });++ it("starts a new Checkout intent when the plan changes", async () => {+ const user = userEvent.setup();+ mocks.checkout.mockRejectedValueOnce(new Error("network lost"));+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await screen.findByText("Billing action failed");+ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(2));+ expect(mocks.checkout.mock.calls[1]?.[0].plan).toBe("business");+ expect(mocks.checkout.mock.calls[1]?.[0].idempotencyKey).not.toBe(+ mocks.checkout.mock.calls[0]?.[0].idempotencyKey,+ );+ });++ describe("plan switching", () => {+ function setPaidPlan(plan: "pro" | "business") {+ Object.assign(mocks.entitlements, {+ plan,+ status: "active",+ limits: { autopilotRuns: { mode: "unlimited", limit: null } },+ currentPeriodEnd: "2030-02-01T00:00:00Z",+ });+ setSeatCapacity({ humanMembers: 4, purchased: 4 });+ mocks.summary.billingInterval = "month";+ mocks.summary.availableActions.changePlan = true;+ }++ it("shows a confirming plan change and lets a manager check it now", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.summary.availableActions.changePlan = false;+ mocks.summary.availableActions.checkPlanChange = true;+ mocks.summary.planChange = {+ targetPlan: "business",+ state: "confirming",+ since: "2030-01-15T00:00:00Z",+ };+ mocks.checkPlanChange.mockResolvedValue({+ workspaceId: "workspace-1",+ action: "none",+ version: 8,+ });+ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Plan change")).toBeInTheDocument();+ expect(+ screen.getByText(+ "Switching to Business. Waiting for Stripe to confirm; seats and the plan can't be changed until then.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByText("Change plan")).not.toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Check status" }));++ await waitFor(() => expect(mocks.checkPlanChange).toHaveBeenCalledOnce());+ expect(mocks.refetchSummary).toHaveBeenCalled();+ });++ it("tells the user to contact support when a plan change is unresolved", () => {+ setPaidPlan("pro");+ mocks.summary.availableActions.changePlan = false;+ mocks.summary.planChange = {+ targetPlan: "business",+ state: "unresolved",+ since: "2030-01-15T00:00:00Z",+ };+ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText(+ "The switch to Business could not be confirmed. Contact support to settle it; seats and the plan can't be changed until then.",+ ),+ ).toBeInTheDocument();+ expect(screen.getByText("Needs support")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Check status" }),+ ).not.toBeInTheDocument();+ });++ it("explains a plan change refused by an unresolved one", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.changePlan.mockRejectedValueOnce(+ new ApiError("request failed", 409, "Conflict", {+ code: "plan_change_unresolved",+ }),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );++ expect(+ await within(dialog).findByText(+ "The previous plan change could not be confirmed. Contact support before changing plans.",+ ),+ ).toBeInTheDocument();+ expect(mocks.refetchSummary).toHaveBeenCalled();+ });++ it("offers no switch unless Cloud allows it", () => {+ setPaidPlan("pro");+ mocks.summary.availableActions.changePlan = false;++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Pro")).toBeInTheDocument();+ expect(screen.queryByText("Change plan")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Upgrade to Business" }),+ ).not.toBeInTheDocument();+ });++ it("quotes and confirms an upgrade from Pro to Business", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");+ expect(mocks.previewPlanChange).toHaveBeenCalledWith({+ plan: "business",+ });+ expect(await within(dialog).findByText("$30.00")).toBeInTheDocument();+ expect(within(dialog).getByText("Charged today")).toBeInTheDocument();+ expect(within(dialog).getByText("$120.00")).toBeInTheDocument();+ expect(within(dialog).getByText("4 seats")).toBeInTheDocument();++ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );++ await waitFor(() => expect(mocks.changePlan).toHaveBeenCalledOnce());+ const request = mocks.changePlan.mock.calls[0]?.[0];+ expect(request).toMatchObject({+ plan: "business",+ expectedSubscriptionVersion: 7,+ quotedAt: "2030-01-15T00:00:00Z",+ acceptedProrationAmount: 3000,+ currency: "usd",+ });+ expect(request.idempotencyKey).toMatch(+ /^workspace-plan-change-workspace-1-/,+ );+ expect(+ await screen.findByText("This workspace is now on Business."),+ ).toBeInTheDocument();+ expect(mocks.refetchSummary).toHaveBeenCalled();+ });++ it("shows a downgrade credit and warns that Business settings become read-only", async () => {+ const user = userEvent.setup();+ setPaidPlan("business");+ mocks.previewPlanChange.mockResolvedValue({+ currentPlan: "business",+ targetPlan: "pro",+ interval: "month",+ seats: 4,+ subscriptionVersion: 8,+ currency: "usd",+ prorationAmount: -3000,+ nextInvoiceAmount: 6000,+ invoiceNow: false,+ quotedAt: "2030-01-15T00:00:00Z",+ });+ mocks.changePlan.mockResolvedValue({+ plan: "pro",+ previousPlan: "business",+ interval: "month",+ seats: 4,+ currency: "usd",+ prorationAmount: -3000,+ invoiceNow: false,+ });+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Switch to Pro" }));+ const dialog = await screen.findByRole("dialog");+ expect(+ within(dialog).getByText(/become read-only/),+ ).toBeInTheDocument();+ expect(+ await within(dialog).findByText("Credit on next invoice"),+ ).toBeInTheDocument();+ expect(within(dialog).getByText("$30.00")).toBeInTheDocument();++ await user.click(+ within(dialog).getByRole("button", { name: "Switch to Pro" }),+ );++ await waitFor(() => expect(mocks.changePlan).toHaveBeenCalledOnce());+ expect(mocks.changePlan.mock.calls[0]?.[0]).toMatchObject({+ plan: "pro",+ acceptedProrationAmount: -3000,+ });+ expect(+ await screen.findByText("This workspace is now on Pro."),+ ).toBeInTheDocument();+ });++ it("requests a fresh quote when Cloud reports the quote changed", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.changePlan.mockRejectedValueOnce(+ new ApiError("request failed", 409, "Conflict", {+ code: "plan_change_quote_changed",+ }),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );++ expect(+ await within(dialog).findByText(+ "The subscription or price changed. Review the refreshed quote before confirming again.",+ ),+ ).toBeInTheDocument();+ await waitFor(() =>+ expect(mocks.previewPlanChange).toHaveBeenCalledTimes(2),+ );+ expect(mocks.refetchSummary).toHaveBeenCalled();+ });++ it("explains that another plan change holds the subscription", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.changePlan.mockRejectedValueOnce(+ new ApiError("request failed", 409, "Conflict", {+ code: "plan_change_in_progress",+ }),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );++ expect(+ await within(dialog).findByText(+ "A plan change is still being processed. Try again in a few minutes.",+ ),+ ).toBeInTheDocument();+ expect(mocks.refetchSummary).toHaveBeenCalled();+ // Not treated as a changed quote: no new preview is requested.+ expect(mocks.previewPlanChange).toHaveBeenCalledTimes(1);+ });++ it("recovers after a lost confirmation once the dialog is reopened", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.changePlan.mockRejectedValueOnce(+ new ApiError("request failed", 503, "Service Unavailable", {}),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ let dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );+ await waitFor(() => expect(mocks.changePlan).toHaveBeenCalledOnce());+ const lostKey = mocks.changePlan.mock.calls[0]?.[0].idempotencyKey;+ // Closing the dialog drops the retry key, as a reload would.+ await user.click(within(dialog).getByRole("button", { name: "Cancel" }));+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );++ // Right after the timeout Cloud still holds the change.+ mocks.previewPlanChange.mockRejectedValueOnce(+ new ApiError("request failed", 409, "Conflict", {+ code: "plan_change_in_progress",+ }),+ );+ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ dialog = await screen.findByRole("dialog");+ expect(+ await within(dialog).findByText(+ "A plan change is still being processed. Try again in a few minutes.",+ ),+ ).toBeInTheDocument();+ await user.click(within(dialog).getByRole("button", { name: "Cancel" }));+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );++ // Once Cloud has settled it, a fresh quote goes through under a new key.+ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );+ await waitFor(() => expect(mocks.changePlan).toHaveBeenCalledTimes(2));+ expect(mocks.changePlan.mock.calls[1]?.[0].idempotencyKey).not.toBe(+ lostKey,+ );+ expect(+ await screen.findByText("This workspace is now on Business."),+ ).toBeInTheDocument();+ });++ it("explains a quote refused while another plan change is in flight", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.previewPlanChange.mockRejectedValueOnce(+ new ApiError("request failed", 409, "Conflict", {+ code: "plan_change_in_progress",+ }),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");++ expect(+ await within(dialog).findByText(+ "A plan change is still being processed. Try again in a few minutes.",+ ),+ ).toBeInTheDocument();+ });++ it("keeps the subscription unchanged and explains a declined upgrade payment", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.changePlan.mockRejectedValueOnce(+ new ApiError("request failed", 402, "Payment Required", {+ code: "plan_change_payment_failed",+ }),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ await user.click(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ );++ expect(+ await within(dialog).findByText(+ "Payment could not be completed. Update the payment method in billing management, then try again.",+ ),+ ).toBeInTheDocument();+ expect(+ within(dialog).getByRole("button", { name: "Upgrade to Business" }),+ ).toBeDisabled();+ });++ it("reuses the idempotency key when retrying the same quote", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.changePlan.mockRejectedValueOnce(new Error("network lost"));+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );+ const dialog = await screen.findByRole("dialog");+ await within(dialog).findByText("$30.00");+ const confirm = within(dialog).getByRole("button", {+ name: "Upgrade to Business",+ });+ await user.click(confirm);+ await within(dialog).findByText(+ "The plan could not be changed. Retry with the same quote.",+ );+ await user.click(confirm);++ await waitFor(() => expect(mocks.changePlan).toHaveBeenCalledTimes(2));+ expect(mocks.changePlan.mock.calls[1]?.[0].idempotencyKey).toBe(+ mocks.changePlan.mock.calls[0]?.[0].idempotencyKey,+ );+ });++ it("closes the dialog and refreshes when the plan can no longer change", async () => {+ const user = userEvent.setup();+ setPaidPlan("pro");+ mocks.previewPlanChange.mockRejectedValueOnce(+ new ApiError("request failed", 409, "Conflict", {+ code: "subscription_not_active",+ }),+ );+ renderWithI18n(<BillingTab />);++ await user.click(+ screen.getByRole("button", { name: "Upgrade to Business" }),+ );++ expect(+ await screen.findByText(+ "This subscription can't change plans right now. The current plan has been refreshed.",+ ),+ ).toBeInTheDocument();+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );+ expect(mocks.refetchSummary).toHaveBeenCalled();+ });+ });});diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 3e0f9b6407..a2dc8b800b 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -4,6 +4,9 @@ import { useEffect, useRef, useState } from "react";import { useQuery } from "@tanstack/react-query";import {AlertCircle,+ ArrowDown,+ ArrowUpCircle,+ Check,CheckCircle2,CreditCard,ExternalLink,@@ -15,8 +18,11 @@ import {import { ApiError, errorCode } from "@multica/core/api";import { autopilotQuotaUsageOptions } from "@multica/core/autopilots";import {+ useChangeWorkspacePlan,useCreateWorkspaceSubscriptionCheckout,useCreateWorkspaceSubscriptionPortal,+ usePreviewWorkspacePlanChange,+ useReconcileWorkspaceSubscriptionSeats,usePreviewWorkspaceSeatPurchase,usePurchaseWorkspaceSeats,workspaceSubscriptionPricesOptions,@@ -27,8 +33,10 @@ import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flagimport { useCurrentWorkspace } from "@multica/core/paths";import type {PurchaseWorkspaceSeatsRequest,+ WorkspacePlanChangePreview,WorkspaceSeatPurchasePreview,WorkspaceSubscriptionInterval,+ WorkspaceSubscriptionPaidPlan,} from "@multica/core/types";import {Alert,@@ -81,6 +89,8 @@ import {import {hasActiveWorkspaceSeatCapacity,resolveAutopilotUsage,+ resolvePlanChangeTarget,+ yearlyPriceMonthlyEquivalent,} from "./billing-state";import { formatStripeMinorAmount } from "./billing-format";@@ -89,6 +99,7 @@ export { formatStripeMinorAmount } from "./billing-format";const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;const SEAT_PURCHASE_POLL_TIMEOUT_MS = 2 * 60_000;const SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS = 800;+const PAID_PLANS = ["pro", "business"] as const;type WorkspaceBillingReturnResult = "success" | "cancel" | "portal";@@ -130,7 +141,7 @@ function formatDateTime(value: string | null, locale: string): string | null {}function planBadgeVariant(plan: string): "default" | "secondary" | "outline" {- if (plan === "pro") return "default";+ if (plan === "pro" || plan === "business") return "default";if (plan === "free") return "secondary";return "outline";}@@ -201,7 +212,20 @@ function BillingTabContent() {: null;const [interval, setInterval] =useState<WorkspaceSubscriptionInterval>("month");+ const [checkoutPlan, setCheckoutPlan] =+ useState<WorkspaceSubscriptionPaidPlan>("pro");const [checkoutConfirmOpen, setCheckoutConfirmOpen] = useState(false);+ const [planChangeTarget, setPlanChangeTarget] =+ useState<WorkspaceSubscriptionPaidPlan | null>(null);+ const [planChangePreview, setPlanChangePreview] =+ useState<WorkspacePlanChangePreview | null>(null);+ const [planChangePreviewRevision, setPlanChangePreviewRevision] =+ useState(0);+ const [planChangeError, setPlanChangeError] = useState<string | null>(null);+ const [planChangeQuoteChanged, setPlanChangeQuoteChanged] = useState(false);+ const [planChangeMessage, setPlanChangeMessage] = useState<string | null>(+ null,+ );const [seatPurchaseOpen, setSeatPurchaseOpen] = useState(false);const [additionalSeatsInput, setAdditionalSeatsInput] = useState("1");const [seatPreview, setSeatPreview] =@@ -224,9 +248,16 @@ function BillingTabContent() {const [syncTimedOut, setSyncTimedOut] = useState(false);const checkoutIntentRef = useRef<{wsId: string;+ plan: WorkspaceSubscriptionPaidPlan;interval: WorkspaceSubscriptionInterval;key: string;} | null>(null);+ const planChangeIntentRef = useRef<{+ wsId: string;+ key: string;+ preview: WorkspacePlanChangePreview;+ } | null>(null);+ const planChangePreviewKeyRef = useRef("");const portalIntentKeyRef = useRef<string | null>(null);const seatPurchaseIntentRef = useRef<{wsId: string;@@ -247,6 +278,13 @@ function BillingTabContent() {seatPurchaseIntentRef.current = null;seatPreviewInputRef.current = "";seatPreviewCapacityRetryRef.current = null;+ planChangeIntentRef.current = null;+ planChangePreviewKeyRef.current = "";+ setPlanChangeTarget(null);+ setPlanChangePreview(null);+ setPlanChangeError(null);+ setPlanChangeQuoteChanged(false);+ setPlanChangeMessage(null);setSeatPurchaseOpen(false);setSeatPreview(null);setSeatPreviewRevision(0);@@ -343,8 +381,73 @@ function BillingTabContent() {const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);const previewSeatPurchaseMutation = usePreviewWorkspaceSeatPurchase();const purchaseSeatsMutation = usePurchaseWorkspaceSeats(wsId);+ const previewPlanChangeMutation = usePreviewWorkspacePlanChange();+ const changePlanMutation = useChangeWorkspacePlan(wsId);+ const checkPlanChangeMutation = useReconcileWorkspaceSubscriptionSeats(wsId);const refetchSummary = summaryQuery.refetch;const previewSeatPurchase = previewSeatPurchaseMutation.mutateAsync;+ const previewPlanChange = previewPlanChangeMutation.mutateAsync;++ // Each open of the plan change dialog, and each explicit refresh, asks Cloud+ // for a new quote. A response for an older request is ignored so a slow+ // quote can never replace the one the user is looking at.+ useEffect(() => {+ if (!planChangeTarget) return;+ const requestKey = `${wsId}:${planChangeTarget}:${planChangePreviewRevision}`;+ planChangePreviewKeyRef.current = requestKey;+ planChangeIntentRef.current = null;+ setPlanChangePreview(null);+ setPlanChangeError(null);+ void previewPlanChange({ plan: planChangeTarget })+ .then((preview) => {+ if (planChangePreviewKeyRef.current !== requestKey) return;+ if (!preview || preview.targetPlan !== planChangeTarget) {+ setPlanChangeError(t(($) => $.workspace.plan_change.preview_failed));+ return;+ }+ setPlanChangePreview(preview);+ })+ .catch((error: unknown) => {+ if (planChangePreviewKeyRef.current !== requestKey) return;+ const status = error instanceof ApiError ? error.status : null;+ const code = errorCode(error);+ if (+ status === 400 ||+ status === 403 ||+ code === "subscription_not_active"+ ) {+ // The plan this dialog was opened for is no longer a valid switch,+ // for example because it already changed in another tab.+ planChangePreviewKeyRef.current = "";+ setPlanChangeTarget(null);+ setActionError(+ status === 403+ ? t(($) => $.workspace.errors.permission_changed)+ : t(($) => $.workspace.plan_change.not_active),+ );+ void refetchSummary();+ return;+ }+ setPlanChangeError(+ code === "plan_change_rate_limited"+ ? t(($) => $.workspace.plan_change.rate_limited)+ : code === "seat_purchase_in_progress"+ ? t(($) => $.workspace.plan_change.in_progress)+ : code === "plan_change_in_progress"+ ? t(($) => $.workspace.plan_change.change_in_progress)+ : code === "plan_change_unresolved"+ ? t(($) => $.workspace.plan_change.unresolved)+ : t(($) => $.workspace.plan_change.preview_failed),+ );+ });+ }, [+ planChangeTarget,+ planChangePreviewRevision,+ previewPlanChange,+ refetchSummary,+ t,+ wsId,+ ]);useEffect(() => {if (!seatPurchaseOpen) return;@@ -473,7 +576,11 @@ function BillingTabContent() {setSeatPurchaseError(previewErrorCode === "seat_purchase_in_progress"? t(($) => $.workspace.seat_purchase.in_progress)- : t(($) => $.workspace.seat_purchase.preview_failed),+ : previewErrorCode === "plan_change_in_progress"+ ? t(($) => $.workspace.seat_purchase.plan_change_in_progress)+ : previewErrorCode === "plan_change_unresolved"+ ? t(($) => $.workspace.seat_purchase.plan_change_unresolved)+ : t(($) => $.workspace.seat_purchase.preview_failed),);});}, SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS);@@ -504,6 +611,8 @@ function BillingTabContent() {return t(($) => $.workspace.plan.free);case "pro":return t(($) => $.workspace.plan.pro);+ case "business":+ return t(($) => $.workspace.plan.business);default:return t(($) => $.workspace.plan.unknown);}@@ -558,17 +667,21 @@ function BillingTabContent() {setActionError(null);const existing = checkoutIntentRef.current;const intent =- existing?.wsId === wsId && existing.interval === interval+ existing?.wsId === wsId &&+ existing.plan === checkoutPlan &&+ existing.interval === interval? existing: {wsId,+ plan: checkoutPlan,interval,key: createIdempotencyKey("workspace-checkout", wsId),};checkoutIntentRef.current = intent;try {const response = await checkoutMutation.mutateAsync({- interval,+ plan: intent.plan,+ interval: intent.interval,idempotencyKey: intent.key,});if (!response?.url) {@@ -595,6 +708,134 @@ function BillingTabContent() {if (!open) checkoutIntentRef.current = null;};+ const openCheckoutConfirm = (plan: WorkspaceSubscriptionPaidPlan) => {+ if (checkoutIntentRef.current?.plan !== plan) {+ checkoutIntentRef.current = null;+ }+ setCheckoutPlan(plan);+ setCheckoutConfirmOpen(true);+ };++ const handlePlanChangeOpenChange = (+ open: boolean,+ target: WorkspaceSubscriptionPaidPlan | null = null,+ ) => {+ if (!open && changePlanMutation.isPending) return;+ planChangeIntentRef.current = null;+ setPlanChangeError(null);+ setPlanChangeQuoteChanged(false);+ setPlanChangePreview(null);+ if (!open) {+ planChangePreviewKeyRef.current = "";+ setPlanChangeTarget(null);+ return;+ }+ setActionError(null);+ setPlanChangeMessage(null);+ setPlanChangePreviewRevision((revision) => revision + 1);+ setPlanChangeTarget(target);+ };++ const handlePlanChange = async () => {+ const preview = planChangePreview;+ if (!preview) return;+ setPlanChangeError(null);+ const existing = planChangeIntentRef.current;+ // A retry of the same quote reuses its key, so an ambiguous failure can+ // never become a second Stripe change.+ const key =+ existing?.wsId === wsId && existing.preview === preview+ ? existing.key+ : createIdempotencyKey("workspace-plan-change", wsId).slice(0, 200);+ planChangeIntentRef.current = { wsId, key, preview };+ try {+ const response = await changePlanMutation.mutateAsync({+ plan: preview.targetPlan,+ expectedSubscriptionVersion: preview.subscriptionVersion,+ quotedAt: preview.quotedAt,+ acceptedProrationAmount: preview.prorationAmount,+ currency: preview.currency,+ idempotencyKey: key,+ });+ if (!response || response.plan !== preview.targetPlan) {+ setPlanChangeError(t(($) => $.workspace.plan_change.unreadable));+ return;+ }+ planChangeIntentRef.current = null;+ planChangePreviewKeyRef.current = "";+ setPlanChangeTarget(null);+ setPlanChangePreview(null);+ setPlanChangeQuoteChanged(false);+ setPlanChangeMessage(+ t(($) => $.workspace.plan_change.success_description, {+ plan: planLabel(response.plan),+ }),+ );+ await summaryQuery.refetch();+ } catch (error) {+ const status = error instanceof ApiError ? error.status : null;+ const code = errorCode(error);+ if (status === 409) {+ planChangeIntentRef.current = null;+ if (code === "subscription_not_active") {+ planChangePreviewKeyRef.current = "";+ setPlanChangeTarget(null);+ setActionError(t(($) => $.workspace.plan_change.not_active));+ await summaryQuery.refetch();+ return;+ }+ if (code === "seat_purchase_in_progress") {+ setPlanChangePreview(null);+ setPlanChangeError(t(($) => $.workspace.plan_change.in_progress));+ return;+ }+ if (+ code === "plan_change_in_progress" ||+ code === "plan_change_unresolved"+ ) {+ setPlanChangePreview(null);+ setPlanChangeError(+ code === "plan_change_unresolved"+ ? t(($) => $.workspace.plan_change.unresolved)+ : t(($) => $.workspace.plan_change.change_in_progress),+ );+ await summaryQuery.refetch();+ return;+ }+ setPlanChangeQuoteChanged(true);+ await summaryQuery.refetch();+ setPlanChangePreviewRevision((revision) => revision + 1);+ return;+ }+ if (status === 402) {+ planChangeIntentRef.current = null;+ setPlanChangePreview(null);+ setPlanChangeError(t(($) => $.workspace.plan_change.payment_failed));+ return;+ }+ if (status === 403) {+ planChangeIntentRef.current = null;+ planChangePreviewKeyRef.current = "";+ setPlanChangeTarget(null);+ reportActionError(error, t(($) => $.workspace.plan_change.failed));+ return;+ }+ setPlanChangeError(t(($) => $.workspace.plan_change.failed));+ }+ };++ // Asks Cloud to settle a plan change that is still being confirmed now,+ // rather than at its next reconcile pass, then shows the result.+ const handleCheckPlanChange = async () => {+ setActionError(null);+ try {+ await checkPlanChangeMutation.mutateAsync();+ } catch (error) {+ reportActionError(error, t(($) => $.workspace.plan_change.check_failed));+ }+ await summaryQuery.refetch();+ };+const handlePortal = async () => {setActionError(null);const key =@@ -690,6 +931,18 @@ function BillingTabContent() {await summaryQuery.refetch();return;}+ if (+ purchaseErrorCode === "plan_change_in_progress" ||+ purchaseErrorCode === "plan_change_unresolved"+ ) {+ setSeatPurchaseError(+ purchaseErrorCode === "plan_change_unresolved"+ ? t(($) => $.workspace.seat_purchase.plan_change_unresolved)+ : t(($) => $.workspace.seat_purchase.plan_change_in_progress),+ );+ await summaryQuery.refetch();+ return;+ }setSeatPurchaseError(t(($) => $.workspace.seat_purchase.quote_changed));await summaryQuery.refetch();setSeatPreviewRevision((revision) => revision + 1);@@ -816,18 +1069,77 @@ function BillingTabContent() {const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||- purchaseSeatsMutation.isPending;- const selectedPrice = pricesQuery.data?.[interval] ?? null;- const formattedUnitPrice = selectedPrice+ purchaseSeatsMutation.isPending ||+ changePlanMutation.isPending;+ const planUnitPrice = (plan: WorkspaceSubscriptionPaidPlan) => {+ const price = pricesQuery.data?.[plan][interval] ?? null;+ if (!price || price.intervalCount !== 1) return null;+ if (price.interval === "year") {+ const monthly = yearlyPriceMonthlyEquivalent(price);+ if (monthly !== null) {+ const formatted = formatStripeMinorAmount(+ monthly,+ price.currency,+ locale,+ );+ if (formatted !== null) {+ return t(($) => $.workspace.upgrade.unit_price_year_monthly, {+ price: formatted,+ });+ }+ }+ const formatted = formatStripeMinorAmount(+ price.unitAmount,+ price.currency,+ locale,+ );+ return formatted === null+ ? null+ : t(($) => $.workspace.upgrade.unit_price_year, { price: formatted });+ }+ const formatted = formatStripeMinorAmount(+ price.unitAmount,+ price.currency,+ locale,+ );+ return formatted === null+ ? null+ : t(($) => $.workspace.upgrade.unit_price_month, { price: formatted });+ };+ const canRetryPrice =+ !pricesQuery.isLoading && (pricesQuery.data ?? null) === null;+ const planFeatures: Record<WorkspaceSubscriptionPaidPlan, string[]> = {+ pro: [+ t(($) => $.workspace.upgrade.features.pro_members),+ t(($) => $.workspace.upgrade.features.pro_autopilots),+ t(($) => $.workspace.upgrade.features.pro_storage),+ t(($) => $.workspace.upgrade.features.pro_dashboard),+ ],+ business: [+ t(($) => $.workspace.upgrade.features.business_everything),+ t(($) => $.workspace.upgrade.features.business_access),+ t(($) => $.workspace.upgrade.features.business_apps),+ t(($) => $.workspace.upgrade.features.business_autopilots),+ t(($) => $.workspace.upgrade.features.business_reports),+ ],+ };+ const availablePlanChange = resolvePlanChangeTarget(summaryQuery.data);+ const planChangeHold = summaryQuery.data?.planChange ?? null;+ const planChangeIsUpgrade = planChangeTarget === "business";+ const formattedPlanChangeProration = planChangePreview? formatStripeMinorAmount(- selectedPrice.unitAmount,- selectedPrice.currency,+ Math.abs(planChangePreview.prorationAmount),+ planChangePreview.currency,+ locale,+ )+ : null;+ const formattedPlanChangeNextInvoice = planChangePreview+ ? formatStripeMinorAmount(+ planChangePreview.nextInvoiceAmount,+ planChangePreview.currency,locale,): null;- const hasDisplayableUnitPrice =- selectedPrice?.intervalCount === 1 && formattedUnitPrice !== null;- const canRetryPrice = !pricesQuery.isLoading && selectedPrice === null;const formattedSeatProration = seatPreview? formatStripeMinorAmount(seatPreview.prorationAmount,@@ -880,12 +1192,16 @@ function BillingTabContent() {)}<AlertTitle>{isCheckoutConfirmed- ? t(($) => $.workspace.return.active_title)+ ? t(($) => $.workspace.return.active_title, {+ plan: planLabel(entitlements.plan),+ }): t(($) => $.workspace.return.syncing_title)}</AlertTitle><AlertDescription>{isCheckoutConfirmed- ? t(($) => $.workspace.return.active_description)+ ? t(($) => $.workspace.return.active_description, {+ plan: planLabel(entitlements.plan),+ }): syncTimedOut? t(($) => $.workspace.return.timeout_description): t(($) => $.workspace.return.syncing_description)}@@ -1000,6 +1316,16 @@ function BillingTabContent() {</Alert>) : null}+ {planChangeMessage ? (+ <Alert>+ <CheckCircle2 />+ <AlertTitle>+ {t(($) => $.workspace.plan_change.success_title)}+ </AlertTitle>+ <AlertDescription>{planChangeMessage}</AlertDescription>+ </Alert>+ ) : null}+<SettingsSection title={t(($) => $.workspace.current.title)}><SettingsCard><SettingsRow@@ -1042,14 +1368,89 @@ function BillingTabContent() {<span className="tabular-nums">{summaryPeriodEnd}</span></SettingsRow>) : null}+ {availablePlanChange ? (+ <SettingsRow+ label={t(($) => $.workspace.current.change_plan)}+ description={+ availablePlanChange === "business"+ ? t(($) => $.workspace.current.business_adds)+ : undefined+ }+ >+ <Button+ className="h-11 w-full sm:w-auto"+ variant={+ availablePlanChange === "business" ? "default" : "outline"+ }+ disabled={isMutating}+ onClick={() =>+ handlePlanChangeOpenChange(true, availablePlanChange)+ }+ >+ {availablePlanChange === "business" ? (+ <ArrowUpCircle />+ ) : (+ <ArrowDown />+ )}+ {availablePlanChange === "business"+ ? t(($) => $.workspace.actions.upgrade_to, {+ plan: planLabel("business"),+ })+ : t(($) => $.workspace.actions.switch_to, {+ plan: planLabel("pro"),+ })}+ </Button>+ </SettingsRow>+ ) : null}+ {planChangeHold ? (+ <SettingsRow+ label={t(($) => $.workspace.current.plan_change_hold)}+ description={+ planChangeHold.state === "unresolved"+ ? t(($) => $.workspace.current.plan_change_unresolved, {+ plan: planLabel(planChangeHold.targetPlan),+ })+ : t(($) => $.workspace.current.plan_change_confirming, {+ plan: planLabel(planChangeHold.targetPlan),+ })+ }+ >+ {planChangeHold.state === "confirming" &&+ summaryQuery.data?.availableActions.checkPlanChange === true ? (+ <Button+ className="h-11 w-full sm:w-auto"+ variant="outline"+ aria-busy={checkPlanChangeMutation.isPending}+ disabled={checkPlanChangeMutation.isPending || isMutating}+ onClick={() => void handleCheckPlanChange()}+ >+ {checkPlanChangeMutation.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <RefreshCw />+ )}+ {t(($) => $.workspace.actions.check_status)}+ </Button>+ ) : (+ <Badge+ variant={+ planChangeHold.state === "unresolved"+ ? "destructive"+ : "secondary"+ }+ >+ {planChangeHold.state === "unresolved"+ ? t(($) => $.workspace.current.plan_change_state_unresolved)+ : t(($) => $.workspace.current.plan_change_state_confirming)}+ </Badge>+ )}+ </SettingsRow>+ ) : null}</SettingsCard></SettingsSection>{canUpgrade ? (- <SettingsSection- title={t(($) => $.workspace.upgrade.title)}- description={t(($) => $.workspace.upgrade.description)}- >+ <SettingsSection title={t(($) => $.workspace.upgrade.title)}><SettingsCard><div className="space-y-5 p-4 sm:p-5"><div@@ -1074,29 +1475,79 @@ function BillingTabContent() {</button>))}</div>+ <div className="grid gap-3 md:grid-cols-2">+ {PAID_PLANS.map((plan) => {+ const recommended = plan === "business";+ const unitPrice = planUnitPrice(plan);+ return (+ <div+ key={plan}+ className={+ recommended+ ? "flex flex-col gap-4 rounded-lg border border-foreground p-4"+ : "flex flex-col gap-4 rounded-lg border border-surface-border p-4"+ }+ >+ <div className="space-y-1">+ <div className="flex items-center gap-2">+ <h3 className="text-title-sm font-semibold">+ {planLabel(plan)}+ </h3>+ {recommended ? (+ <Badge>+ {t(($) => $.workspace.upgrade.recommended)}+ </Badge>+ ) : null}+ </div>+ {pricesQuery.isLoading ? (+ <Skeleton+ aria-hidden="true"+ className="h-5 w-48 max-w-full motion-reduce:animate-none"+ />+ ) : unitPrice ? (+ <p className="text-body font-semibold tabular-nums">+ {unitPrice}+ </p>+ ) : null}+ </div>+ <ul className="flex-1 space-y-2">+ {planFeatures[plan].map((feature) => (+ <li+ key={feature}+ className="flex items-start gap-2 text-body"+ >+ <Check+ aria-hidden="true"+ className="mt-0.5 size-4 shrink-0 text-muted-foreground"+ />+ <span>{feature}</span>+ </li>+ ))}+ </ul>+ <Button+ className="h-11 w-full"+ variant={recommended ? "default" : "outline"}+ disabled={isMutating}+ onClick={() => openCheckoutConfirm(plan)}+ >+ <CreditCard />+ {t(($) => $.workspace.actions.upgrade_to, {+ plan: planLabel(plan),+ })}+ </Button>+ </div>+ );+ })}+ </div><div className="space-y-2">- <p className="text-body font-medium">- {t(($) => $.workspace.upgrade.pro_for_team, {- count: actualSeats,- })}- </p>{pricesQuery.isLoading ? (- <div- className="space-y-2 motion-reduce:[&_[data-slot=skeleton]]:animate-none"+ <span+ className="sr-only"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>- </div>+ {t(($) => $.workspace.upgrade.price_loading)}+ </span>) : null}<p className="max-w-[65ch] text-caption leading-5 text-muted-foreground">{t(($) => $.workspace.upgrade.price_at_checkout)}@@ -1132,14 +1583,6 @@ function BillingTabContent() {</>) : null}</div>- <Button- className="h-11 w-full sm:w-auto"- disabled={isMutating}- onClick={() => setCheckoutConfirmOpen(true)}- >- <CreditCard />- {t(($) => $.workspace.actions.upgrade)}- </Button></div></SettingsCard></SettingsSection>@@ -1647,6 +2090,152 @@ function BillingTabContent() {</DialogContent></Dialog>+ <Dialog+ open={planChangeTarget !== null}+ onOpenChange={(open) => handlePlanChangeOpenChange(open)}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {planChangeTarget === null+ ? null+ : planChangeIsUpgrade+ ? t(($) => $.workspace.actions.upgrade_to, {+ plan: planLabel(planChangeTarget),+ })+ : t(($) => $.workspace.actions.switch_to, {+ plan: planLabel(planChangeTarget),+ })}+ </DialogTitle>+ <DialogDescription>+ {planChangeIsUpgrade+ ? t(($) => $.workspace.plan_change.upgrade_description)+ : t(($) => $.workspace.plan_change.downgrade_description)}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ {planChangeQuoteChanged ? (+ <Alert>+ <AlertCircle />+ <AlertDescription>+ {t(($) => $.workspace.plan_change.quote_changed)}+ </AlertDescription>+ </Alert>+ ) : null}+ {previewPlanChangeMutation.isPending ? (+ <div+ className="flex items-center gap-2 text-body text-muted-foreground"+ role="status"+ >+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ {t(($) => $.workspace.plan_change.preview_loading)}+ </div>+ ) : null}+ {planChangeError ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.plan_change.error_title)}+ </AlertTitle>+ <AlertDescription>+ <p>{planChangeError}</p>+ {!planChangePreview ? (+ <Button+ className="mt-3"+ type="button"+ variant="outline"+ size="sm"+ disabled={previewPlanChangeMutation.isPending}+ onClick={() =>+ setPlanChangePreviewRevision(+ (revision) => revision + 1,+ )+ }+ >+ <RefreshCw />+ {t(($) => $.workspace.actions.retry)}+ </Button>+ ) : null}+ </AlertDescription>+ </Alert>+ ) : null}+ {planChangePreview &&+ formattedPlanChangeProration !== null &&+ formattedPlanChangeNextInvoice !== null ? (+ <div className="space-y-3 rounded-lg border border-surface-border p-4">+ <div className="flex items-center justify-between gap-4 text-body">+ <span className="text-muted-foreground">+ {t(($) => $.workspace.plan_change.seats)}+ </span>+ <span className="font-medium tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: planChangePreview.seats,+ })}+ </span>+ </div>+ <div className="flex items-center justify-between gap-4 text-body">+ <span className="text-muted-foreground">+ {planChangePreview.prorationAmount < 0+ ? t(($) => $.workspace.plan_change.credit)+ : t(($) => $.workspace.plan_change.charge_today)}+ </span>+ <span className="font-medium tabular-nums">+ {formattedPlanChangeProration}+ </span>+ </div>+ <div className="flex items-center justify-between gap-4 text-body">+ <span className="text-muted-foreground">+ {t(($) => $.workspace.plan_change.next_invoice)}+ </span>+ <span className="font-medium tabular-nums">+ {formattedPlanChangeNextInvoice}+ </span>+ </div>+ <p className="text-caption leading-5 text-muted-foreground">+ {t(($) => $.workspace.plan_change.tax_notice)}+ </p>+ </div>+ ) : null}+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ className="h-11"+ disabled={changePlanMutation.isPending}+ onClick={() => handlePlanChangeOpenChange(false)}+ >+ {t(($) => $.workspace.actions.cancel)}+ </Button>+ <Button+ type="button"+ className="h-11"+ disabled={+ !planChangePreview ||+ formattedPlanChangeProration === null ||+ formattedPlanChangeNextInvoice === null ||+ previewPlanChangeMutation.isPending ||+ changePlanMutation.isPending+ }+ onClick={() => void handlePlanChange()}+ >+ {changePlanMutation.isPending ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : null}+ {planChangeTarget === null+ ? null+ : planChangeIsUpgrade+ ? t(($) => $.workspace.actions.upgrade_to, {+ plan: planLabel(planChangeTarget),+ })+ : t(($) => $.workspace.actions.switch_to, {+ plan: planLabel(planChangeTarget),+ })}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<AlertDialogopen={checkoutConfirmOpen}onOpenChange={handleCheckoutConfirmOpenChange}@@ -1658,6 +2247,7 @@ function BillingTabContent() {</AlertDialogTitle><AlertDialogDescription>{t(($) => $.workspace.confirm.description, {+ plan: planLabel(checkoutPlan),interval:interval === "month"? t(($) => $.workspace.upgrade.monthly)diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.tsindex e1ed6906b3..6dfd36caa8 100644--- a/packages/views/settings/components/seat-invite-purchase.test.ts+++ b/packages/views/settings/components/seat-invite-purchase.test.ts@@ -58,7 +58,10 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSumcheckout: false,portal: true,purchaseSeats: true,+ changePlan: false,+ checkPlanChange: false,},+ planChange: null,};}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 29acd59b03..9a21c8912b 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2148,6 +2148,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/seats/purchase-preview", h.PreviewCloudWorkspaceSubscriptionSeatPurchase)r.Post("/seats/purchases", h.PurchaseCloudWorkspaceSubscriptionSeats)r.Post("/seats/reconcile", h.ReconcileCloudWorkspaceSubscriptionSeats)+ r.Post("/plan-changes/preview", h.PreviewCloudWorkspaceSubscriptionPlanChange)+ r.Post("/plan-changes", h.ChangeCloudWorkspaceSubscriptionPlan)r.Post("/portal-sessions", h.CreateCloudWorkspaceSubscriptionPortal)})})diff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.goindex 07ded6b82a..5b8dde3dba 100644--- a/server/internal/handler/cloud_billing.go+++ b/server/internal/handler/cloud_billing.go@@ -6,6 +6,7 @@ import ("io""net/http""strings"+ "time""github.com/go-chi/chi/v5""github.com/multica-ai/multica/server/internal/cloudruntime"@@ -49,8 +50,17 @@ const stripeSignatureHeader = "Stripe-Signature"const idempotencyKeyHeader = "Idempotency-Key"const maxCloudSubscriptionIdempotencyKeyLength = 255const maxCloudSubscriptionSeatPurchaseIdempotencyKeyLength = 200+const maxCloudSubscriptionPlanChangeIdempotencyKeyLength = 200++// isCloudSubscriptionPaidPlan reports whether plan names a plan a workspace can+// check out or switch to. Free is never purchased: it is what a workspace falls+// back to without an active subscription.+func isCloudSubscriptionPaidPlan(plan string) bool {+ return plan == "pro" || plan == "business"+}type cloudSubscriptionCheckoutRequest struct {+ Plan string `json:"plan"`Interval string `json:"interval"`IdempotencyKey string `json:"idempotency_key,omitempty"`}@@ -59,11 +69,25 @@ type cloudSubscriptionCheckoutRequest struct {// until the main repository explicitly reviews and adds them here.type cloudSubscriptionCheckoutUpstreamRequest struct {WorkspaceID string `json:"workspace_id"`+ Plan string `json:"plan"`Interval string `json:"interval"`IdempotencyKey string `json:"idempotency_key,omitempty"`CustomerEmail string `json:"customer_email,omitempty"`}+type cloudSubscriptionPlanChangePreviewRequest struct {+ Plan string `json:"plan"`+}++type cloudSubscriptionPlanChangeRequest struct {+ Plan string `json:"plan"`+ ExpectedSubscriptionVersion int64 `json:"expected_subscription_version"`+ QuotedAt time.Time `json:"quoted_at"`+ AcceptedProrationAmount int64 `json:"accepted_proration_amount"`+ Currency string `json:"currency"`+ IdempotencyKey string `json:"idempotency_key,omitempty"`+}+type cloudSubscriptionSeatPurchasePreviewRequest struct {AdditionalSeats int `json:"additional_seats"`}@@ -177,7 +201,7 @@ func (h *Handler) GetCloudWorkspaceSubscriptionSummary(w http.ResponseWriter, r// GetCloudWorkspaceSubscriptionPrices forwards cloud's validated per-seat price// read so the client never hardcodes an amount that Stripe can change.//-// Member-readable: seeing what Pro costs is not a privileged action, and cloud+// Member-readable: seeing what a plan costs is not a privileged action, and cloud// scopes the read to a workspace this caller belongs to. Cloud returns only// currency, minor-unit amount and interval — Price and Product IDs stay server// side — and answers 503 when a configured Price cannot be validated, which the@@ -208,6 +232,10 @@ func (h *Handler) CreateCloudWorkspaceSubscriptionCheckout(w http.ResponseWriterwriteError(w, http.StatusBadRequest, "invalid request body")return}+ if !isCloudSubscriptionPaidPlan(in.Plan) {+ writeError(w, http.StatusBadRequest, "plan must be pro or business")+ return+ }if in.Interval != "month" && in.Interval != "year" {writeError(w, http.StatusBadRequest, "interval must be month or year")return@@ -232,6 +260,7 @@ func (h *Handler) CreateCloudWorkspaceSubscriptionCheckout(w http.ResponseWriter}upstreamBody, err := json.Marshal(cloudSubscriptionCheckoutUpstreamRequest{WorkspaceID: workspaceID,+ Plan: in.Plan,Interval: in.Interval,IdempotencyKey: idempotencyKey,CustomerEmail: customerEmail,@@ -326,6 +355,79 @@ func (h *Handler) PurchaseCloudWorkspaceSubscriptionSeats(w http.ResponseWriter,http.Header{idempotencyKeyHeader: []string{key}})}+// PreviewCloudWorkspaceSubscriptionPlanChange accepts only the target plan.+// Cloud reads the current plan, interval and seats itself and returns Stripe's+// proration for switching the subscription to the target plan's Price.+func (h *Handler) PreviewCloudWorkspaceSubscriptionPlanChange(w http.ResponseWriter, r *http.Request) {+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")+ if !ok {+ return+ }+ body, ok := readCloudRuntimeJSONBody(w, r)+ if !ok {+ return+ }+ var in cloudSubscriptionPlanChangePreviewRequest+ if err := json.Unmarshal(body, &in); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if !isCloudSubscriptionPaidPlan(in.Plan) {+ writeError(w, http.StatusBadRequest, "plan must be pro or business")+ return+ }+ upstreamBody, err := json.Marshal(in)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to build plan change preview")+ return+ }+ h.proxyCloudSubscription(w, r, http.MethodPost,+ "/api/v1/subscriptions/"+workspaceID+"/plan-changes/preview", userID, upstreamBody, nil)+}++// ChangeCloudWorkspaceSubscriptionPlan forwards a user-confirmed plan change+// quote. A downgrade's proration is a credit, so the accepted amount may be+// negative. Cloud repeats the quote and owns concurrency, idempotency, and the+// Stripe write.+func (h *Handler) ChangeCloudWorkspaceSubscriptionPlan(w http.ResponseWriter, r *http.Request) {+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")+ if !ok {+ return+ }+ body, ok := readCloudRuntimeJSONBody(w, r)+ if !ok {+ return+ }+ var in cloudSubscriptionPlanChangeRequest+ if err := json.Unmarshal(body, &in); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if !isCloudSubscriptionPaidPlan(in.Plan) || in.ExpectedSubscriptionVersion < 1 ||+ in.QuotedAt.IsZero() || !isASCIICurrency(in.Currency) {+ writeError(w, http.StatusBadRequest, "invalid plan change confirmation")+ return+ }+ key, ok := requireCloudSubscriptionIdempotencyKey(w, r, in.IdempotencyKey)+ if !ok {+ return+ }+ if len(key) > maxCloudSubscriptionPlanChangeIdempotencyKeyLength {+ writeError(w, http.StatusBadRequest, "plan change idempotency key must be at most 200 bytes")+ return+ }+ in.Currency = strings.ToLower(in.Currency)+ in.IdempotencyKey = key+ upstreamBody, err := json.Marshal(in)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to build plan change request")+ return+ }+ h.proxyCloudSubscription(w, r, http.MethodPost,+ "/api/v1/subscriptions/"+workspaceID+"/plan-changes", userID, upstreamBody,+ http.Header{idempotencyKeyHeader: []string{key}})+}+func isASCIICurrency(value string) bool {if len(value) != 3 {return falsediff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.goindex 98490e3236..d2c8f6f365 100644--- a/server/internal/handler/cloud_billing_test.go+++ b/server/internal/handler/cloud_billing_test.go@@ -379,6 +379,7 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutInjectsAuthoritativeWorkspaceAnreq := newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{"workspace_id": "00000000-0000-0000-0000-000000000001",+ "plan": "business","interval": "year","idempotency_key": "checkout-request-1","customer_email": "[email protected]",@@ -401,7 +402,7 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutInjectsAuthoritativeWorkspaceAnif body.WorkspaceID != testWorkspaceID {t.Fatalf("upstream workspace_id = %q, want middleware workspace %q", body.WorkspaceID, testWorkspaceID)}- if body.Interval != "year" || body.IdempotencyKey != "checkout-request-1" || body.CustomerEmail != handlerTestEmail {+ if body.Plan != "business" || body.Interval != "year" || body.IdempotencyKey != "checkout-request-1" || body.CustomerEmail != handlerTestEmail {t.Fatalf("upstream body = %+v", body)}if got := proxy.req.Headers.Get(idempotencyKeyHeader); got != "checkout-header-1" {@@ -415,6 +416,7 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutFailsWhenPayerCannotBeResolved(useCloudRuntimeProxy(t, proxy)req := newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{+ "plan": "pro","interval": "month","idempotency_key": "checkout-request-missing-payer",})@@ -437,6 +439,7 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutRejectsInvalidPayerID(t *testinuseCloudRuntimeProxy(t, proxy)req := newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{+ "plan": "pro","interval": "month","idempotency_key": "checkout-request-invalid-payer",})@@ -461,6 +464,7 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutRejectsEmptyPayerEmail(t *testidbfx.Member(t, testWorkspaceID, emptyEmailUserID, "owner")req := newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{+ "plan": "pro","interval": "month","idempotency_key": "checkout-request-empty-email",})@@ -489,7 +493,7 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutAcceptsHeaderIdempotencyKey(t *useCloudRuntimeProxy(t, proxy)req := withCloudSubscriptionWorkspace(- newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{"interval": "month"}),+ newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", map[string]any{"plan": "pro", "interval": "month"}),"admin",)req.Header.Set(idempotencyKeyHeader, "checkout-header-only")@@ -597,6 +601,108 @@ func TestCloudWorkspaceSeatPurchaseRejectsInvalidRequests(t *testing.T) {}}+func TestCloudWorkspacePlanChangePreviewForwardsOnlyTargetPlan(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusOK, Body: []byte(`{"target_plan":"business"}`)}}+ useCloudRuntimeProxy(t, proxy)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/plan-changes/preview", map[string]any{+ "plan": "business", "workspace_id": "00000000-0000-0000-0000-000000000002", "interval": "year",+ }), "admin")+ w := httptest.NewRecorder()+ testHandler.PreviewCloudWorkspaceSubscriptionPlanChange(w, req)++ if w.Code != http.StatusOK || proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/plan-changes/preview" {+ t.Fatalf("status=%d path=%s body=%s", w.Code, proxy.req.Path, w.Body.String())+ }+ if string(proxy.req.Body) != `{"plan":"business"}` {+ t.Fatalf("upstream body=%s", proxy.req.Body)+ }+}++func TestCloudWorkspacePlanChangeForwardsOnlyConfirmedQuote(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusOK, Body: []byte(`{"plan":"pro"}`)}}+ useCloudRuntimeProxy(t, proxy)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/plan-changes", map[string]any{+ "workspace_id": "00000000-0000-0000-0000-000000000002",+ "interval": "year",+ "plan": "pro",+ "expected_subscription_version": 7,+ "quoted_at": "2026-11-18T08:00:00Z",+ // A downgrade's proration is a credit, so a negative amount is valid.+ "accepted_proration_amount": -4500,+ "currency": "USD",+ "idempotency_key": "plan-change-1",+ }), "owner")+ w := httptest.NewRecorder()+ testHandler.ChangeCloudWorkspaceSubscriptionPlan(w, req)++ if w.Code != http.StatusOK || proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/plan-changes" {+ t.Fatalf("status=%d path=%s body=%s", w.Code, proxy.req.Path, w.Body.String())+ }+ var body map[string]any+ if err := json.Unmarshal(proxy.req.Body, &body); err != nil {+ t.Fatal(err)+ }+ for _, leaked := range []string{"workspace_id", "interval"} {+ if _, ok := body[leaked]; ok {+ t.Fatalf("%s leaked upstream: %v", leaked, body)+ }+ }+ if body["plan"] != "pro" || body["expected_subscription_version"] != float64(7) ||+ body["quoted_at"] != "2026-11-18T08:00:00Z" || body["accepted_proration_amount"] != float64(-4500) ||+ body["currency"] != "usd" || body["idempotency_key"] != "plan-change-1" {+ t.Fatalf("upstream body=%v", body)+ }+ if proxy.req.Headers.Get(idempotencyKeyHeader) != "plan-change-1" {+ t.Fatalf("upstream idempotency=%q", proxy.req.Headers.Get(idempotencyKeyHeader))+ }+}++func TestCloudWorkspacePlanChangeRejectsInvalidRequests(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ valid := func() map[string]any {+ return map[string]any{+ "plan": "business", "expected_subscription_version": 3, "quoted_at": "2026-11-18T08:00:00Z",+ "accepted_proration_amount": 100, "currency": "usd", "idempotency_key": "key",+ }+ }+ tests := []struct {+ name string+ role string+ mutate func(map[string]any)+ header string+ }{+ {name: "member", role: "member", mutate: func(map[string]any) {}},+ {name: "free plan", role: "owner", mutate: func(b map[string]any) { b["plan"] = "free" }},+ {name: "missing version", role: "owner", mutate: func(b map[string]any) { delete(b, "expected_subscription_version") }},+ {name: "missing quote time", role: "owner", mutate: func(b map[string]any) { delete(b, "quoted_at") }},+ {name: "bad currency", role: "owner", mutate: func(b map[string]any) { b["currency"] = "u$d" }},+ {name: "missing key", role: "owner", mutate: func(b map[string]any) { delete(b, "idempotency_key") }},+ {name: "long key", role: "owner", mutate: func(b map[string]any) { delete(b, "idempotency_key") }, header: strings.Repeat("a", 201)},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{enabled: true}+ useCloudRuntimeProxy(t, proxy)+ body := valid()+ tc.mutate(body)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/plan-changes", body), tc.role)+ if tc.header != "" {+ req.Header.Set(idempotencyKeyHeader, tc.header)+ }+ w := httptest.NewRecorder()+ testHandler.ChangeCloudWorkspaceSubscriptionPlan(w, req)+ if w.Code != http.StatusBadRequest && w.Code != http.StatusForbidden {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if proxy.called {+ t.Fatal("invalid request reached upstream")+ }+ })+ }+}+func TestCloudWorkspaceSubscriptionWritesRequireManagerRole(t *testing.T) {withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)proxy := &fakeCloudRuntimeProxy{enabled: true}@@ -658,17 +764,38 @@ func TestCloudWorkspaceSubscriptionMutationsValidateLocally(t *testing.T) {{name: "checkout missing idempotency key",path: "/api/cloud-subscriptions/checkout-sessions",- body: map[string]any{"interval": "month"},+ body: map[string]any{"plan": "pro", "interval": "month"},wantError: "Idempotency-Key or idempotency_key is required",invoke: testHandler.CreateCloudWorkspaceSubscriptionCheckout,},{name: "checkout invalid interval",path: "/api/cloud-subscriptions/checkout-sessions",- body: map[string]any{"interval": "weekly", "idempotency_key": "checkout-request-1"},+ body: map[string]any{"plan": "pro", "interval": "weekly", "idempotency_key": "checkout-request-1"},wantError: "interval must be month or year",invoke: testHandler.CreateCloudWorkspaceSubscriptionCheckout,},+ {+ name: "checkout missing plan",+ path: "/api/cloud-subscriptions/checkout-sessions",+ body: map[string]any{"interval": "month", "idempotency_key": "checkout-request-1"},+ wantError: "plan must be pro or business",+ invoke: testHandler.CreateCloudWorkspaceSubscriptionCheckout,+ },+ {+ name: "checkout cannot buy free",+ path: "/api/cloud-subscriptions/checkout-sessions",+ body: map[string]any{"plan": "free", "interval": "month", "idempotency_key": "checkout-request-1"},+ wantError: "plan must be pro or business",+ invoke: testHandler.CreateCloudWorkspaceSubscriptionCheckout,+ },+ {+ name: "plan change preview invalid plan",+ path: "/api/cloud-subscriptions/plan-changes/preview",+ body: map[string]any{"plan": "enterprise"},+ wantError: "plan must be pro or business",+ invoke: testHandler.PreviewCloudWorkspaceSubscriptionPlanChange,+ },{name: "portal missing idempotency key",path: "/api/cloud-subscriptions/portal-sessions",