diff --git a/.env_example b/.env_example index 025bfba1f1e..d3849d484bf 100644 --- a/.env_example +++ b/.env_example @@ -44,6 +44,8 @@ ALGOLIA_API_KEY=684d998c36b67a9a9fce8fc2d8860579 # Override staging comfy-api / comfy-platform base URLs. # VITE_STAGING_API_BASE_URL=https://stagingapi.comfy.org # VITE_STAGING_PLATFORM_BASE_URL=https://stagingplatform.comfy.org +# VITE_STRIPE_PUBLISHABLE_KEY=pk_test_... +# VITE_STRIPE_PAYMENT_METHOD_CONFIGURATION_ID=pmc_... # Sentry ENV vars replace with real ones for debugging # SENTRY_AUTH_TOKEN=private-token # get from sentry diff --git a/browser_tests/tests/dialogs/checkoutRecovery.spec.ts b/browser_tests/tests/dialogs/checkoutRecovery.spec.ts new file mode 100644 index 00000000000..b311fe82b20 --- /dev/null +++ b/browser_tests/tests/dialogs/checkoutRecovery.spec.ts @@ -0,0 +1,278 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' +import type { + BillingOpStatusResponse, + BillingPlansResponse, + BillingStatusResponse, + ErrorResponse, + Plan, + PreviewSubscribeResponse +} from '@comfyorg/ingest-types' + +import type { RemoteConfig } from '@/platform/remoteConfig/types' +import type { PendingSubscriptionCheckout } from '@/platform/workspace/utils/pendingSubscriptionCheckout' + +import { + cloudAppExpect, + cloudAppFixture as test, + waitForCloudApp +} from '@e2e/fixtures/cloudAppFixture' +import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' +import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' + +/** + * A redirect checkout persists its pending billing operation in sessionStorage + * before leaving the app. On the next boot `resumePendingPricingFlow()` + * reconciles that operation: a terminal failure reopens checkout for the + * persisted selection, success stays silent, and an entry for another user or + * workspace is dropped without reconciliation. Drives a raw `page` against + * fully mocked endpoints, like the pricing deep-link spec. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const PENDING_CHECKOUT_STORAGE_KEY = 'comfy:pending-subscription-checkout' +const RECOVERY_OPERATION_ID = 'op-e2e-recover' + +const BOOT_FEATURES = { + billing_control_enabled: true +} satisfies RemoteConfig +// Disable the experimental Asset API: with it on (cloud default) the unmocked +// asset endpoints 403 and workflow restore throws uncaught, aborting the +// GraphCanvas onMounted chain before the recovery loader. +const BOOT_SETTINGS = { + 'Comfy.Assets.UseAssetAPI': false, + 'Comfy.TutorialCompleted': true +} + +// ownerUid matches the mocked Firebase uid (CloudAuthHelper) and workspaceId +// the personal workspace the boot mocks resolve as active. +const PENDING_CREATOR_CHECKOUT = { + operationId: RECOVERY_OPERATION_ID, + workspaceId: workspace('personal', 'owner').id, + ownerUid: 'test-user-e2e', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'yearly' + } +} satisfies Omit + +const CREATOR_ANNUAL_PLAN = { + slug: 'creator-annual', + tier: 'CREATOR', + duration: 'ANNUAL', + price_cents: 33_600, + credits_cents: 7_400, + max_seats: 5, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 33_600, + total_credits_cents: 7_400 + } +} satisfies Plan + +const LEGACY_ACTIVE_STANDARD_STATUS = { + is_active: true, + subscription_status: 'active', + subscription_tier: 'STANDARD', + subscription_duration: 'ANNUAL', + plan_slug: 'standard-annual', + billing_status: 'paid', + has_funds: true, + renewal_date: '2099-02-20T00:00:00Z', + team_credit_stop: null, + max_seats: 1, + occupied_seats: 1, + billing_rail: 'legacy_stripe' +} satisfies BillingStatusResponse & { billing_rail: 'legacy_stripe' } + +const NEW_CREATOR_SUBSCRIPTION = { + allowed: true, + transition_type: 'new_subscription', + effective_at: '2026-07-21T00:00:00Z', + is_immediate: true, + cost_today_cents: 33_600, + cost_next_period_cents: 33_600, + credits_today_cents: 7_400, + credits_next_period_cents: 7_400, + new_plan: CREATOR_ANNUAL_PLAN +} satisfies PreviewSubscribeResponse + +const FAILED_RECOVERY_OPERATION = { + id: RECOVERY_OPERATION_ID, + status: 'failed', + error_message: 'Payment was not completed', + started_at: '2026-07-20T00:00:00Z', + completed_at: '2026-07-20T00:00:01Z' +} satisfies BillingOpStatusResponse + +const SUCCEEDED_RECOVERY_OPERATION = { + id: RECOVERY_OPERATION_ID, + status: 'succeeded', + started_at: '2026-07-20T00:00:00Z', + completed_at: '2026-07-20T00:00:01Z' +} satisfies BillingOpStatusResponse + +// The recovery loader runs at the tail of GraphCanvas onMounted, so the boot +// chain must not throw before it: a missing settings subpath, prompt exec_info, +// or queue status each abort that chain. +async function mockGraphBootExtras(page: Page) { + await page.route('**/api/settings/**', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({})) + }) + await page.route('**/api/prompt', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ exec_info: { queue_remaining: 0 } })) + }) + await page.route('**/api/queue', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ queue_running: [], queue_pending: [] })) + }) +} + +async function setupCloudApp(page: Page) { + await mockCloudBoot(page, { + features: BOOT_FEATURES, + settings: BOOT_SETTINGS + }) + await mockGraphBootExtras(page) + await mockBilling(page) + await mockWorkspace(page, workspace('personal', 'owner'), []) + await bootCloud(page) +} + +// sessionStorage must be seeded before any app code runs; attemptedAt is +// stamped in the init script so the entry is always fresher than the 24h cap. +async function seedPendingCheckout( + page: Page, + entry: Omit +) { + await page.addInitScript( + ({ key, seeded }) => { + sessionStorage.setItem( + key, + JSON.stringify({ ...seeded, attemptedAt: Date.now() - 60_000 }) + ) + }, + { key: PENDING_CHECKOUT_STORAGE_KEY, seeded: entry } + ) +} + +function readPendingCheckout(page: Page) { + return page.evaluate( + (key) => sessionStorage.getItem(key), + PENDING_CHECKOUT_STORAGE_KEY + ) +} + +function trackBillingOpRequests(page: Page) { + const operationPollRequests: Request[] = [] + page.on('request', (request) => { + if (request.url().includes('/api/billing/ops/')) { + operationPollRequests.push(request) + } + }) + return operationPollRequests +} + +const confirmPaymentHeading = (page: Page) => + page.getByRole('heading', { name: 'Confirm your payment' }) + +test.describe('Redirect checkout recovery', { tag: '@cloud' }, () => { + test('reopens checkout for the attempted plan when reconciliation fails', async ({ + page + }) => { + const subscribeRequests: Request[] = [] + const operationPollRequests: Request[] = [] + await seedPendingCheckout(page, PENDING_CREATOR_CHECKOUT) + await setupCloudApp(page) + await page.route('**/api/billing/status', (route) => + route.fulfill(jsonRoute(LEGACY_ACTIVE_STANDARD_STATUS)) + ) + await page.route('**/api/billing/plans', (route) => + route.fulfill( + jsonRoute({ + plans: [CREATOR_ANNUAL_PLAN] + } satisfies BillingPlansResponse) + ) + ) + await page.route('**/api/billing/preview-subscribe', (route) => + route.fulfill(jsonRoute(NEW_CREATOR_SUBSCRIPTION)) + ) + await page.route('**/api/billing/subscribe', (route) => { + subscribeRequests.push(route.request()) + return route.fulfill({ + ...jsonRoute({ + code: 'unexpected_subscribe', + message: 'Recovered checkouts must not auto-subscribe' + } satisfies ErrorResponse), + status: 500 + }) + }) + await page.route(`**/api/billing/ops/${RECOVERY_OPERATION_ID}`, (route) => { + operationPollRequests.push(route.request()) + return route.fulfill(jsonRoute(FAILED_RECOVERY_OPERATION)) + }) + + await page.goto(APP_URL) + + await cloudAppExpect(confirmPaymentHeading(page)).toBeVisible() + const checkoutDialog = page.getByRole('dialog') + await expect( + checkoutDialog.getByRole('button', { name: 'Subscribe to Creator' }) + ).toBeVisible() + await expect( + checkoutDialog.getByText('$336 Billed yearly').filter({ visible: true }) + ).toBeVisible() + expect(operationPollRequests.length).toBeGreaterThan(0) + expect(subscribeRequests).toHaveLength(0) + await expect.poll(() => readPendingCheckout(page)).toBeNull() + }) + + test('stays silent when reconciliation succeeds', async ({ page }) => { + const operationPollRequests: Request[] = [] + await seedPendingCheckout(page, PENDING_CREATOR_CHECKOUT) + await setupCloudApp(page) + await page.route(`**/api/billing/ops/${RECOVERY_OPERATION_ID}`, (route) => { + operationPollRequests.push(route.request()) + return route.fulfill(jsonRoute(SUCCEEDED_RECOVERY_OPERATION)) + }) + + await page.goto(APP_URL) + + await waitForCloudApp(page) + await cloudAppExpect + .poll(() => operationPollRequests.length) + .toBeGreaterThan(0) + await expect.poll(() => readPendingCheckout(page)).toBeNull() + await expect(confirmPaymentHeading(page)).toBeHidden() + await expect( + page.getByRole('heading', { name: 'Choose a Plan' }) + ).toBeHidden() + }) + + test('drops an entry for another user without reconciling', async ({ + page + }) => { + await seedPendingCheckout(page, { + ...PENDING_CREATOR_CHECKOUT, + ownerUid: 'someone-else' + }) + await setupCloudApp(page) + const operationPollRequests = trackBillingOpRequests(page) + + await page.goto(APP_URL) + + await waitForCloudApp(page) + await cloudAppExpect.poll(() => readPendingCheckout(page)).toBeNull() + expect(operationPollRequests).toHaveLength(0) + await expect(confirmPaymentHeading(page)).toBeHidden() + await expect( + page.getByRole('heading', { name: 'Choose a Plan' }) + ).toBeHidden() + }) +}) diff --git a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts index 6280c9e5bda..b8ba7916a52 100644 --- a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts +++ b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts @@ -644,7 +644,7 @@ test.describe('Pricing table deep link', { tag: '@cloud' }, () => { await expect.poll(() => operationPollRequests.length).toBeGreaterThan(0) await expect(backButton).toBeDisabled() - await page.clock.fastForward(5 * 60_000 + 1) + await page.clock.fastForward(23 * 60 * 60_000 + 1) await expect(backButton).toBeEnabled() await expect( diff --git a/package.json b/package.json index c3e2b5b1404..0c055ea6a5a 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,7 @@ "@primevue/themes": "catalog:", "@sentry/vue": "catalog:", "@sparkjsdev/spark": "catalog:", + "@stripe/stripe-js": "catalog:", "@tanstack/vue-virtual": "catalog:", "@tiptap/core": "catalog:", "@tiptap/extension-link": "catalog:", diff --git a/packages/ingest-types/src/index.ts b/packages/ingest-types/src/index.ts index 27d40003c06..cfe24801d3b 100644 --- a/packages/ingest-types/src/index.ts +++ b/packages/ingest-types/src/index.ts @@ -210,6 +210,7 @@ export type { CreateWorkspaceResponse, CreateWorkspaceResponses, CredentialOption, + CurrentWorkspaceResponse, DeleteAssetData, DeleteAssetError, DeleteAssetErrors, @@ -348,6 +349,11 @@ export type { GetChurnkeyAuthErrors, GetChurnkeyAuthResponse, GetChurnkeyAuthResponses, + GetCurrentWorkspaceData, + GetCurrentWorkspaceError, + GetCurrentWorkspaceErrors, + GetCurrentWorkspaceResponse, + GetCurrentWorkspaceResponses, GetCustomNodeProxyData, GetCustomNodeProxyErrors, GetCustomNodeProxyResponses, @@ -703,6 +709,11 @@ export type { ListJobsResponse, ListJobsResponses, ListMembersResponse, + ListSavedPaymentMethodsData, + ListSavedPaymentMethodsError, + ListSavedPaymentMethodsErrors, + ListSavedPaymentMethodsResponse, + ListSavedPaymentMethodsResponses, ListSecretProvidersData, ListSecretProvidersError, ListSecretProvidersErrors, @@ -895,6 +906,7 @@ export type { RevokeWorkspaceInviteErrors, RevokeWorkspaceInviteResponse, RevokeWorkspaceInviteResponses, + SavedPaymentMethod, SecretListResponse, SecretProvider, SecretProvidersResponse, @@ -916,6 +928,7 @@ export type { SubscribeResponses, SubscribeToLogsData, SubscribeToLogsResponses, + SubscriptionDiscount, SubscriptionDuration, SubscriptionTier, SystemStatsResponse, diff --git a/packages/ingest-types/src/types.gen.ts b/packages/ingest-types/src/types.gen.ts index 7b1f1b8dba3..349688ada7f 100644 --- a/packages/ingest-types/src/types.gen.ts +++ b/packages/ingest-types/src/types.gen.ts @@ -746,6 +746,22 @@ export type SystemStatsResponse = { */ export type SubscriptionDuration = 'MONTHLY' | 'ANNUAL' +export type SubscriptionDiscount = { + /** + * What this discount removed from the amount due today. + */ + amount_off_cents?: number + code: string + kind: 'plan' | 'promotion' + /** + * Customer-facing display name of the underlying coupon. `code` can + * be an internal identifier (e.g. team_commitment_7_5); render this + * when present. + * + */ + name?: string +} + /** * Response after successfully subscribing to a billing plan. */ @@ -799,6 +815,13 @@ export type SubscribeRequest = { * */ confirm_reactivation?: boolean + /** + * Stripe ConfirmationToken created from deferred Payment Element + * details. For an initial subscription, the backend creates the exact + * invoice PaymentIntent and confirms it with this token. + * + */ + confirmation_token?: string /** * Client-provided key to prevent duplicate operations. * If a billing op with this key already exists, returns the existing op instead of creating a new one. @@ -809,6 +832,12 @@ export type SubscribeRequest = { * Target plan slug to subscribe to */ plan_slug: string + /** + * Optional customer-facing Stripe promotion code. The backend + * resolves and validates it, then stacks it with plan discounts. + * + */ + promotion_code?: string /** * Echoes PreviewSubscribeResponse.proration_at from the preview the * caller consented to. When present, the charge is prorated to this @@ -821,12 +850,31 @@ export type SubscribeRequest = { * */ proration_at?: string + /** + * Opaque quote id returned by PreviewSubscribeResponse. + */ + quote_id?: string + /** + * Quote version returned by PreviewSubscribeResponse. + */ + quote_version?: number /** * URL to redirect after payment method is added successfully. - * Required if workspace has no payment method on file. + * Required if the workspace has no payment method on file, when + * confirmation_token is provided, or when a selected saved payment + * method is redirect-based (any non-card type). Redirect-based flows + * require an absolute HTTPS URL; plain HTTP is accepted only for + * loopback hosts during local development. * */ return_url?: string + /** + * Optional saved payment method selected for this subscription. It + * must be attached to the current workspace's Stripe customer. + * Mutually exclusive with confirmation_token. + * + */ + saved_payment_method_id?: string /** * Selected team credit-stop preset id (e.g. "team_700") for the * per-credit Team plan. Required when subscribing to a per-credit Team @@ -921,6 +969,23 @@ export type SecretListResponse = { data: Array } +export type SavedPaymentMethod = { + /** + * Card brand. Present only for card payment methods. + */ + brand?: string + id: string + /** + * Exactly one item is the default when the returned list is non-empty. + */ + is_default: boolean + /** + * Masked card suffix. Present only for card payment methods. + */ + last4?: string + type: string +} + /** * Response after accepting a resubscribe request. */ @@ -1232,6 +1297,7 @@ export type PreviewSubscribeResponse = { * Whether this subscription change is allowed */ allowed: boolean + amount_due_cents?: number /** * Amount that will be charged at next billing period in cents */ @@ -1248,7 +1314,9 @@ export type PreviewSubscribeResponse = { * Credits granted today in cents (prorated for mid-period upgrades) */ credits_today_cents: number + currency?: string current_plan?: PreviewPlanInfo + discounts?: Array /** * When the change takes effect */ @@ -1258,6 +1326,20 @@ export type PreviewSubscribeResponse = { */ is_immediate: boolean new_plan: PreviewPlanInfo + /** + * The Stripe payment method configuration governing which payment + * methods the embedded checkout offers for this environment. Mount + * Stripe Elements with `paymentMethodConfiguration` set to this id + * instead of hardcoding payment method types. Present on every + * successful preview while embedded checkout is enabled and absent + * from legacy previews. + * + */ + payment_method_configuration_id?: string + /** + * Normalized promotion code accepted by Stripe. + */ + promotion_code?: string /** * The instant cost_today_cents was priced at (Stripe-native transitions * only; absent for other billing rails). Echo this back as proration_at @@ -1267,10 +1349,34 @@ export type PreviewSubscribeResponse = { * */ proration_at?: string + /** + * Opaque short-lived quote identifier to echo on Subscribe. + */ + quote_id?: string + /** + * Quote contract version to echo on Subscribe. + */ + quote_version?: number /** * Reason why the change is not allowed (only present if allowed=false) */ reason?: string + renewal_amount_cents?: number + /** + * The next recurring charge and target-plan period end. Current servers + * always return this later than effective_at and following the target + * plan's billing interval. Optional in the schema for older clients. + * + */ + renewal_at?: string + /** + * Whether this previewed change requires explicit reactivation + * consent. Computed from the persisted subscription and a short-lived + * cache of Stripe lifecycle state. The subscribe enforcement path + * performs its own uncached Stripe lifecycle read. + * + */ + requires_reactivation_confirmation?: boolean /** * Type of subscription transition */ @@ -1336,6 +1442,10 @@ export type PreviewSubscribeRequest = { * Target plan slug to preview subscribing to */ plan_slug: string + /** + * Optional Stripe promotion code to validate and include in the exact quote. + */ + promotion_code?: string /** * Selected per-credit Team plan stop to preview. */ @@ -3146,6 +3256,23 @@ export type DeleteSessionResponse = { success: boolean } +/** + * The workspace bound to the presented credential, plus how that credential authenticated. Same shape as Workspace with the caller's role and the auth method added, and without created_at (callers of this endpoint want identity, not provenance). + */ +export type CurrentWorkspaceResponse = { + /** + * How this request authenticated. Known values are firebase, cookie, comfy_api_key, comfy_admin_key, cloud_api_key and cloud_jwt; treat it as an open string so a new auth method is not a breaking change. + */ + auth_method: string + id: string + name: string + /** + * The requesting user's role in this workspace. Omitted (absent from the object, never an explicit null) when the credential carries no resolvable user membership. + */ + role?: 'owner' | 'member' + type: 'personal' | 'team' +} + /** * Request body for creating a new workspace. */ @@ -3432,7 +3559,8 @@ export type BillingStatusResponse = { * customer. Today this is a Stripe-hosted payment page for an invoice * needing authentication (SCA/3DS); * send the customer there to complete payment. Mirrors the field of - * the same name on BillingOpStatusResponse. + * the same name on BillingOpStatusResponse. This bearer capability is + * returned only to workspace billing managers. * */ action_url?: string @@ -3461,6 +3589,16 @@ export type BillingStatusResponse = { * Current workspace members plus non-expired pending invites, used against max_seats. 0 when billing is disabled. */ occupied_seats: number + /** + * Present when a pending operation supports embedded Stripe + * authentication. It may be returned alongside a hosted payment page + * when both recovery methods are available. This bearer + * capability is returned only to workspace billing managers. Pass + * directly to Stripe.js; do not log or + * persist it in client storage. + * + */ + payment_intent_client_secret?: string /** * The workspace's in-flight billing operation, when one exists. Lets a * client recover a payment it has lost the local reference to — a @@ -3532,30 +3670,84 @@ export type BillingOpStatusResponse = { * Present while status is "pending" and the operation cannot proceed * without the customer. Today this is a Stripe-hosted payment page for * a subscription whose first invoice needs authentication (SCA/3DS); - * send the customer there to complete payment. Absent otherwise. + * send the customer there to complete payment. This bearer capability is + * returned only to workspace billing managers. Absent otherwise. * */ action_url?: string + /** + * State derived from the PaymentIntent attached to this operation's + * exact stored Stripe invoice. Absent when the operation has no + * correlated PaymentIntent. + * + */ + authentication_state?: + | 'requires_action' + | 'processing' + | 'failed_retryable' + | 'succeeded' + | 'reconciliation_needed' /** * When the operation completed (success or failure) */ completed_at?: string /** - * Error message if status is failed + * Coarse classification of why the correlated PaymentIntent's last + * payment attempt failed, derived at read time from the provider's + * machine-readable error and decline codes — never from provider + * message text or payment-method details. Present only when the + * intent has recorded a failed attempt and the operation is either + * still pending with authentication_state failed_retryable or has + * terminally failed. generic means the attempt failed for a reason + * outside this vocabulary. + * + */ + decline_reason?: + | 'card_declined' + | 'insufficient_funds' + | 'expired_card' + | 'incorrect_cvc' + | 'authentication_required' + | 'authentication_failed' + | 'processing_error' + | 'generic' + /** + * PII-safe failure code or generic failure message */ error_message?: string /** * Unique identifier for the billing operation */ id: string + /** + * Stripe PaymentIntent client secret for completing requires_action. + * This bearer capability is returned only to workspace billing managers + * and is absent otherwise. + * + */ + payment_intent_client_secret?: string + /** + * Typed next action for a failed operation. Absent for pending and succeeded operations. + */ + recovery_action?: + | 'retry' + | 'replace_payment_method' + | 'authenticate_payment' + | 'contact_support' + /** + * Whether the customer can recover by starting a new billing operation after performing recovery_action. + */ + retryable?: boolean /** * When the operation was initiated */ started_at: string /** - * Current status of the operation + * Current status of the operation. reconciliation_needed is terminal + * for client polling but requires support reconciliation. + * */ - status: 'pending' | 'succeeded' | 'failed' + status: 'pending' | 'succeeded' | 'failed' | 'reconciliation_needed' } /** @@ -6100,6 +6292,45 @@ export type GetBillingOpStatusResponses = { export type GetBillingOpStatusResponse = GetBillingOpStatusResponses[keyof GetBillingOpStatusResponses] +export type ListSavedPaymentMethodsData = { + body?: never + path?: never + query?: never + url: '/api/billing/payment-methods' +} + +export type ListSavedPaymentMethodsErrors = { + /** + * Billing is disabled + */ + 400: ErrorResponse + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * Workspace owner role required + */ + 403: ErrorResponse + /** + * Internal server error + */ + 500: ErrorResponse +} + +export type ListSavedPaymentMethodsError = + ListSavedPaymentMethodsErrors[keyof ListSavedPaymentMethodsErrors] + +export type ListSavedPaymentMethodsResponses = { + /** + * Saved payment methods + */ + 200: Array +} + +export type ListSavedPaymentMethodsResponse = + ListSavedPaymentMethodsResponses[keyof ListSavedPaymentMethodsResponses] + export type GetPaymentPortalData = { body?: PaymentPortalRequest path?: never @@ -6182,6 +6413,10 @@ export type PreviewSubscribeErrors = { * Unauthorized */ 401: ErrorResponse + /** + * Workspace owner role required + */ + 403: ErrorResponse /** * Internal server error */ @@ -10901,6 +11136,41 @@ export type UpdateWorkspaceResponses = { export type UpdateWorkspaceResponse = UpdateWorkspaceResponses[keyof UpdateWorkspaceResponses] +export type GetCurrentWorkspaceData = { + body?: never + path?: never + query?: never + url: '/api/workspaces/current' +} + +export type GetCurrentWorkspaceErrors = { + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * No workspace resolves for this credential — it carries no workspace binding, the workspace was deleted, or the credential's user is no longer a member. Deliberately not 401: the credential itself is valid, so clients must not discard it or re-authenticate. + */ + 404: ErrorResponse + /** + * Internal server error + */ + 500: ErrorResponse +} + +export type GetCurrentWorkspaceError = + GetCurrentWorkspaceErrors[keyof GetCurrentWorkspaceErrors] + +export type GetCurrentWorkspaceResponses = { + /** + * The credential's workspace + */ + 200: CurrentWorkspaceResponse +} + +export type GetCurrentWorkspaceResponse = + GetCurrentWorkspaceResponses[keyof GetCurrentWorkspaceResponses] + export type GetStaticExtensionsData = { body?: never path: { diff --git a/packages/ingest-types/src/zod.gen.ts b/packages/ingest-types/src/zod.gen.ts index a4504755451..bbba6ea7a02 100644 --- a/packages/ingest-types/src/zod.gen.ts +++ b/packages/ingest-types/src/zod.gen.ts @@ -480,6 +480,21 @@ export const zSystemStatsResponse = z.object({ */ export const zSubscriptionDuration = z.enum(['MONTHLY', 'ANNUAL']) +export const zSubscriptionDiscount = z.object({ + amount_off_cents: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .max(BigInt('9223372036854775807'), { + message: 'Invalid value: Expected int64 to be <= 9223372036854775807' + }) + .optional(), + code: z.string(), + kind: z.enum(['plan', 'promotion']), + name: z.string().optional() +}) + /** * Response after successfully subscribing to a billing plan. */ @@ -497,10 +512,15 @@ export const zSubscribeRequest = z.object({ billing_cycle: z.enum(['monthly', 'yearly']).optional(), cancel_url: z.string().optional(), confirm_reactivation: z.boolean().optional(), + confirmation_token: z.string().optional(), idempotency_key: z.string().optional(), plan_slug: z.string(), + promotion_code: z.string().optional(), proration_at: z.string().datetime().optional(), + quote_id: z.string().optional(), + quote_version: z.number().int().optional(), return_url: z.string().optional(), + saved_payment_method_id: z.string().regex(/^pm_/).optional(), team_credit_stop_id: z.string().optional() }) @@ -549,6 +569,17 @@ export const zSecretListResponse = z.object({ data: z.array(zSecretResponse) }) +export const zSavedPaymentMethod = z.object({ + brand: z.string().optional(), + id: z.string().regex(/^pm_/), + is_default: z.boolean(), + last4: z + .string() + .regex(/^[0-9]{4}$/) + .optional(), + type: z.string() +}) + /** * Response after accepting a resubscribe request. */ @@ -763,6 +794,15 @@ export const zPreviewPlanInfo = z.object({ */ export const zPreviewSubscribeResponse = z.object({ allowed: z.boolean(), + amount_due_cents: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .max(BigInt('9223372036854775807'), { + message: 'Invalid value: Expected int64 to be <= 9223372036854775807' + }) + .optional(), cost_next_period_cents: z.coerce .bigint() .min(BigInt('-9223372036854775808'), { @@ -795,12 +835,29 @@ export const zPreviewSubscribeResponse = z.object({ .max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), + currency: z.string().optional(), current_plan: zPreviewPlanInfo.optional(), + discounts: z.array(zSubscriptionDiscount).optional(), effective_at: z.string().datetime(), is_immediate: z.boolean(), new_plan: zPreviewPlanInfo, + payment_method_configuration_id: z.string().optional(), + promotion_code: z.string().optional(), proration_at: z.string().datetime().optional(), + quote_id: z.string().optional(), + quote_version: z.number().int().optional(), reason: z.string().optional(), + renewal_amount_cents: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .max(BigInt('9223372036854775807'), { + message: 'Invalid value: Expected int64 to be <= 9223372036854775807' + }) + .optional(), + renewal_at: z.string().datetime().optional(), + requires_reactivation_confirmation: z.boolean().optional(), transition_type: z.enum([ 'new_subscription', 'upgrade', @@ -814,6 +871,7 @@ export const zPreviewSubscribeResponse = z.object({ */ export const zPreviewSubscribeRequest = z.object({ plan_slug: z.string(), + promotion_code: z.string().optional(), team_credit_stop_id: z.string().optional() }) @@ -1887,6 +1945,17 @@ export const zDeleteSessionResponse = z.object({ success: z.boolean() }) +/** + * The workspace bound to the presented credential, plus how that credential authenticated. Same shape as Workspace with the caller's role and the auth method added, and without created_at (callers of this endpoint want identity, not provenance). + */ +export const zCurrentWorkspaceResponse = z.object({ + auth_method: z.string(), + id: z.string(), + name: z.string(), + role: z.enum(['owner', 'member']).optional(), + type: z.enum(['personal', 'team']) +}) + /** * Request body for creating a new workspace. */ @@ -2062,6 +2131,7 @@ export const zBillingStatusResponse = z.object({ is_active: z.boolean(), max_seats: z.number().int(), occupied_seats: z.number().int(), + payment_intent_client_secret: z.string().optional(), pending_billing_op_id: z.string().optional(), pending_billing_op_type: z.enum(['subscription', 'topup']).optional(), plan_slug: z.string().optional(), @@ -2086,11 +2156,42 @@ export const zBillingPlansResponse = z.object({ */ export const zBillingOpStatusResponse = z.object({ action_url: z.string().optional(), + authentication_state: z + .enum([ + 'requires_action', + 'processing', + 'failed_retryable', + 'succeeded', + 'reconciliation_needed' + ]) + .optional(), completed_at: z.string().datetime().optional(), + decline_reason: z + .enum([ + 'card_declined', + 'insufficient_funds', + 'expired_card', + 'incorrect_cvc', + 'authentication_required', + 'authentication_failed', + 'processing_error', + 'generic' + ]) + .optional(), error_message: z.string().optional(), id: z.string(), + payment_intent_client_secret: z.string().optional(), + recovery_action: z + .enum([ + 'retry', + 'replace_payment_method', + 'authenticate_payment', + 'contact_support' + ]) + .optional(), + retryable: z.boolean().optional(), started_at: z.string().datetime(), - status: z.enum(['pending', 'succeeded', 'failed']) + status: z.enum(['pending', 'succeeded', 'failed', 'reconciliation_needed']) }) /** @@ -2990,6 +3091,17 @@ export const zGetBillingOpStatusData = z.object({ */ export const zGetBillingOpStatusResponse = zBillingOpStatusResponse +export const zListSavedPaymentMethodsData = z.object({ + body: z.never().optional(), + path: z.never().optional(), + query: z.never().optional() +}) + +/** + * Saved payment methods + */ +export const zListSavedPaymentMethodsResponse = z.array(zSavedPaymentMethod) + export const zGetPaymentPortalData = z.object({ body: zPaymentPortalRequest.optional(), path: z.never().optional(), @@ -4556,6 +4668,17 @@ export const zUpdateWorkspaceData = z.object({ */ export const zUpdateWorkspaceResponse = zWorkspace +export const zGetCurrentWorkspaceData = z.object({ + body: z.never().optional(), + path: z.never().optional(), + query: z.never().optional() +}) + +/** + * The credential's workspace + */ +export const zGetCurrentWorkspaceResponse = zCurrentWorkspaceResponse + export const zGetStaticExtensionsData = z.object({ body: z.never().optional(), path: z.object({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ada39788392..8750639cd3d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -99,6 +99,9 @@ catalogs: '@storybook/vue3-vite': specifier: ^10.5.6 version: 10.5.6 + '@stripe/stripe-js': + specifier: ^9.12.0 + version: 9.12.1 '@tailwindcss/vite': specifier: ^4.3.2 version: 4.3.2 @@ -497,6 +500,9 @@ importers: '@sparkjsdev/spark': specifier: 'catalog:' version: 2.1.0(three@0.184.0) + '@stripe/stripe-js': + specifier: 'catalog:' + version: 9.12.1 '@tanstack/vue-virtual': specifier: 'catalog:' version: 3.13.32(vue@3.5.41(typescript@6.0.3)) @@ -3819,6 +3825,10 @@ packages: storybook: ^10.5.6 vue: ^3.0.0 + '@stripe/stripe-js@9.12.1': + resolution: {integrity: sha512-KLXPvjA0BfS4dQnW+ddHjwtIXMnIfKYxqmeNMmQCfKjvYog0cSG+Z7ZvK4RH1+bV90GC07nUztWDRWmJLi5HZQ==} + engines: {node: '>=12.16'} + '@swc/helpers@0.5.23': resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} @@ -11922,6 +11932,8 @@ snapshots: vue: 3.5.41(typescript@6.0.3) vue-component-type-helpers: 3.3.9 + '@stripe/stripe-js@9.12.1': {} + '@swc/helpers@0.5.23': dependencies: tslib: 2.8.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index e713f6f2b02..e10ad43fbea 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -41,6 +41,7 @@ catalog: '@storybook/addon-mcp': 0.7.0 '@storybook/vue3': ^10.5.6 '@storybook/vue3-vite': ^10.5.6 + '@stripe/stripe-js': ^9.12.0 '@tailwindcss/vite': ^4.3.2 '@tanstack/vue-virtual': ^3.13.12 '@testing-library/jest-dom': ^6.9.1 diff --git a/src/assets/css/style.css b/src/assets/css/style.css index 5957d089293..594854795d5 100644 --- a/src/assets/css/style.css +++ b/src/assets/css/style.css @@ -1,5 +1,18 @@ @import '@comfyorg/design-system/css/style.css'; +/* Toasts teleport to . Reka's modal mode sets pointer-events: none on + the body, which left toast close buttons painted above dialogs but + unclickable — clicks fell through to whatever sat beneath (including the + payment dialog's X, closing the checkout mid-payment). Keep toasts + interactive regardless of modal state. */ +.p-toast { + pointer-events: none; +} + +.p-toast-message { + pointer-events: auto; +} + /* Use 0.001ms instead of 0s so transitionend/animationend events still fire and JS listeners aren't broken. */ .disable-animations *, diff --git a/src/components/dialog/GlobalDialog.test.ts b/src/components/dialog/GlobalDialog.test.ts index 2043e243f86..6d83d4f1386 100644 --- a/src/components/dialog/GlobalDialog.test.ts +++ b/src/components/dialog/GlobalDialog.test.ts @@ -31,10 +31,18 @@ vi.mock( isResubscribing: ref(false), previewData: ref(null), reactivationRequired: ref(false), + quoteIsCurrent: ref(false), + savedPaymentMethods: ref([]), + selectedSavedPaymentMethodId: ref(null), selectedTierKey: ref(null), selectedTeamStop: ref(null), selectedBillingCycle: ref('yearly'), activeCheckoutActionUrl: ref(null), + authenticationState: ref(null), + authenticationError: ref(null), + canRetryAuthentication: ref(false), + isAuthenticating: ref(false), + reconciliationOperationId: ref(null), isPolling: ref(false), isTeamCheckout: computed(() => false), previewVariant: computed(() => null), @@ -45,6 +53,11 @@ vi.mock( handleAddCreditCard: vi.fn(), handleConfirmTransition: vi.fn(), handleTeamSubscribe: vi.fn(), + handleSubscriptionPayment: vi.fn(), + handleTeamSubscriptionPayment: vi.fn(), + retryPaymentAuthentication: vi.fn(), + applyPromotionCode: vi.fn(), + invalidateQuote: vi.fn(), handleResubscribe: vi.fn() }) } diff --git a/src/components/graph/GraphCanvas.firstRunEntry.test.ts b/src/components/graph/GraphCanvas.firstRunEntry.test.ts index 63ac127cc10..6e8496565b3 100644 --- a/src/components/graph/GraphCanvas.firstRunEntry.test.ts +++ b/src/components/graph/GraphCanvas.firstRunEntry.test.ts @@ -16,7 +16,9 @@ import GraphCanvas from './GraphCanvas.vue' * feeds the startup outcome to `handleStartupOutcome`, and the URL workflow * results to `handleUrlWorkflow`. Both composables are unit-tested on their * own; this file covers the seam, so deleting either call from the startup - * sequence fails a test instead of silently disconnecting the feature. + * sequence fails a test instead of silently disconnecting the feature. It also + * pins the order the deep-link loaders depend on: dialogs they open must land + * on top of the overlays `handleStartupOutcome` establishes. */ const mocks = vi.hoisted(() => ({ handleStartupOutcome: vi.fn(), @@ -24,6 +26,7 @@ const mocks = vi.hoisted(() => ({ initializeWorkflow: vi.fn(), loadTemplateFromUrlIfPresent: vi.fn(), loadSharedWorkflowFromUrlIfPresent: vi.fn(), + runUrlActionLoaders: vi.fn(), workspaceStore: { spinner: false, focusMode: false, @@ -88,7 +91,9 @@ vi.mock('@/services/useNewUserService', () => ({ })) vi.mock('@/composables/useUrlActionLoaders', () => ({ - useUrlActionLoaders: () => ({ runUrlActionLoaders: vi.fn() }) + useUrlActionLoaders: () => ({ + runUrlActionLoaders: mocks.runUrlActionLoaders + }) })) vi.mock('@/platform/updates/common/releaseStore', () => ({ @@ -193,6 +198,14 @@ describe('GraphCanvas first-run tour wiring', () => { expect(mocks.handleStartupOutcome).toHaveBeenCalledWith('url-intent') }) + it('settles the startup outcome before running the URL action loaders', async () => { + await mountGraphCanvas() + + expect( + mocks.runUrlActionLoaders.mock.invocationCallOrder[0] + ).toBeGreaterThan(mocks.handleStartupOutcome.mock.invocationCallOrder[0]) + }) + it('offers the tour over a workflow that arrived from the URL', async () => { await mountGraphCanvas() diff --git a/src/composables/useFeatureFlags.test.ts b/src/composables/useFeatureFlags.test.ts index c93393e675e..398de40193a 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -147,6 +147,33 @@ describe('useFeatureFlags', () => { }) }) + describe('embeddedCheckoutEnabled', () => { + it.for([ + ['missing', undefined, false], + ['false', false, false], + ['malformed', 'true', false], + ['true', true, true] + ] as const)('is fail-closed for %s values', ([, value, expected]) => { + vi.mocked(api.getServerFeature).mockReturnValue(value) + + const { flags } = useFeatureFlags() + + expect(flags.embeddedCheckoutEnabled).toBe(expected) + expect(api.getServerFeature).toHaveBeenCalledWith( + 'embedded_checked_enabled', + false + ) + }) + + it('is false when feature lookup throws', () => { + vi.mocked(api.getServerFeature).mockImplementation(() => { + throw new Error('feature service unavailable') + }) + + expect(useFeatureFlags().flags.embeddedCheckoutEnabled).toBe(false) + }) + }) + describe('linearToggleEnabled', () => { it('should return true when isNightly is true', () => { vi.mocked(distributionTypes).isNightly = true diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index e8516a63780..711a3d184f0 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -36,6 +36,7 @@ export enum ServerFeatureFlag { UNIFIED_CLOUD_AUTH = 'unified_cloud_auth', BILLING_CONTROL_ENABLED = 'billing_control_enabled', LEGACY_BILLING_MIGRATION_ENABLED = 'legacy_billing_migration_enabled', + EMBEDDED_CHECKOUT_ENABLED = 'embedded_checked_enabled', V1_PAYMENT_RECOVERY = 'v1_payment_recovery', FREE_TIER_JOB_ALLOWANCE_ENABLED = 'free_tier_job_allowance_enabled', CHURNKEY_APP_ID = 'churnkey_app_id', @@ -84,6 +85,14 @@ function resolveAuthGatedFlag( return remoteConfigValue ?? api.getServerFeature(flagKey, false) } +function resolveFailClosedBooleanFlag(flagKey: string): boolean { + try { + return api.getServerFeature(flagKey, false) === true + } catch { + return false + } +} + /** * Composable for reactive access to server-side feature flags */ @@ -211,6 +220,11 @@ export function useFeatureFlags() { cachedLegacyBillingMigrationEnabled ) }, + get embeddedCheckoutEnabled() { + return resolveFailClosedBooleanFlag( + ServerFeatureFlag.EMBEDDED_CHECKOUT_ENABLED + ) + }, get v1PaymentRecovery() { return resolveAuthGatedFlag( ServerFeatureFlag.V1_PAYMENT_RECOVERY, diff --git a/src/composables/useUrlActionLoaders.test.ts b/src/composables/useUrlActionLoaders.test.ts index 08e1f43dc3d..a26eb5487d8 100644 --- a/src/composables/useUrlActionLoaders.test.ts +++ b/src/composables/useUrlActionLoaders.test.ts @@ -15,11 +15,15 @@ const mocks = vi.hoisted(() => ({ loadPricingTable: vi.fn(async () => undefined), loadTopUp: vi.fn(async () => undefined), loadSettings: vi.fn(), + loadPaymentReturn: vi.fn(async () => undefined), + resumePendingPricingFlow: vi.fn(async () => undefined), useInvite: vi.fn(), useCreateWorkspace: vi.fn(), usePricingTable: vi.fn(), useTopUp: vi.fn(), - useSettings: vi.fn() + useSettings: vi.fn(), + usePaymentReturn: vi.fn(), + useSubscriptionDialog: vi.fn() })) mocks.useInvite.mockImplementation(() => ({ loadInviteFromUrl: mocks.loadInvite @@ -36,6 +40,12 @@ mocks.useTopUp.mockImplementation(() => ({ mocks.useSettings.mockImplementation(() => ({ loadSettingsFromUrl: mocks.loadSettings })) +mocks.usePaymentReturn.mockImplementation(() => ({ + loadPaymentReturnFromUrl: mocks.loadPaymentReturn +})) +mocks.useSubscriptionDialog.mockImplementation(() => ({ + resumePendingPricingFlow: mocks.resumePendingPricingFlow +})) vi.mock('@/platform/workspace/composables/useInviteUrlLoader', () => ({ useInviteUrlLoader: mocks.useInvite @@ -53,6 +63,14 @@ vi.mock('@/platform/cloud/subscription/composables/useTopUpUrlLoader', () => ({ vi.mock('@/platform/settings/composables/useSettingsUrlLoader', () => ({ useSettingsUrlLoader: mocks.useSettings })) +vi.mock( + '@/platform/cloud/subscription/composables/usePaymentReturnUrlLoader', + () => ({ usePaymentReturnUrlLoader: mocks.usePaymentReturn }) +) +vi.mock( + '@/platform/cloud/subscription/composables/useSubscriptionDialog', + () => ({ useSubscriptionDialog: mocks.useSubscriptionDialog }) +) describe('useUrlActionLoaders', () => { beforeEach(() => { @@ -72,6 +90,12 @@ describe('useUrlActionLoaders', () => { mocks.useSettings.mockImplementation(() => ({ loadSettingsFromUrl: mocks.loadSettings })) + mocks.usePaymentReturn.mockImplementation(() => ({ + loadPaymentReturnFromUrl: mocks.loadPaymentReturn + })) + mocks.useSubscriptionDialog.mockImplementation(() => ({ + resumePendingPricingFlow: mocks.resumePendingPricingFlow + })) }) it('does not instantiate or run any loader off cloud', async () => { @@ -85,11 +109,15 @@ describe('useUrlActionLoaders', () => { expect(mocks.usePricingTable).not.toHaveBeenCalled() expect(mocks.useTopUp).not.toHaveBeenCalled() expect(mocks.useSettings).not.toHaveBeenCalled() + expect(mocks.usePaymentReturn).not.toHaveBeenCalled() + expect(mocks.useSubscriptionDialog).not.toHaveBeenCalled() expect(mocks.loadInvite).not.toHaveBeenCalled() expect(mocks.loadCreateWorkspace).not.toHaveBeenCalled() expect(mocks.loadPricingTable).not.toHaveBeenCalled() expect(mocks.loadTopUp).not.toHaveBeenCalled() expect(mocks.loadSettings).not.toHaveBeenCalled() + expect(mocks.loadPaymentReturn).not.toHaveBeenCalled() + expect(mocks.resumePendingPricingFlow).not.toHaveBeenCalled() }) it('runs all loaders on Cloud', async () => { @@ -101,6 +129,26 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadPricingTable).toHaveBeenCalledOnce() expect(mocks.loadTopUp).toHaveBeenCalledOnce() expect(mocks.loadSettings).toHaveBeenCalledOnce() + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() + }) + + it('recovers an interrupted checkout after handling the payment return', async () => { + const { runUrlActionLoaders } = useUrlActionLoaders() + await runUrlActionLoaders() + + expect(mocks.resumePendingPricingFlow).toHaveBeenCalledOnce() + expect( + mocks.resumePendingPricingFlow.mock.invocationCallOrder[0] + ).toBeGreaterThan(mocks.loadPaymentReturn.mock.invocationCallOrder[0]) + }) + + it('isolates a checkout-recovery failure so it does not abort the boot chain', async () => { + mocks.resumePendingPricingFlow.mockRejectedValueOnce(new Error('boom')) + + const { runUrlActionLoaders } = useUrlActionLoaders() + await expect(runUrlActionLoaders()).resolves.toBeUndefined() + + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() }) it('isolates a pricing-loader failure so it does not abort the boot chain', async () => { @@ -122,6 +170,7 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadPricingTable).toHaveBeenCalledOnce() expect(mocks.loadSettings).toHaveBeenCalledOnce() + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() }) it('isolates a settings-loader failure so it does not abort the boot chain', async () => { @@ -132,6 +181,7 @@ describe('useUrlActionLoaders', () => { const { runUrlActionLoaders } = useUrlActionLoaders() await expect(runUrlActionLoaders()).resolves.toBeUndefined() - expect(mocks.loadTopUp).toHaveBeenCalledOnce() + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() + expect(mocks.resumePendingPricingFlow).toHaveBeenCalledOnce() }) }) diff --git a/src/composables/useUrlActionLoaders.ts b/src/composables/useUrlActionLoaders.ts index b291d8bb714..169d64133ac 100644 --- a/src/composables/useUrlActionLoaders.ts +++ b/src/composables/useUrlActionLoaders.ts @@ -1,4 +1,6 @@ +import { usePaymentReturnUrlLoader } from '@/platform/cloud/subscription/composables/usePaymentReturnUrlLoader' import { usePricingTableUrlLoader } from '@/platform/cloud/subscription/composables/usePricingTableUrlLoader' +import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { useTopUpUrlLoader } from '@/platform/cloud/subscription/composables/useTopUpUrlLoader' import { isCloud } from '@/platform/distribution/types' import { useSettingsUrlLoader } from '@/platform/settings/composables/useSettingsUrlLoader' @@ -7,9 +9,10 @@ import { useInviteUrlLoader } from '@/platform/workspace/composables/useInviteUr /** * Aggregates the query-param "deep link" loaders the cloud app checks on mount - * (`?invite`, `?create_workspace`, `?pricing`, `?topup`, `?settings`). The - * loaders are instantiated in setup so their `useRoute`/`useRouter` resolve; - * call `runUrlActionLoaders()` from `onMounted` once the app is ready. + * (`?invite`, `?create_workspace`, `?pricing`, `?topup`, `?settings`), then + * recovers an interrupted checkout. The loaders are instantiated in setup so + * their `useRoute`/`useRouter` resolve; call `runUrlActionLoaders()` from + * `onMounted` once the app is ready. */ export function useUrlActionLoaders() { const inviteUrlLoader = isCloud ? useInviteUrlLoader() : null @@ -19,6 +22,8 @@ export function useUrlActionLoaders() { const pricingTableUrlLoader = isCloud ? usePricingTableUrlLoader() : null const topUpUrlLoader = isCloud ? useTopUpUrlLoader() : null const settingsUrlLoader = isCloud ? useSettingsUrlLoader() : null + const paymentReturnUrlLoader = isCloud ? usePaymentReturnUrlLoader() : null + const subscriptionDialog = isCloud ? useSubscriptionDialog() : null async function runUrlActionLoaders() { // Accept workspace invite from URL if present (e.g., ?invite=TOKEN). @@ -74,6 +79,34 @@ export function useUrlActionLoaders() { ) } } + + // Handle the return leg of a redirect payment (Stripe appends + // payment_intent/redirect_status params): strip the params and refresh + // billing status so the pending checkout resumes polling immediately. + if (paymentReturnUrlLoader) { + try { + await paymentReturnUrlLoader.loadPaymentReturnFromUrl() + } catch (error) { + console.error( + '[UrlActionLoaders] Failed to handle payment return from URL:', + error + ) + } + } + + // Reopen a checkout that was interrupted by a redirect payment. Runs here, + // not during workspace init, so the first-run and Templates overlays are + // already settled and the recovered dialog is reachable. + if (subscriptionDialog) { + try { + await subscriptionDialog.resumePendingPricingFlow() + } catch (error) { + console.error( + '[UrlActionLoaders] Failed to resume pending billing flow:', + error + ) + } + } } return { runUrlActionLoaders } diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 7a100514634..e9bb6a260dd 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2653,7 +2653,7 @@ "addMoreCreditsToRun": "Add more credits to run", "insufficientWorkflowMessage": "You don't have enough credits to run this workflow.", "creditsDescription": "Credits are used to run workflows or partner nodes.", - "chargedImmediatelyNote": "Your saved card is charged immediately.", + "chargedImmediatelyNote": "Your saved payment method is charged immediately.", "confirmSubtitle": "Credits are added to this workspace as soon as payment completes.", "confirmTitle": "Confirm", "howManyCredits": "How many credits would you like to add?", @@ -2718,6 +2718,17 @@ "topupSuccess": "Credits added successfully", "topupFailed": "Top-up failed", "topupTimeout": "Top-up verification timed out", + "paymentDeclinedDetail": "Your bank declined this payment. Try another payment method or contact your bank.", + "insufficientFundsDetail": "This payment method has insufficient funds. Try another payment method or contact your bank.", + "expiredCardDetail": "This card has expired. Use a different payment method.", + "incorrectCvcDetail": "The card security code is incorrect. Check it and try again.", + "processingErrorDetail": "Your payment couldn't be processed. Try again or use another payment method.", + "authenticationUnavailable": "Secure payment authentication is unavailable. Please refresh and try again.", + "authenticationFailedDetail": "We couldn't complete payment verification. Please try again.", + "authenticationManagerRequired": "Payment verification needs attention from a workspace billing manager.", + "retryVerification": "Retry verification", + "reconciliationTitle": "Payment received — confirmation pending", + "reconciliationDetail": "Your payment was received, but we couldn't finish updating your workspace. Contact support and include this operation ID:", "cancelFailed": "Failed to cancel subscription", "cancelTimeout": "Subscription cancellation timed out" }, @@ -3026,6 +3037,12 @@ "confirmChange": "Confirm change", "confirmChangeTitle": "Review your scheduled change", "paymentPopupBlocked": "Couldn't open the payment page — please allow popups and try again.", + "paymentMethod": "Payment method", + "stripeMethodChoice": "Your payment details are handled securely by Stripe.", + "alipayRenewalNote": "Alipay authorization will also be used for automatic renewals and future purchases.", + "payAndSubscribe": "Pay and subscribe", + "stripeUnavailable": "Payment options are unavailable. Please refresh and try again.", + "quoteUnavailable": "Unavailable", "switchesToday": "Switches today", "startsOn": "Starts {date}", "yearlySubscription": "Yearly subscription", @@ -3039,7 +3056,7 @@ "creditsRefillMonthlyTo": "Credits refill monthly to", "billedEachMonth": "{amount} billed each month. Cancel anytime.", "stayOnUntil": "You'll stay on {plan} until {date}.", - "termsAgreement": "By continuing, you agree to Comfy Org's {terms} and {privacy}.", + "termsAgreement": "By continuing, you agree to Comfy Org's {terms} and {privacy}, and authorize Comfy Org to charge your payment method each billing period until you cancel.", "terms": "Terms", "privacyPolicy": "Privacy Policy", "addCreditCard": "Add credit card", @@ -3060,7 +3077,22 @@ "confirmationRequired": "Your subscription is cancelled — please confirm the reactivation charge before continuing", "amountChanged": "The charge amount changed since you confirmed it — please review and try again", "unavailable": "We can't confirm this reactivation right now — please choose your plan again" - } + }, + "promoCodePlaceholder": "Promo code", + "applyPromoCode": "Apply", + "applyQuoteBeforeContinuing": "Apply the promo code to refresh your quote before continuing.", + "quoteStale": "Your quote changed. Review the updated amount and try again.", + "quoteRefreshFailed": "Your quote expired and couldn't be refreshed. Choose your plan again.", + "renewsAt": "Renews at {amount} on {date}. Cancel anytime.", + "discountComposition": "Discounts", + "discount": { + "plan": "Plan discount", + "promotion": "Promo code" + }, + "changePaymentMethod": "Change", + "savedPaymentMethod": "Payment method", + "addNewPaymentMethod": "Add new payment method", + "alipay": "Alipay" }, "success": { "allSet": "You're all set", @@ -3069,7 +3101,9 @@ "inviteTitle": "Invite your team", "planUpdated": "Your plan has been successfully updated.", "receiptEmailed": "A receipt has been emailed to you.", - "sendInvites": "Send invites" + "sendInvites": "Send invites", + "promoApplied": "{code} applied.", + "promoRenews": "Renews at {amount} on {date}" } }, "userSettings": { diff --git a/src/main.ts b/src/main.ts index 38fd07172c8..16220fea63c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -24,6 +24,7 @@ import { flushErrorReports } from '@/platform/telemetry/reportError' import '@/lib/litegraph/public/css/litegraph.css' import router from '@/router' import { isDesktop, isNightly } from '@/platform/distribution/types' +import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' import { useToastStore } from '@/platform/updates/common/toastStore' import { useBootstrapStore } from '@/stores/bootstrapStore' @@ -35,6 +36,8 @@ import { i18n } from './i18n' const isCloud = __DISTRIBUTION__ === 'cloud' const hasHostTelemetryBridge = Boolean(window.__comfyDesktop2?.Telemetry) +if (isCloud) stripPaymentReturnParams() + // Load remote config before initializeApp() below, so getFirebaseConfig() resolves // against the server's runtime values instead of the build-time defaults. const { refreshRemoteConfig } = diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts new file mode 100644 index 00000000000..20574992ce8 --- /dev/null +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' + +import { usePaymentReturnUrlLoader } from './usePaymentReturnUrlLoader' + +const mocks = vi.hoisted(() => ({ + fetchStatus: vi.fn().mockResolvedValue(undefined), + embeddedCheckoutEnabled: true +})) + +vi.mock('@/composables/billing/useBillingContext', () => ({ + useBillingContext: () => ({ fetchStatus: mocks.fetchStatus }) +})) + +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get embeddedCheckoutEnabled() { + return mocks.embeddedCheckoutEnabled + } + } + }) +})) + +describe('usePaymentReturnUrlLoader', () => { + beforeEach(() => { + mocks.embeddedCheckoutEnabled = true + window.history.replaceState({}, '', '/') + }) + + it('refreshes billing after bootstrap strips Stripe return params', async () => { + window.history.replaceState( + {}, + '', + '/?payment_intent=pi_123&payment_intent_client_secret=pi_123_secret_abc&redirect_status=succeeded&workspace=ws-1' + ) + stripPaymentReturnParams() + + const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() + await loadPaymentReturnFromUrl() + + expect(window.location.search).toBe('?workspace=ws-1') + expect(mocks.fetchStatus).toHaveBeenCalledOnce() + }) + + it('does nothing on an ordinary page load', async () => { + window.history.replaceState({}, '', '/?workspace=ws-1') + + const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() + await loadPaymentReturnFromUrl() + + expect(mocks.fetchStatus).not.toHaveBeenCalled() + }) + + it('does not start embedded recovery while the flag is off', async () => { + mocks.embeddedCheckoutEnabled = false + window.history.replaceState( + {}, + '', + '/?payment_intent=pi_123&redirect_status=succeeded' + ) + stripPaymentReturnParams() + + await usePaymentReturnUrlLoader().loadPaymentReturnFromUrl() + + expect(mocks.fetchStatus).not.toHaveBeenCalled() + }) +}) diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.ts new file mode 100644 index 00000000000..1184c77f017 --- /dev/null +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.ts @@ -0,0 +1,27 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { consumePaymentReturn } from '@/platform/cloud/subscription/utils/paymentReturnUrl' + +/** + * Handles the return leg of a redirect payment method (Alipay). The checkout's + * `return_url` points back at the page it started on, and Stripe appends + * `payment_intent`, `payment_intent_client_secret`, and `redirect_status` to + * it. The client secret is a bearer capability, so it must not linger in the + * address bar or history; strip all three, then refresh billing status so the + * pending-operation recovery resumes polling the in-flight checkout without + * waiting for the next scheduled read. + */ +export function usePaymentReturnUrlLoader() { + const billingContext = useBillingContext() + const { flags } = useFeatureFlags() + + async function loadPaymentReturnFromUrl() { + if (!consumePaymentReturn()) return + if (!flags.embeddedCheckoutEnabled) return + await billingContext.fetchStatus() + } + + return { + loadPaymentReturnFromUrl + } +} diff --git a/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts b/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts index d60029d06ec..8ff2414128a 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts @@ -1,5 +1,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { SubscriptionInfo } from '@/composables/billing/types' +import type { + BillingSubscriptionStatus, + TeamCreditStops, + TeamCreditStopSummary +} from '@/platform/workspace/api/workspaceApi' +import { savePendingSubscriptionCheckout } from '@/platform/workspace/utils/pendingSubscriptionCheckout' + import { useSubscriptionDialog } from './useSubscriptionDialog' const mockCloseDialog = vi.fn() @@ -18,6 +26,24 @@ const mockIsLegacyTeamPlan = vi.hoisted(() => ({ value: false })) const mockIsTeamPlan = vi.hoisted(() => ({ value: false })) const mockCurrentPlanSlug = vi.hoisted(() => ({ value: null as string | null })) const mockCanManageSubscription = vi.hoisted(() => ({ value: true })) +const mockEmbeddedCheckoutEnabled = vi.hoisted(() => ({ value: false })) +const mockActiveWorkspaceId = vi.hoisted(() => ({ value: 'workspace-1' })) +const mockUserId = vi.hoisted(() => ({ value: 'user-1' as string | undefined })) +const mockStartOperation = vi.hoisted(() => vi.fn()) +const mockFetchPlans = vi.hoisted(() => vi.fn()) +const mockFetchStatus = vi.hoisted(() => vi.fn()) +const mockTeamCreditStops = vi.hoisted(() => ({ + value: null as TeamCreditStops | null +})) +const mockCurrentTeamCreditStop = vi.hoisted(() => ({ + value: null as TeamCreditStopSummary | null +})) +const mockSubscription = vi.hoisted(() => ({ + value: null as Pick | null +})) +const mockSubscriptionStatus = vi.hoisted(() => ({ + value: null as BillingSubscriptionStatus | null +})) vi.mock('vue', async (importOriginal) => { const actual = await importOriginal() @@ -55,6 +81,16 @@ vi.mock('@/composables/billing/useBillingRouting', () => ({ }) })) +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get embeddedCheckoutEnabled() { + return mockEmbeddedCheckoutEnabled.value + } + } + }) +})) + vi.mock('@/platform/distribution/types', () => ({ get isCloud() { return mockIsCloud.value @@ -63,19 +99,40 @@ vi.mock('@/platform/distribution/types', () => ({ vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ useTeamWorkspaceStore: () => ({ + get activeWorkspaceId() { + return mockActiveWorkspaceId.value + }, get isInPersonalWorkspace() { return mockIsInPersonalWorkspace.value } }) })) +vi.mock('@/platform/workspace/stores/billingOperationStore', () => ({ + useBillingOperationStore: () => ({ startOperation: mockStartOperation }) +})) + +vi.mock('@/stores/authStore', () => ({ + useAuthStore: () => ({ + get userId() { + return mockUserId.value + } + }) +})) + vi.mock('@/composables/billing/useBillingContext', () => ({ useBillingContext: () => ({ isFreeTier: mockIsFreeTier, isLegacyTeamPlan: mockIsLegacyTeamPlan, isTeamPlan: mockIsTeamPlan, currentPlanSlug: mockCurrentPlanSlug, - tier: mockTier + tier: mockTier, + fetchPlans: mockFetchPlans, + fetchStatus: mockFetchStatus, + teamCreditStops: mockTeamCreditStops, + currentTeamCreditStop: mockCurrentTeamCreditStop, + subscription: mockSubscription, + subscriptionStatus: mockSubscriptionStatus }) })) @@ -117,6 +174,17 @@ describe('useSubscriptionDialog', () => { mockIsTeamPlan.value = false mockCurrentPlanSlug.value = null mockCanManageSubscription.value = true + mockEmbeddedCheckoutEnabled.value = false + mockActiveWorkspaceId.value = 'workspace-1' + mockUserId.value = 'user-1' + mockStartOperation.mockResolvedValue({ status: 'succeeded' }) + mockFetchPlans.mockResolvedValue(undefined) + mockFetchStatus.mockResolvedValue(undefined) + mockTeamCreditStops.value = null + mockCurrentTeamCreditStop.value = null + mockSubscription.value = null + mockSubscriptionStatus.value = null + sessionStorage.clear() }) describe('showPricingTable', () => { @@ -301,6 +369,19 @@ describe('useSubscriptionDialog', () => { const props = mockShowLayoutDialog.mock.calls[0][0].props expect(props.initialPlanMode).toBe('personal') expect(props).not.toHaveProperty('onChooseTeam') + expect(props.embeddedCheckoutEnabled).toBe(false) + }) + + it('enables embedded checkout only for the exact server flag', () => { + mockShouldUseWorkspaceBilling.value = true + mockEmbeddedCheckoutEnabled.value = true + const { showPricingTable } = useSubscriptionDialog() + + showPricingTable() + + expect( + mockShowLayoutDialog.mock.calls[0][0].props.embeddedCheckoutEnabled + ).toBe(true) }) it('routes an existing per-member (legacy) team subscriber to the old team table', () => { @@ -543,7 +624,7 @@ describe('useSubscriptionDialog', () => { it('does nothing when no resume intent is stored', () => { const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() expect(mockShowLayoutDialog).not.toHaveBeenCalled() }) @@ -555,7 +636,7 @@ describe('useSubscriptionDialog', () => { mockCurrentPlanSlug.value = 'creator-monthly' const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBeNull() expect(mockShowLayoutDialog).toHaveBeenCalledWith( @@ -571,7 +652,7 @@ describe('useSubscriptionDialog', () => { mockIsInPersonalWorkspace.value = true const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBeNull() expect(mockShowLayoutDialog).not.toHaveBeenCalled() @@ -582,11 +663,241 @@ describe('useSubscriptionDialog', () => { mockIsInPersonalWorkspace.value = false const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() mockShowLayoutDialog.mockClear() - resumePendingPricingFlow() + void resumePendingPricingFlow() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + }) + + it('reconciles a failed redirect and reopens the attempted checkout', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'failed' }) + savePendingSubscriptionCheckout({ + operationId: 'op-alipay', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).toHaveBeenCalledWith( + 'op-alipay', + 'subscription', + { + tier: 'creator', + cycle: 'monthly', + attemptStartedAt: expect.any(Number) + } + ) + expect(mockShowLayoutDialog).toHaveBeenCalledWith( + expect.objectContaining({ + props: expect.objectContaining({ + initialPlanMode: 'personal', + initialCheckout: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + } + }) + }) + ) + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('completes a succeeded redirect silently', async () => { + mockShouldUseWorkspaceBilling.value = true + savePendingSubscriptionCheckout({ + operationId: 'op-succeeded', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).toHaveBeenCalledOnce() expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('does not reopen checkout when reconciliation times out', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'timeout' }) + savePendingSubscriptionCheckout({ + operationId: 'op-timeout', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('clears a checkout owned by another user without reconciling it', async () => { + savePendingSubscriptionCheckout({ + operationId: 'op-other-user', + workspaceId: 'workspace-1', + ownerUid: 'user-2', + selection: { + planMode: 'personal', + tierKey: 'standard', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).not.toHaveBeenCalled() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('clears a checkout for another workspace without reconciling it', async () => { + savePendingSubscriptionCheckout({ + operationId: 'op-other-workspace', + workspaceId: 'workspace-2', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'standard', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).not.toHaveBeenCalled() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('restores a Team plan change from fresh catalog and subscription state', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'failed' }) + mockFetchPlans.mockImplementationOnce(async () => { + mockTeamCreditStops.value = { + default_stop_index: 0, + stops: [ + { + id: 'team_700', + credits: 147_700, + monthly: { + list_price_cents: 70_000, + price_cents: 66_500 + }, + yearly: { + list_price_cents: 70_000, + price_cents: 63_000 + } + } + ] + } + }) + mockFetchStatus.mockImplementationOnce(async () => { + mockCurrentTeamCreditStop.value = { + id: 'team_400', + stop_usd: 400, + credits_monthly: 84_400 + } + mockSubscription.value = { duration: 'MONTHLY' } + mockSubscriptionStatus.value = 'active' + }) + savePendingSubscriptionCheckout({ + operationId: 'op-team-change', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'team', + teamCreditStopId: 'team_700', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockShowLayoutDialog).toHaveBeenCalledWith( + expect.objectContaining({ + props: expect.objectContaining({ + initialCheckout: { + planMode: 'team', + stop: { + id: 'team_700', + credits: 147_700, + usd: 700, + discountedUsd: 630 + }, + billingCycle: 'yearly', + isChange: true + } + }) + }) + ) + }) + + it('falls back to Team pricing when the stop catalog is unavailable', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'failed' }) + savePendingSubscriptionCheckout({ + operationId: 'op-team-catalog-failure', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'team', + teamCreditStopId: 'team_700', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockShowLayoutDialog).toHaveBeenCalledWith( + expect.objectContaining({ + props: expect.objectContaining({ initialPlanMode: 'team' }) + }) + ) + const props = mockShowLayoutDialog.mock.calls[0][0].props + expect(props.initialCheckout).toBeUndefined() }) }) }) diff --git a/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts b/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts index ffc40d20cdd..92e1ec7bf3b 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts @@ -3,12 +3,24 @@ import { useDialogService } from '@/services/dialogService' import { useDialogStore } from '@/stores/dialogStore' import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingRouting } from '@/composables/billing/useBillingRouting' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { + getStopDiscountedMonthlyUsd, + mapApiTeamCreditStops +} from '@/platform/cloud/subscription/constants/teamPlanCreditStops' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { PaymentIntentSource } from '@/platform/telemetry/types' import type { SubscriptionCheckoutSelection } from '@/platform/workspace/composables/useSubscriptionCheckout' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' +import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useAuthStore } from '@/stores/authStore' +import { + clearPendingSubscriptionCheckout, + getPendingSubscriptionCheckout +} from '@/platform/workspace/utils/pendingSubscriptionCheckout' +import type { PendingSubscriptionCheckout } from '@/platform/workspace/utils/pendingSubscriptionCheckout' const DIALOG_KEY = 'subscription-required' const RESUME_PRICING_KEY = 'comfy:resume-team-pricing' @@ -43,6 +55,7 @@ export const useSubscriptionDialog = () => { const dialogService = useDialogService() const dialogStore = useDialogStore() const workspaceStore = useTeamWorkspaceStore() + const { flags } = useFeatureFlags() function hide() { dialogStore.closeDialog({ key: DIALOG_KEY }) @@ -148,6 +161,7 @@ export const useSubscriptionDialog = () => { props: { onClose: hide, reason: options?.reason, + embeddedCheckoutEnabled: flags.embeddedCheckoutEnabled, initialCheckout: options?.initialCheckout, initialPlanMode: getInitialPlanMode( options?.planMode, @@ -164,6 +178,8 @@ export const useSubscriptionDialog = () => { // steps shrink (the content root sets its own width per checkoutStep). renderer: 'reka', size: 'full', + // A scrim click mid-checkout would silently discard typed card + // details and any pending 3DS state; the X is the only close. dismissableMask: false, contentClass: 'w-fit max-w-[min(1280px,95vw)] sm:max-w-[min(1280px,95vw)] max-h-[90vh] rounded-2xl border border-border-default bg-secondary-background shadow-[0_25px_80px_rgba(5,6,12,0.45)]' @@ -222,11 +238,86 @@ export const useSubscriptionDialog = () => { }) } - /** - * Check for and consume a pending team pricing resume intent. - * Call once after workspace initialization on app boot. - */ - function resumePendingPricingFlow() { + async function restoreCheckoutSelection( + pending: PendingSubscriptionCheckout + ): Promise { + const selection = pending.selection + if (selection.planMode === 'personal') return selection + + const { + fetchPlans, + fetchStatus, + teamCreditStops, + currentTeamCreditStop, + subscription, + subscriptionStatus + } = useBillingContext() + await Promise.all([fetchPlans(), fetchStatus()]) + const stop = mapApiTeamCreditStops(teamCreditStops.value?.stops ?? []).find( + ({ id }) => id === selection.teamCreditStopId + ) + if (!stop?.id) return null + + return { + planMode: 'team', + stop: { + id: stop.id, + usd: stop.usd, + credits: stop.credits, + discountedUsd: getStopDiscountedMonthlyUsd(stop, selection.billingCycle) + }, + billingCycle: selection.billingCycle, + isChange: + currentTeamCreditStop.value !== null && + subscriptionStatus.value !== 'ended' && + (currentTeamCreditStop.value.id !== stop.id || + (subscription.value?.duration === 'MONTHLY' + ? 'monthly' + : 'yearly') !== selection.billingCycle) + } + } + + async function resumePendingCheckout( + pending: PendingSubscriptionCheckout + ): Promise { + if ( + pending.workspaceId !== workspaceStore.activeWorkspaceId || + pending.ownerUid !== useAuthStore().userId + ) { + clearPendingSubscriptionCheckout(pending.operationId) + return + } + + const billingOperationStore = useBillingOperationStore() + try { + const operation = await billingOperationStore.startOperation( + pending.operationId, + 'subscription', + { + tier: + pending.selection.planMode === 'personal' + ? pending.selection.tierKey + : 'team', + cycle: pending.selection.billingCycle, + attemptStartedAt: pending.attemptedAt + } + ) + if (operation.status !== 'failed') return + + const initialCheckout = await restoreCheckoutSelection(pending) + showPricingTable({ + planMode: pending.selection.planMode, + ...(initialCheckout && { initialCheckout }) + }) + } finally { + clearPendingSubscriptionCheckout(pending.operationId) + } + } + + function resumePendingPricingFlow(): Promise | void { + const pendingCheckout = getPendingSubscriptionCheckout() + if (pendingCheckout) return resumePendingCheckout(pendingCheckout) + try { const pending = sessionStorage.getItem(RESUME_PRICING_KEY) if (!pending) return diff --git a/src/platform/cloud/subscription/utils/paymentReturnUrl.test.ts b/src/platform/cloud/subscription/utils/paymentReturnUrl.test.ts new file mode 100644 index 00000000000..faf1c1176ed --- /dev/null +++ b/src/platform/cloud/subscription/utils/paymentReturnUrl.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from 'vitest' + +import { paymentReturnUrl } from './paymentReturnUrl' + +vi.mock('@/config/comfyApi', () => ({ + getComfyPlatformBaseUrl: () => 'https://platform.comfy.org' +})) + +describe('paymentReturnUrl', () => { + it('returns to the page the checkout started on, without query or hash', () => { + vi.stubGlobal('location', { + origin: 'https://cloud.comfy.org', + pathname: '/workspace/abc', + search: '?pricing=team', + hash: '#section' + }) + expect(paymentReturnUrl()).toBe('https://cloud.comfy.org/workspace/abc') + }) + + it('accepts an HTTP origin', () => { + vi.stubGlobal('location', { + origin: 'http://localhost:5173', + pathname: '/workspace/abc' + }) + + expect(paymentReturnUrl()).toBe('http://localhost:5173/workspace/abc') + }) + + it('falls back to the platform success page on a non-HTTP origin, which the backend would reject', () => { + vi.stubGlobal('location', { + origin: 'file://', + pathname: '/index.html' + }) + expect(paymentReturnUrl()).toBe( + 'https://platform.comfy.org/payment/success' + ) + }) +}) diff --git a/src/platform/cloud/subscription/utils/paymentReturnUrl.ts b/src/platform/cloud/subscription/utils/paymentReturnUrl.ts new file mode 100644 index 00000000000..bb79fd6e06d --- /dev/null +++ b/src/platform/cloud/subscription/utils/paymentReturnUrl.ts @@ -0,0 +1,44 @@ +import { getComfyPlatformBaseUrl } from '@/config/comfyApi' + +const STRIPE_RETURN_PARAMS = [ + 'payment_intent', + 'payment_intent_client_secret', + 'redirect_status' +] as const + +let paymentReturnPending = false + +export function stripPaymentReturnParams(): void { + const url = new URL(globalThis.location.href) + const returnParams = STRIPE_RETURN_PARAMS.filter((param) => + url.searchParams.has(param) + ) + if (returnParams.length === 0) return + + paymentReturnPending = true + for (const param of returnParams) url.searchParams.delete(param) + globalThis.history.replaceState(globalThis.history.state, '', url) +} + +export function consumePaymentReturn(): boolean { + stripPaymentReturnParams() + const pending = paymentReturnPending + paymentReturnPending = false + return pending +} + +/** + * Where a redirect payment method (Alipay) or a hosted checkout sends the + * customer afterwards. Returning to the page the checkout started on keeps + * them in the app, where the pending-operation recovery on the next billing + * status read resumes polling and completes the flow. Non-HTTP origins + * (Electron) fall back to the platform success page: the backend requires an + * absolute HTTP(S) return URL. + */ +export function paymentReturnUrl(): string { + const { origin, pathname } = globalThis.location + if (origin?.startsWith('https://') || origin?.startsWith('http://')) { + return `${origin}${pathname}` + } + return `${getComfyPlatformBaseUrl()}/payment/success` +} diff --git a/src/platform/cloud/subscription/utils/subscriptionQuoteFormatting.ts b/src/platform/cloud/subscription/utils/subscriptionQuoteFormatting.ts new file mode 100644 index 00000000000..67e9fb9055c --- /dev/null +++ b/src/platform/cloud/subscription/utils/subscriptionQuoteFormatting.ts @@ -0,0 +1,11 @@ +export function formatQuoteMoney( + cents: number, + currency: string | undefined, + locale: string +): string { + if (!currency) return '' + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: currency.toUpperCase() + }).format(cents / 100) +} diff --git a/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts b/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts index 4991f0c3b1b..811aa4b1176 100644 --- a/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts +++ b/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts @@ -7,6 +7,7 @@ import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFai import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { trackWorkspaceCheckoutStarted } from '@/platform/workspace/utils/workspaceCheckoutTelemetry' +import { paymentReturnUrl } from './paymentReturnUrl' import type { BillingCycle } from './subscriptionTierRank' interface PerformTeamSubscriptionCheckoutOptions { @@ -63,7 +64,7 @@ async function initiateTeamSubscriptionCheckout( ): Promise { const planSlug = getTeamPlanSlug(billingCycle) const response = await workspaceApi.subscribe(planSlug, { - returnUrl: `${getComfyPlatformBaseUrl()}/payment/success`, + returnUrl: paymentReturnUrl(), cancelUrl: `${getComfyPlatformBaseUrl()}/payment/failed`, teamCreditStopId }) diff --git a/src/platform/telemetry/types.ts b/src/platform/telemetry/types.ts index f565e342377..d9bf95b1cd6 100644 --- a/src/platform/telemetry/types.ts +++ b/src/platform/telemetry/types.ts @@ -734,6 +734,7 @@ type BillingFailureCategory = | 'provider_decline' | 'redirect' | 'poll_timeout' + | 'reconciliation_needed' | 'stale_operation' | 'rendering' | 'unknown' diff --git a/src/platform/workspace/api/workspaceApi.test.ts b/src/platform/workspace/api/workspaceApi.test.ts index ec8ac9b68af..8abb5ed9086 100644 --- a/src/platform/workspace/api/workspaceApi.test.ts +++ b/src/platform/workspace/api/workspaceApi.test.ts @@ -1,5 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { + BillingOpStatusResponse, + SavedPaymentMethod +} from './workspaceApi' + const { mockAxiosInstance, mockGetWorkspaceAuthHeaderOrThrow, @@ -439,6 +444,92 @@ describe('workspaceApi', () => { }) describe('subscription', () => { + it('listSavedPaymentMethods() returns masked methods from GET', async () => { + const data: SavedPaymentMethod[] = [ + { + type: 'card', + id: 'pm_saved', + brand: 'visa', + last4: '4242', + is_default: true + } + ] + mockAxiosInstance.get.mockResolvedValue({ data }) + + const result = await workspaceApi.listSavedPaymentMethods() + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/api/billing/payment-methods', + { headers: AUTH_HEADER } + ) + expect(result).toEqual(data) + }) + + it('previewSubscribe() sends the promotion code only when applied', async () => { + mockAxiosInstance.post.mockResolvedValue({ data: { allowed: true } }) + + await workspaceApi.previewSubscribe('pro-monthly', { + promotionCode: 'SAVE20' + }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/api/billing/preview-subscribe', + expect.objectContaining({ promotion_code: 'SAVE20' }), + { headers: AUTH_HEADER } + ) + }) + + it('subscribe() echoes the quote and selected saved method', async () => { + mockAxiosInstance.post.mockResolvedValue({ + data: { billing_op_id: 'op-quote', status: 'subscribed' } + }) + + await workspaceApi.subscribe('pro-monthly', { + promotionCode: 'SAVE20', + quoteId: 'quote_123', + quoteVersion: 2, + savedPaymentMethodId: 'pm_saved' + }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/api/billing/subscribe', + expect.objectContaining({ + promotion_code: 'SAVE20', + quote_id: 'quote_123', + quote_version: 2, + saved_payment_method_id: 'pm_saved' + }), + { headers: AUTH_HEADER } + ) + }) + + it('subscribe() omits a promotion code when none is applied', async () => { + mockAxiosInstance.post.mockResolvedValue({ + data: { billing_op_id: 'op-no-promo', status: 'subscribed' } + }) + + await workspaceApi.subscribe('pro-monthly') + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/api/billing/subscribe', + expect.objectContaining({ promotion_code: undefined }), + { headers: AUTH_HEADER } + ) + }) + + it('subscribe() rejects mutually exclusive payment credentials', async () => { + await expect( + workspaceApi.subscribe('pro-monthly', { + confirmationToken: 'ctoken_1', + savedPaymentMethodId: 'pm_saved' + }) + ).rejects.toThrow( + 'confirmationToken and savedPaymentMethodId are mutually exclusive' + ) + + expect(mockAxiosInstance.post).not.toHaveBeenCalled() + }) + it('previewSubscribe() sends POST with plan_slug', async () => { const data = { allowed: true, transition_type: 'new_subscription' } mockAxiosInstance.post.mockResolvedValue({ data }) @@ -458,6 +549,7 @@ describe('workspaceApi', () => { mockAxiosInstance.post.mockResolvedValue({ data }) const result = await workspaceApi.subscribe('pro-monthly', { + confirmationToken: 'ctoken_1', returnUrl: 'https://return.url', cancelUrl: 'https://cancel.url' }) @@ -466,6 +558,7 @@ describe('workspaceApi', () => { '/api/billing/subscribe', { plan_slug: 'pro-monthly', + confirmation_token: 'ctoken_1', return_url: 'https://return.url', cancel_url: 'https://cancel.url', team_credit_stop_id: undefined, @@ -489,6 +582,7 @@ describe('workspaceApi', () => { '/api/billing/subscribe', { plan_slug: 'team_per_credit_annual', + confirmation_token: undefined, return_url: undefined, cancel_url: undefined, team_credit_stop_id: 'team_700', @@ -609,9 +703,12 @@ describe('workspaceApi', () => { it('getBillingOpStatus() sends GET /billing/ops/:id', async () => { const data = { id: 'op-1', - status: 'succeeded', - started_at: '2026-01-01' - } + status: 'pending', + authentication_state: 'failed_retryable', + decline_reason: 'card_declined', + payment_intent_client_secret: 'pi_secret_current', + started_at: '2026-01-01T00:00:00Z' + } satisfies BillingOpStatusResponse mockAxiosInstance.get.mockResolvedValue({ data }) const result = await workspaceApi.getBillingOpStatus('op-1') diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index ad9f1cd2ac2..c18aad70910 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -25,6 +25,7 @@ import type { PreviewSubscribeResponse, ResubscribeRequest, ResubscribeResponse, + SavedPaymentMethod, SubscribeRequest, SubscribeResponse, SubscriptionDuration, @@ -90,6 +91,11 @@ interface PreviewSubscribeRequest extends GeneratedPreviewSubscribeRequest { } export interface SubscribeOptions { + confirmationToken?: string + promotionCode?: string + quoteId?: string + quoteVersion?: number + savedPaymentMethodId?: string returnUrl?: string cancelUrl?: string teamCreditStopId?: string @@ -101,6 +107,7 @@ export interface SubscribeOptions { export interface PreviewSubscribeOptions { teamCreditStopId?: string billingCycle?: SubscribeBillingCycle + promotionCode?: string } export type { SubscribeResponse } @@ -137,6 +144,13 @@ export type BillingStatusResponse = Omit< export type { BillingBalanceResponse } export type { CreateTopupResponse } export type { BillingOpStatusResponse } +export type { SavedPaymentMethod } +export type BillingAuthenticationState = NonNullable< + BillingOpStatusResponse['authentication_state'] +> +export type BillingDeclineReason = NonNullable< + BillingOpStatusResponse['decline_reason'] +> interface GetBillingEventsParams { page?: number @@ -463,6 +477,19 @@ export const workspaceApi = { } }, + async listSavedPaymentMethods(): Promise { + const headers = await getAuthHeaderOrThrow() + try { + const response = await workspaceApiClient.get( + workspaceApiUrl('/billing/payment-methods'), + { headers } + ) + return response.data + } catch (err) { + handleAxiosError(err) + } + }, + /** * Preview subscription change * POST /api/billing/preview-subscribe @@ -478,7 +505,8 @@ export const workspaceApi = { { plan_slug: planSlug, team_credit_stop_id: options.teamCreditStopId, - billing_cycle: options.billingCycle + billing_cycle: options.billingCycle, + promotion_code: options.promotionCode } satisfies PreviewSubscribeRequest, { headers } ) @@ -496,12 +524,22 @@ export const workspaceApi = { planSlug: string, options: SubscribeOptions = {} ): Promise { + if (options.confirmationToken && options.savedPaymentMethodId) { + throw new TypeError( + 'confirmationToken and savedPaymentMethodId are mutually exclusive' + ) + } const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.post( workspaceApiUrl('/billing/subscribe'), { plan_slug: planSlug, + confirmation_token: options.confirmationToken, + promotion_code: options.promotionCode, + quote_id: options.quoteId, + quote_version: options.quoteVersion, + saved_payment_method_id: options.savedPaymentMethodId, return_url: options.returnUrl, cancel_url: options.cancelUrl, team_credit_stop_id: options.teamCreditStopId, @@ -642,7 +680,7 @@ export const workspaceApi = { const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.get( - workspaceApiUrl(`/billing/ops/${opId}`), + workspaceApiUrl(`/billing/ops/${encodeURIComponent(opId)}`), { headers, timeout: 30_000 } ) return response.data diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 23a6323b7a1..df7c37044c8 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -98,20 +98,6 @@ vi.mock('@/platform/distribution/types', () => ({ } })) -const mockResumePendingPricingFlow = vi.fn() -vi.mock( - '@/platform/cloud/subscription/composables/useSubscriptionDialog', - () => ({ - useSubscriptionDialog: () => ({ - show: vi.fn(), - showPricingTable: vi.fn(), - hide: vi.fn(), - startTeamWorkspaceUpgradeFlow: vi.fn(), - resumePendingPricingFlow: mockResumePendingPricingFlow - }) - }) -) - describe('WorkspaceAuthGate', () => { beforeEach(() => { mockIsCloud.value = true @@ -309,19 +295,9 @@ describe('WorkspaceAuthGate', () => { expect(signal.aborted).toBe(true) expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() - expect(mockResumePendingPricingFlow).not.toHaveBeenCalled() expect(mockReportError).not.toHaveBeenCalled() }) - it('calls resumePendingPricingFlow after successful workspace init', async () => { - mockWorkspaceStoreInitState.value = 'ready' - - mountComponent() - await flushPromises() - - expect(mockResumePendingPricingFlow).toHaveBeenCalled() - }) - it('skips workspace init when store is already initialized', async () => { mockWorkspaceStoreInitState.value = 'ready' @@ -546,7 +522,6 @@ describe('WorkspaceAuthGate', () => { expect(retrySignal.aborted).toBe(true) expect(mockLogout).toHaveBeenCalledOnce() expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() - expect(mockResumePendingPricingFlow).not.toHaveBeenCalled() }) }) }) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index 21f14d8af48..1d8fdca44a9 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -71,7 +71,6 @@ import Button from '@/components/ui/button/Button.vue' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { isCloud } from '@/platform/distribution/types' -import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { remoteConfigErrorStatus, remoteConfigState @@ -90,7 +89,6 @@ const initializationState = ref< >(isCloud ? 'initializing' : 'ready') const initializationRetryable = ref(true) const errorPanel = useTemplateRef('errorPanel') -const subscriptionDialog = useSubscriptionDialog() let initializationGeneration = 0 let initializationController: AbortController | null = null let backgroundInitialization: Promise | null = null @@ -173,14 +171,6 @@ async function initialize(): Promise { throw new Error('Unified cloud auth was cleared during workspace setup') } - // Resume any pending pricing flow from team workspace creation - // Only safe after workspace store initialized successfully — the pricing - // dialog reads workspace state to decide which variant to show. - const workspaceStore = useTeamWorkspaceStore() - if (workspaceStore.initState === 'ready') { - subscriptionDialog.resumePendingPricingFlow() - } - if (generation === initializationGeneration) { initializationState.value = 'ready' } diff --git a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts index ac88a3e8222..80f9c23a1d6 100644 --- a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts +++ b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts @@ -22,6 +22,12 @@ function previewFixture( cost_next_period_cents: priceCents, credits_today_cents: 0, credits_next_period_cents: 0, + quote_id: 'quote_123', + quote_version: 1, + amount_due_cents: priceCents, + currency: 'usd', + renewal_amount_cents: priceCents, + renewal_at: '2027-06-19T00:00:00Z', new_plan: { slug: 'creator', tier: 'CREATOR', @@ -41,7 +47,8 @@ function previewFixture( vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key, - n: (value: number) => value.toLocaleString('en-US') + n: (value: number) => value.toLocaleString('en-US'), + locale: { value: 'en' } }) })) @@ -56,6 +63,114 @@ const globalOptions = { } describe('SubscriptionAddPaymentPreviewWorkspace', () => { + // Stripe Elements configure themselves once from the amount and currency, so + // mounting the selector before the quote lands leaves it permanently + // unusable. The team checkout renders its preview step while the quote is + // still in flight, which is how "payment options are unavailable" reached + // customers holding a perfectly good quote. + it('withholds the payment element until the quote is usable, then renders it', async () => { + let selectorInstances = 0 + const { rerender } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + teamPlan: { usd: 700, credits: 147_700, discountedUsd: 665 }, + usePaymentElement: true + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + UnifiedStripePaymentSelector: { + name: 'UnifiedStripePaymentSelector', + props: ['amountCents', 'currency'], + template: + '
{{ amountCents }}/{{ currency }}
', + setup() { + selectorInstances += 1 + } + } + } + } + }) + + expect(screen.queryByTestId('payment-selector')).toBeNull() + + await rerender({ previewData: previewFixture('MONTHLY', 66_500) }) + + expect(screen.getByTestId('payment-selector')).toHaveTextContent( + '66500/usd' + ) + expect(selectorInstances).toBe(1) + + await rerender({ + previewData: { + ...previewFixture('MONTHLY', 50_000), + quote_id: 'quote_456', + quote_version: 2 + } + }) + + expect(screen.getByTestId('payment-selector')).toHaveTextContent( + '50000/usd' + ) + expect(selectorInstances).toBe(2) + }) + + it('submits a zero-dollar quote without mounting Stripe Elements', async () => { + const quote = previewFixture('MONTHLY', 0) + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: quote, + usePaymentElement: true, + quoteIsCurrent: true + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + UnifiedStripePaymentSelector: { + template: '
' + } + } + } + }) + + expect(screen.queryByTestId('payment-selector')).toBeNull() + await userEvent.click( + screen.getByText('subscription.preview.payAndSubscribe') + ) + expect(emitted().addCreditCard).toBeTruthy() + }) + + it('falls back to subscription confirmation when quote identity is missing', async () => { + const quote = previewFixture('MONTHLY', 3500) + delete quote.quote_id + delete quote.quote_version + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: quote, + usePaymentElement: true, + quoteIsCurrent: true + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + UnifiedStripePaymentSelector: { + template: '
' + } + } + } + }) + + expect(screen.queryByTestId('payment-selector')).toBeNull() + await userEvent.click( + screen.getByText('subscription.preview.payAndSubscribe') + ) + expect(emitted().addCreditCard).toBeTruthy() + }) + it('renders personal tier price and credits from tierKey', () => { render(SubscriptionAddPaymentPreviewWorkspace, { props: { tierKey: 'creator' }, @@ -73,7 +188,7 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { expect(screen.getByText('subscription.teamPlan.name')).toBeTruthy() expect(screen.getByText('$380')).toBeTruthy() expect(screen.getAllByText('84,400').length).toBeGreaterThan(0) - expect(screen.getByText('$380.00')).toBeTruthy() + expect(screen.queryByText('$380.00')).toBeNull() }) it('shows the monthly-equivalent price and annual total for a yearly preview', () => { @@ -102,7 +217,7 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { }) expect(screen.getByText('$28')).toBeTruthy() expect(screen.getByText('subscription.billedYearly')).toBeTruthy() - expect(screen.getByText('$336.00')).toBeTruthy() + expect(screen.queryByText('$336.00')).toBeNull() }) it('omits the billed-yearly note for a monthly subscription', () => { @@ -135,12 +250,16 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { }) expect(screen.getByText('$380')).toBeTruthy() expect(screen.getByText('subscription.billedYearly')).toBeTruthy() - expect(screen.getByText('$4560.00')).toBeTruthy() + expect(screen.queryByText('$4,560.00')).toBeNull() }) it('emits addCreditCard from the team confirm CTA', async () => { const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { - props: { teamPlan: { usd: 400, credits: 84_400, discountedUsd: 380 } }, + props: { + teamPlan: { usd: 400, credits: 84_400, discountedUsd: 380 }, + previewData: previewFixture('MONTHLY', 38_000), + quoteIsCurrent: true + }, global: globalOptions }) await userEvent.click( @@ -149,6 +268,70 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { expect(emitted().addCreditCard).toBeTruthy() }) + it('invalidates while editing a promo and applies only on button click', async () => { + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: previewFixture('MONTHLY', 3500), + quoteIsCurrent: true, + embeddedCheckoutEnabled: true + }, + global: globalOptions + }) + const input = screen.getByPlaceholderText( + 'subscription.preview.promoCodePlaceholder' + ) + + await userEvent.type(input, 'SAVE20') + expect(emitted().invalidateQuote).toBeTruthy() + expect(emitted().applyPromotionCode).toBeUndefined() + + await userEvent.click( + screen.getByText('subscription.preview.applyPromoCode') + ) + expect(emitted().applyPromotionCode?.at(-1)).toEqual(['SAVE20']) + }) + + it('offers Add new payment method from the saved-method picker', async () => { + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: previewFixture('MONTHLY', 3500), + quoteIsCurrent: true, + embeddedCheckoutEnabled: true, + selectedSavedMethodId: 'pm_default', + savedMethods: [ + { + type: 'card', + id: 'pm_default', + brand: 'visa', + last4: '4242', + is_default: true + }, + { type: 'alipay', id: 'pm_alipay', is_default: false } + ] + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + SingleSelect: { + props: ['options'], + emits: ['update:modelValue'], + template: + '' + } + } + } + }) + + await userEvent.click( + screen.getByText('subscription.preview.addNewPaymentMethod') + ) + expect(emitted()['update:selectedSavedMethodId']).toEqual([[null]]) + expect(emitted().changePaymentMethod).toBeTruthy() + }) + it('opens verification only from its button without exposing the URL', async () => { const actionUrl = 'https://verify.example/sensitive-token' const open = vi.spyOn(window, 'open').mockReturnValue({} as Window) @@ -171,16 +354,53 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { ) }) - it('prevents leaving the preview while payment is pending', () => { + it('renders an explicit retry action after failed verification', async () => { + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + embeddedCheckoutEnabled: true, + authenticationState: 'failed_retryable', + authenticationError: 'Challenge was closed', + canRetryAuthentication: true + }, + global: globalOptions + }) + + expect(screen.getByRole('alert')).toHaveTextContent('Challenge was closed') + await userEvent.click( + screen.getByRole('button', { + name: 'billingOperation.retryVerification' + }) + ) + expect(emitted().retryAuthentication).toBeTruthy() + }) + + it('shows reconciliation support guidance with the operation id', () => { + render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + embeddedCheckoutEnabled: true, + reconciliationOperationId: 'op-reconcile-123' + }, + global: globalOptions + }) + + expect( + screen.getByText('billingOperation.reconciliationTitle') + ).toBeTruthy() + expect(screen.getByText('op-reconcile-123')).toBeTruthy() + }) + + it('does not render a back action on the payment confirmation', () => { render(SubscriptionAddPaymentPreviewWorkspace, { props: { tierKey: 'creator', isLoading: true }, global: globalOptions }) expect( - screen.getByRole('button', { + screen.queryByRole('button', { name: 'subscription.preview.backToAllPlans' }) - ).toBeDisabled() + ).toBeNull() }) }) diff --git a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue index b673bda0534..d9faffa26a3 100644 --- a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue +++ b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue @@ -1,21 +1,67 @@ diff --git a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts index 20384f42b54..b233b40d804 100644 --- a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts +++ b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts @@ -8,23 +8,38 @@ import SubscriptionRequiredDialogContentUnified from './SubscriptionRequiredDial const mockHandleSubscribeTeamClick = vi.fn() const mockHandleSubscribeClick = vi.fn() +const mockInvalidateQuote = vi.fn() const mockIsInPersonalWorkspace = ref(false) +const mockCheckoutStep = ref('pricing') +const mockPreviewVariant = ref(null) +const mockPreviewData = ref | null>(null) +const mockSelectedTeamStop = ref | null>(null) +const mockSelectedSavedPaymentMethodId = ref('pm_default') +const mockSavedPaymentMethods = ref[]>([]) vi.mock('@/platform/workspace/composables/useSubscriptionCheckout', () => ({ useSubscriptionCheckout: () => ({ - checkoutStep: ref('pricing'), + checkoutStep: mockCheckoutStep, isLoadingPreview: ref(false), loadingTier: ref(null), isSubscribing: ref(false), isResubscribing: ref(false), - previewData: ref(null), + previewData: mockPreviewData, + quoteIsCurrent: ref(false), + savedPaymentMethods: mockSavedPaymentMethods, + selectedSavedPaymentMethodId: mockSelectedSavedPaymentMethodId, selectedTierKey: ref(null), - selectedTeamStop: ref(null), + selectedTeamStop: mockSelectedTeamStop, selectedBillingCycle: ref('yearly'), activeCheckoutActionUrl: ref(null), + authenticationState: ref(null), + authenticationError: ref(null), + canRetryAuthentication: ref(false), + isAuthenticating: ref(false), + reconciliationOperationId: ref(null), isPolling: ref(false), isTeamCheckout: computed(() => false), - previewVariant: computed(() => null), + previewVariant: computed(() => mockPreviewVariant.value), handleSubscribeClick: mockHandleSubscribeClick, handleSubscribeTeamClick: mockHandleSubscribeTeamClick, handleBackToPricing: vi.fn(), @@ -32,6 +47,11 @@ vi.mock('@/platform/workspace/composables/useSubscriptionCheckout', () => ({ handleAddCreditCard: vi.fn(), handleConfirmTransition: vi.fn(), handleTeamSubscribe: vi.fn(), + handleSubscriptionPayment: vi.fn(), + handleTeamSubscriptionPayment: vi.fn(), + retryPaymentAuthentication: vi.fn(), + applyPromotionCode: vi.fn(), + invalidateQuote: mockInvalidateQuote, handleResubscribe: vi.fn() }) })) @@ -73,12 +93,27 @@ const UnifiedPricingTableStub = { function renderComponent(props: Record = {}) { return render(SubscriptionRequiredDialogContentUnified, { - props: { onClose: vi.fn(), ...props }, + props: { onClose: vi.fn(), embeddedCheckoutEnabled: true, ...props }, global: { plugins: [i18n], stubs: { UnifiedPricingTable: UnifiedPricingTableStub, - SubscriptionAddPaymentPreviewWorkspace: { template: '
' }, + SubscriptionAddPaymentPreviewWorkspace: { + name: 'SubscriptionAddPaymentPreviewWorkspace', + props: [ + 'previewData', + 'teamPlan', + 'savedMethods', + 'usePaymentElement' + ], + template: `
+ {{ previewData?.amount_due_cents ?? "no-quote" }} + {{ savedMethods.length }} + {{ usePaymentElement }} + + +
` + }, SubscriptionTransitionPreviewWorkspace: { template: '
' }, SubscriptionSuccessWorkspace: { template: '
' } } @@ -89,6 +124,68 @@ function renderComponent(props: Record = {}) { describe('SubscriptionRequiredDialogContentUnified team-plan subscribe', () => { beforeEach(() => { mockIsInPersonalWorkspace.value = false + mockCheckoutStep.value = 'pricing' + mockPreviewVariant.value = null + mockPreviewData.value = null + mockSelectedTeamStop.value = null + mockSelectedSavedPaymentMethodId.value = 'pm_default' + mockSavedPaymentMethods.value = [] + }) + + // The team checkout mounts the payment element against the quote's amount, so + // omitting preview-data left the element with nothing to charge and it + // refused to render — a served, correctly priced quote presented as + // "Payment options are unavailable". + it('hands the team checkout its quote so the payment element can mount', () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'team-new' + mockSelectedTeamStop.value = TEAM_PAYLOAD.stop + mockPreviewData.value = { amount_due_cents: 129_500, currency: 'usd' } + + renderComponent() + + expect(screen.getByTestId('add-payment-preview')).toHaveTextContent( + '129500' + ) + }) + + it('preserves the quote when the payment method changes', async () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'personal-new' + mockPreviewData.value = { amount_due_cents: 1600, currency: 'usd' } + renderComponent() + + await userEvent.click(screen.getByTestId('saved-method-btn')) + await userEvent.click(screen.getByTestId('new-method-btn')) + + expect(mockSelectedSavedPaymentMethodId.value).toBeNull() + expect(mockInvalidateQuote).not.toHaveBeenCalled() + }) + + it('collects a new method when none is selected', () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'personal-new' + mockPreviewData.value = { amount_due_cents: 1600, currency: 'usd' } + mockSavedPaymentMethods.value = [ + { id: 'pm_first', type: 'card', last4: '1111', is_default: false } + ] + mockSelectedSavedPaymentMethodId.value = null + + renderComponent() + + expect(screen.getByTestId('saved-method-count')).toHaveTextContent('0') + }) + + it('does not initialize the payment element while embedded checkout is off', () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'personal-new' + mockPreviewData.value = { amount_due_cents: 1600, currency: 'usd' } + + renderComponent({ embeddedCheckoutEnabled: false }) + + expect(screen.getByTestId('payment-element-enabled')).toHaveTextContent( + 'false' + ) }) it('advances to team checkout from a team workspace', async () => { diff --git a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue index e3587740cf8..bb75978af34 100644 --- a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue +++ b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue @@ -1,15 +1,39 @@ @@ -110,6 +201,7 @@ :team-plan="selectedTeamStop" :preview-data="previewData" :billing-cycle="selectedBillingCycle" + :dark-surface="isEmbeddedSuccessStep" @close="handleSuccessClose" />
@@ -118,7 +210,7 @@ diff --git a/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts b/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts index 276489812d0..8ee3e1cd46e 100644 --- a/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts +++ b/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts @@ -87,7 +87,7 @@ const i18n = createI18n({ function makePreview( overrides: Partial ): PreviewSubscribeResponse { - return { + const result: PreviewSubscribeResponse = { allowed: true, transition_type: 'upgrade', effective_at: '2026-08-01T00:00:00Z', @@ -123,14 +123,25 @@ function makePreview( }, ...overrides } + return { + ...result, + quote_id: 'quote_123', + quote_version: 1, + amount_due_cents: result.cost_today_cents, + currency: 'usd', + renewal_amount_cents: result.new_plan.price_cents, + renewal_at: result.new_plan.period_end ?? '2026-09-01T00:00:00Z', + ...overrides + } } function renderComponent( previewData: PreviewSubscribeResponse, - forceReactivation = false + forceReactivation = false, + quoteIsCurrent = true ) { return render(SubscriptionTransitionPreviewWorkspace, { - props: { previewData, forceReactivation }, + props: { previewData, forceReactivation, quoteIsCurrent }, global: { plugins: [i18n] } }) } @@ -534,6 +545,45 @@ describe('SubscriptionTransitionPreviewWorkspace reactivation disclosure', () => }) describe('confirm gating on load state', () => { + it('shows unavailable exact quote fields', () => { + mockSubscription.value = { isCancelled: false, endDate: null } + renderComponent( + makePreview({ + quote_id: undefined, + quote_version: undefined, + amount_due_cents: undefined, + currency: undefined, + renewal_amount_cents: undefined, + renewal_at: undefined + }) + ) + + expect( + screen.getAllByText('subscription.preview.quoteUnavailable') + ).toHaveLength(2) + }) + + it('does not confirm without a current quote', async () => { + const user = userEvent.setup() + mockSubscription.value = { isCancelled: false, endDate: null } + const { emitted } = render(SubscriptionTransitionPreviewWorkspace, { + props: { + previewData: makePreview({}), + forceReactivation: false, + quoteIsCurrent: false, + embeddedCheckoutEnabled: true + }, + global: { plugins: [i18n] } + }) + const confirmButton = screen.getByRole('button', { + name: 'Confirm upgrade' + }) + + expect(confirmButton).toBeDisabled() + await user.click(confirmButton) + expect(emitted().confirm).toBeUndefined() + }) + it('disables confirm while subscription status has not loaded yet, even below the charge threshold', () => { mockSubscription.value = null renderComponent( diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index e507c0243c5..1fd55d4691c 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -14,6 +14,7 @@ const mockFetchStatus = vi.fn() const mockTopup = vi.fn<(amountCents: number) => Promise>() const mockStartOperation = vi.fn() +const mockRetryPaymentAuthentication = vi.fn() const mockShowSettings = vi.fn() const mockToastAdd = vi.fn() const mockCloseDialog = vi.fn() @@ -23,10 +24,21 @@ const mockPermissions = vi.hoisted(() => ({ ref: undefined as { value: { canTopUp: boolean } } | undefined })) const mockShouldUseWorkspaceBilling = vi.hoisted(() => ({ value: true })) + +interface MockTopupOperation { + opId: string + status: 'pending' | 'reconciliation_needed' + actionUrl: string | null + authenticationState?: string + errorMessage?: string | null + canRetryAuthentication?: boolean + isAuthenticating?: boolean +} + const mockBillingOperationState = vi.hoisted(() => ({ isAddingCredits: undefined as { value: boolean } | undefined, topupActionOperation: undefined as - | { value: { actionUrl: string } | undefined } + | { value: MockTopupOperation | undefined } | undefined })) @@ -51,7 +63,8 @@ vi.mock('@/platform/workspace/stores/billingOperationStore', async () => { get topupActionOperation() { return mockBillingOperationState.topupActionOperation?.value }, - startOperation: mockStartOperation + startOperation: mockStartOperation, + retryPaymentAuthentication: mockRetryPaymentAuthentication }) } }) @@ -149,6 +162,12 @@ const i18n = createI18n({ 'Your bank requires additional verification to complete this payment.', verifyTitle: 'Verify your payment' } + }, + billingOperation: { + authenticationFailedDetail: 'Verification failed.', + authenticationManagerRequired: 'Ask a workspace manager for help.', + retryVerification: 'Try verification again', + reconciliationDetail: 'Contact support with operation ID' } } } @@ -192,7 +211,7 @@ function setIsAddingCredits(isAddingCredits: boolean) { mockBillingOperationState.isAddingCredits.value = isAddingCredits } -function setTopupActionOperation(operation: { actionUrl: string } | undefined) { +function setTopupActionOperation(operation: MockTopupOperation | undefined) { if (!mockBillingOperationState.topupActionOperation) { throw new Error('Billing operation mock not initialized') } @@ -288,7 +307,11 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('reopens in verification without exposing the action URL', async () => { const actionUrl = 'https://verify.example/sensitive-token' const open = vi.spyOn(window, 'open').mockReturnValue({} as Window) - setTopupActionOperation({ actionUrl }) + setTopupActionOperation({ + opId: 'op-action', + status: 'pending', + actionUrl + }) const { container } = renderDialog() @@ -308,6 +331,11 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('reopens in verification while the action URL is loading', () => { setIsAddingCredits(true) + setTopupActionOperation({ + opId: 'op-loading', + status: 'pending', + actionUrl: null + }) renderDialog() @@ -320,11 +348,17 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('returns to amount selection when a reopened operation ends', async () => { setIsAddingCredits(true) + setTopupActionOperation({ + opId: 'op-loading', + status: 'pending', + actionUrl: null + }) renderDialog() expect(screen.getByText('Verify your payment')).toBeInTheDocument() setIsAddingCredits(false) + setTopupActionOperation(undefined) await nextTick() expect(screen.getByText('Select amount')).toBeInTheDocument() @@ -334,6 +368,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('hides topup verification after permission is revoked', () => { setCanTopUp(false) setTopupActionOperation({ + opId: 'op-action', + status: 'pending', actionUrl: 'https://verify.example/sensitive-token' }) @@ -344,6 +380,47 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ).not.toBeInTheDocument() }) + it('retries failed payment authentication', async () => { + renderDialog() + + setIsAddingCredits(true) + setTopupActionOperation({ + opId: 'op-retry', + status: 'pending', + actionUrl: null, + authenticationState: 'failed_retryable', + errorMessage: 'Your bank rejected the verification.', + canRetryAuthentication: true + }) + await nextTick() + + expect( + screen.getByText('Your bank rejected the verification.') + ).toBeInTheDocument() + await userEvent.click( + screen.getByRole('button', { name: 'Try verification again' }) + ) + expect(mockRetryPaymentAuthentication).toHaveBeenCalledWith('op-retry') + }) + + it('keeps a top-up locked when reconciliation needs support', () => { + setTopupActionOperation({ + opId: 'op-reconcile', + status: 'reconciliation_needed', + actionUrl: null + }) + + renderDialog() + + expect( + screen.getByText('Contact support with operation ID') + ).toBeInTheDocument() + expect(screen.getByText('op-reconcile')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Add credits' }) + ).not.toBeInTheDocument() + }) + it('locks pending payment actions and prevents duplicate top-ups', async () => { mockTopup.mockResolvedValue(topupResponse('pending')) @@ -356,7 +433,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled() expect(payButton).toBeDisabled() expect(mockStartOperation).toHaveBeenCalledWith('op-1', 'topup', { - attemptStartedAt: expect.any(Number) + attemptStartedAt: expect.any(Number), + autoHandleRequiresAction: true }) payButton.dispatchEvent(new MouseEvent('click', { bubbles: true })) @@ -448,7 +526,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) expect(mockStartOperation).toHaveBeenCalledWith('op-1', 'topup', { - attemptStartedAt: expect.any(Number) + attemptStartedAt: expect.any(Number), + autoHandleRequiresAction: true }) expect(mockFetchBalance).not.toHaveBeenCalled() expect(mockFetchStatus).not.toHaveBeenCalled() diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue index 9f358a79bf4..606a2612cb7 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue @@ -82,8 +82,18 @@ {{ $t('credits.topUp.verifyTitle') }}

- {{ $t('credits.topUp.verifyBody') }} + {{ + topupReconciliationOperationId + ? $t('billingOperation.reconciliationDetail') + : topupAuthenticationError || $t('credits.topUp.verifyBody') + }}

+ + {{ topupReconciliationOperationId }} +
@@ -188,6 +198,18 @@
+