diff --git a/browser_tests/fixtures/ComfyPage.ts b/browser_tests/fixtures/ComfyPage.ts index 8b2d86a8e65..2ce4619969e 100644 --- a/browser_tests/fixtures/ComfyPage.ts +++ b/browser_tests/fixtures/ComfyPage.ts @@ -15,10 +15,6 @@ import { PERSONAL_BILLING_STATUS } from '@e2e/fixtures/data/cloudWorkspace' import { createBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' -import { - UNSUBSCRIBED, - ZERO_BALANCE -} from '@e2e/fixtures/data/subscriptionFixtures' import { ComfyActionbar } from '@e2e/fixtures/components/Actionbar' import { ComfyTemplates } from '@e2e/fixtures/components/Templates' import { ComfyMouse } from '@e2e/fixtures/ComfyMouse' @@ -721,12 +717,6 @@ export const comfyPageFixture = base.extend<{ await context.route('**/api/billing/plans', (route) => route.fulfill({ json: EMPTY_BILLING_PLANS }) ) - await context.route('**/customers/cloud-subscription-status', (route) => - route.fulfill({ json: UNSUBSCRIBED }) - ) - await context.route('**/customers/balance', (route) => - route.fulfill({ json: ZERO_BALANCE }) - ) await mockWorkspace(context, workspace('personal', 'owner'), []) } if (testInfo.tags.includes('@cloud') || testInfo.tags.includes('@auth')) { diff --git a/browser_tests/fixtures/apiKeyAuthFixture.ts b/browser_tests/fixtures/apiKeyAuthFixture.ts index b4dc738a715..f03a8d19b69 100644 --- a/browser_tests/fixtures/apiKeyAuthFixture.ts +++ b/browser_tests/fixtures/apiKeyAuthFixture.ts @@ -56,33 +56,13 @@ const API_KEY_WORKSPACE_EVENT_ID = 'evt-api-key-workspace' * user, a stored `comfy_api_key`, and the cloud API resolving that key to a * single bound workspace. Mirrors the QA flow behind the 1.51 API-key billing * findings: workspace context, balance, and activity must all come from the - * key's workspace via `/api/workspaces/current` and `/api/billing/*`, never - * from the legacy user-scoped `/customers/*` rail. - * - * The fixture records any legacy-rail read so specs can assert the session - * never falls back to it. + * key's workspace via `/api/workspaces/current` and `/api/billing/*`. */ export const apiKeyAuthFixture = base.extend<{ comfyPage: ComfyPage - legacyBillingReads: string[] }>({ - legacyBillingReads: async ({ page }, use) => { - const reads: string[] = [] - await page.route('**/customers/balance', (route) => { - reads.push(route.request().url()) - return route.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) - }) - await page.route('**/customers/events**', (route) => { - reads.push(route.request().url()) - return route.fulfill( - jsonRoute({ events: [], page: 1, limit: 7, total: 0, totalPages: 0 }) - ) - }) - await use(reads) - }, - comfyPage: async ({ page, request, legacyBillingReads }, use, testInfo) => { + comfyPage: async ({ page, request }, use, testInfo) => { testInfo.setTimeout(45_000) - void legacyBillingReads const comfyPage = new ComfyPage(page, request) const userId = await comfyPage.setupUser( diff --git a/browser_tests/fixtures/helpers/SubscriptionHelper.ts b/browser_tests/fixtures/helpers/SubscriptionHelper.ts index bf740b42f99..e102badc1c1 100644 --- a/browser_tests/fixtures/helpers/SubscriptionHelper.ts +++ b/browser_tests/fixtures/helpers/SubscriptionHelper.ts @@ -122,40 +122,6 @@ export class SubscriptionHelper { } this.routeHandlers.push({ pattern: statusPattern, handler: statusHandler }) await this.page.route(statusPattern, statusHandler) - - const balancePattern = '**/customers/balance' - const balanceHandler = async (route: Route) => { - await route.fulfill({ json: this.balanceResponse }) - } - this.routeHandlers.push({ - pattern: balancePattern, - handler: balanceHandler - }) - await this.page.route(balancePattern, balanceHandler) - - const checkoutPattern = '**/customers/cloud-subscription-checkout**' - const checkoutHandler = async (route: Route) => { - await route.fulfill({ - json: { checkout_url: 'https://checkout.stripe.com/mock' } - }) - } - this.routeHandlers.push({ - pattern: checkoutPattern, - handler: checkoutHandler - }) - await this.page.route(checkoutPattern, checkoutHandler) - - const billingPortalPattern = '**/customers/billing' - const billingPortalHandler = async (route: Route) => { - await route.fulfill({ - json: { billing_portal_url: 'https://billing.example/portal' } - }) - } - this.routeHandlers.push({ - pattern: billingPortalPattern, - handler: billingPortalHandler - }) - await this.page.route(billingPortalPattern, billingPortalHandler) } configure(...operators: SubscriptionOperator[]): void { diff --git a/browser_tests/fixtures/utils/cloudBillingMocks.ts b/browser_tests/fixtures/utils/cloudBillingMocks.ts index 33b22b371c2..c7116bc0dd1 100644 --- a/browser_tests/fixtures/utils/cloudBillingMocks.ts +++ b/browser_tests/fixtures/utils/cloudBillingMocks.ts @@ -60,7 +60,4 @@ export async function mockBilling( await page.route('**/api/billing/plans', (r) => r.fulfill(jsonRoute({ plans: [] })) ) - await page.route('**/customers/balance', (r) => - r.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) - ) } diff --git a/browser_tests/fixtures/utils/liveCloudBillingPolicy.test.ts b/browser_tests/fixtures/utils/liveCloudBillingPolicy.test.ts index 71c5cdbe9d9..d055cf38ec4 100644 --- a/browser_tests/fixtures/utils/liveCloudBillingPolicy.test.ts +++ b/browser_tests/fixtures/utils/liveCloudBillingPolicy.test.ts @@ -25,7 +25,6 @@ describe('live Cloud mutation policy', () => { { method: 'POST', path: '/api/auth/session', allowed: true }, { method: 'POST', path: '/api/billing/subscribe', allowed: false }, { method: 'POST', path: '/api/billing/payment-portal', allowed: false }, - { method: 'POST', path: '/customers/credit', allowed: false }, { method: 'DELETE', path: '/customers', allowed: false }, { method: 'PATCH', path: '/api/billing/payment-methods', allowed: false }, { method: 'PUT', path: '/api/billing/subscription', allowed: false }, diff --git a/browser_tests/tests/billing/cloudCreditsLockedRefusal.spec.ts b/browser_tests/tests/billing/cloudCreditsLockedRefusal.spec.ts index e308c0d1303..fc720012cf7 100644 --- a/browser_tests/tests/billing/cloudCreditsLockedRefusal.spec.ts +++ b/browser_tests/tests/billing/cloudCreditsLockedRefusal.spec.ts @@ -57,9 +57,6 @@ test.describe('Run refused for locked credits', { tag: '@cloud' }, () => { await page.route('**/api/features', (route) => route.fulfill(jsonRoute({ subscription_required: true })) ) - await page.route('**/customers/balance', (route) => - route.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) - ) }) test( diff --git a/browser_tests/tests/currentUserPopoverCredits.spec.ts b/browser_tests/tests/currentUserPopoverCredits.spec.ts index 05872af8551..6a5dd00da35 100644 --- a/browser_tests/tests/currentUserPopoverCredits.spec.ts +++ b/browser_tests/tests/currentUserPopoverCredits.spec.ts @@ -107,14 +107,6 @@ const test = comfyPageFixture.extend({ route.fulfill({ status: 204 }) ) - await page.route('**/customers/balance', (route) => - route.fulfill({ - status: 200, - contentType: 'application/json', - body: JSON.stringify(mockBalance) - }) - ) - // The popover sources its data from the workspace billing endpoints. await page.route('**/api/billing/capabilities', (route) => { if (route.request().method() !== 'GET') return route.fallback() diff --git a/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts b/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts index 07e56ff89bd..e50968ff2e1 100644 --- a/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts +++ b/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts @@ -104,9 +104,6 @@ async function setupRefusedPlanChange(page: Page, portalUrl: string) { await page.route('**/api/billing/balance', (r) => r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) ) - await page.route('**/customers/balance', (r) => - r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) - ) await page.route('**/api/billing/capabilities', (r) => { if (r.request().method() !== 'GET') return r.fallback() return r.fulfill(jsonRoute(createWorkspaceBillingCapabilities(PERSONAL))) diff --git a/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts b/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts index 443532bd05d..48fd2e4bc47 100644 --- a/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts +++ b/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts @@ -252,9 +252,6 @@ async function setupParity( routes.balanceRequests.push(route.request()) return route.fulfill(jsonRoute(balance(server.balanceMicros))) }) - await page.route('**/customers/balance', (route) => - route.fulfill(jsonRoute(balance(server.balanceMicros))) - ) await page.route('**/api/billing/plans', (route) => route.fulfill(jsonRoute(PLAN_CATALOG)) ) diff --git a/browser_tests/tests/dialogs/billingReadsSdkRail.spec.ts b/browser_tests/tests/dialogs/billingReadsSdkRail.spec.ts index d607f20e712..cd33155df9b 100644 --- a/browser_tests/tests/dialogs/billingReadsSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/billingReadsSdkRail.spec.ts @@ -239,7 +239,6 @@ async function mockCloudBoot( eventPages.push(requested) return r.fulfill(jsonRoute(eventsPage(Number(requested ?? 1)))) }) - await page.route('**/customers/balance', (r) => r.fulfill(jsonRoute(BALANCE))) return { reads, eventPages } } diff --git a/browser_tests/tests/dialogs/billingSessionSdkRail.spec.ts b/browser_tests/tests/dialogs/billingSessionSdkRail.spec.ts index 9e46a0f1951..0d43f122acb 100644 --- a/browser_tests/tests/dialogs/billingSessionSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/billingSessionSdkRail.spec.ts @@ -91,9 +91,6 @@ const PENDING_TOPUP = { started_at: '2026-09-20T00:00:00Z' } satisfies BillingOpStatusResponse -/** The legacy personal balance read, which a rail-on load must not issue. */ -const LEGACY_BALANCE_ROUTE = '/customers/balance' - interface BillingServer { status: BillingStatusResponse balance: BillingBalanceResponse @@ -145,7 +142,6 @@ async function bootWithRailsOn( return route.fulfill(jsonRoute(server.balance)) } await page.route('**/api/billing/balance', answerBalance) - await page.route(`**${LEGACY_BALANCE_ROUTE}`, answerBalance) await page.route( `**/api/billing/ops/${PENDING_OPERATION_ID}`, async (route) => { @@ -330,7 +326,6 @@ test.describe('Billing SDK rails across a session', { tag: '@cloud' }, () => { ]) ).toEqual(['fetch', 'fetch']) expect(transports(wire.reads)).not.toContain('xhr') - expect(readsOf(wire.reads, LEGACY_BALANCE_ROUTE)).toEqual([]) }) test('never shows the balance as 0 or blank across five reloads', async ({ diff --git a/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts b/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts index 1d5e6ff45f4..6a25527e976 100644 --- a/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts @@ -100,9 +100,6 @@ async function mockCloudBoot(page: Page): Promise { jsonRoute(createBillingCapabilities('ws-personal', { can_cancel: true })) ) ) - await page.route('**/customers/balance', (r) => - r.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) - ) await page.route('**/api/billing/subscription/cancel', async (r) => { requests.push(r.request()) diff --git a/browser_tests/tests/dialogs/creditsTile.spec.ts b/browser_tests/tests/dialogs/creditsTile.spec.ts index 7d1e0c58bdd..e46de5f4d97 100644 --- a/browser_tests/tests/dialogs/creditsTile.spec.ts +++ b/browser_tests/tests/dialogs/creditsTile.spec.ts @@ -43,8 +43,6 @@ const jsonRoute = (body: unknown) => ({ body: JSON.stringify(body) }) -// Legacy `/customers/balance` and workspace `/api/billing/balance` share the -// same response shape, so one body fulfills both endpoints. const balanceRoute = (balance: { amount: number monthly: number @@ -168,10 +166,6 @@ async function mockCloudBoot( ) ) - await page.route('**/customers/balance', (r) => - r.fulfill(balanceRoute(DEFAULT_BALANCE)) - ) - // Workspace billing (flag-on path) — a personal workspace now routes through // `/api/billing/*`. await page.route('**/api/billing/status', (r) => @@ -200,11 +194,7 @@ async function mockBalance( page: Page, balance: { amount: number; monthly: number; prepaid: number } ) { - await page.unroute('**/customers/balance') await page.unroute('**/api/billing/balance') - await page.route('**/customers/balance', (r) => - r.fulfill(balanceRoute(balance)) - ) await page.route('**/api/billing/balance', (r) => r.fulfill(balanceRoute(balance)) ) diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts index 8b526881f73..56852d0e028 100644 --- a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -132,9 +132,6 @@ async function mockCloudBoot(page: Page): Promise { await page.route('**/api/billing/balance', (r) => r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) ) - await page.route('**/customers/balance', (r) => - r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) - ) await page.route('**/api/billing/plans', (r) => r.fulfill(jsonRoute({ plans: [] })) ) diff --git a/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts b/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts index 465be92bc2d..be7b6e1ee9d 100644 --- a/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts @@ -173,14 +173,6 @@ async function mockCloudBoot( ) ) }) - await page.route('**/customers/balance', (r) => - r.fulfill( - jsonRoute({ - amount_micros: 0, - currency: 'usd' - } satisfies BillingBalanceResponse) - ) - ) // Both lifecycle routes answer POST only. A regression to GET would // otherwise be served the success fixture and pass every assertion below, diff --git a/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts b/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts index 187a5309f23..2ec0565171b 100644 --- a/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts +++ b/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts @@ -18,8 +18,7 @@ import { */ test.describe('API-key login billing surfaces', () => { test('shows the key workspace context, balance, and activity from the workspace rail', async ({ - comfyPage, - legacyBillingReads + comfyPage }) => { const page = comfyPage.page @@ -52,7 +51,5 @@ test.describe('API-key login billing surfaces', () => { .getByRole('button', { name: 'Activity' }) .click() await expect(settingsDialog.contentArea).toContainText('Credits Added') - - expect(legacyBillingReads).toEqual([]) }) }) diff --git a/docs/architecture/domains/boundaries.json b/docs/architecture/domains/boundaries.json index cfc49b7b3ec..f4d9a9597a8 100644 --- a/docs/architecture/domains/boundaries.json +++ b/docs/architecture/domains/boundaries.json @@ -710,6 +710,7 @@ "src/platform/billing/composables/deriveBillingBanner.test.ts", "src/platform/billing/composables/readOnRail.ts", "src/platform/billing/composables/readOnRail.test.ts", + "src/platform/billing/composables/readWorkspaceBillingEvents.ts", "src/platform/billing/composables/useBillingBanner.ts", "src/platform/billing/composables/useBillingBanner.test.ts", "src/platform/billing/composables/useBillingCapabilities.ts", @@ -736,9 +737,7 @@ "src/platform/billing/composables/useWorkspaceBilling.test.ts", "src/platform/billing/composables/useWorkspacePlanPricing.ts", "src/platform/billing/stores/billingOperationStore.ts", - "src/platform/billing/stores/billingOperationStore.test.ts", - "src/platform/billing/subscription/utils/subscriptionCheckoutUtil.ts", - "src/platform/billing/subscription/utils/subscriptionCheckoutUtil.test.ts" + "src/platform/billing/stores/billingOperationStore.test.ts" ] }, { @@ -750,7 +749,6 @@ "src/platform/billing/hostedBillingRoutes.ts", "src/platform/billing/hostedBillingRoutes.test.ts", "src/platform/billing/subscribeInput.ts", - "src/platform/billing/subscription/utils/checkoutAttributionLoader.ts", "src/platform/billing/subscription/utils/paymentReturnUrl.ts", "src/platform/billing/subscription/utils/paymentReturnUrl.test.ts", "src/platform/billing/subscription/utils/subscriptionCheckoutTracker.ts", @@ -1014,7 +1012,6 @@ "patterns": [ "src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue", "src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts", - "src/components/topbar/CloudBadge.vue", "src/platform/cloud/notification/components/**", "src/platform/cloud/oauth/OAuthConsentView.stories.ts", "src/platform/cloud/oauth/OAuthConsentView.vue", diff --git a/docs/architecture/domains/records/billing.domain.json b/docs/architecture/domains/records/billing.domain.json index 821ae80bc7b..73a8101ae52 100644 --- a/docs/architecture/domains/records/billing.domain.json +++ b/docs/architecture/domains/records/billing.domain.json @@ -227,6 +227,10 @@ "path": "src/platform/billing/composables/readOnRail.ts", "role": "application" }, + { + "path": "src/platform/billing/composables/readWorkspaceBillingEvents.ts", + "role": "application" + }, { "path": "src/platform/billing/composables/useBillingBanner.ts", "role": "application" @@ -311,10 +315,6 @@ "path": "src/platform/billing/subscription/utils/**", "role": "domain" }, - { - "path": "src/platform/billing/subscription/utils/checkoutAttributionLoader.ts", - "role": "infrastructure" - }, { "path": "src/platform/billing/subscription/utils/paymentReturnUrl.ts", "role": "infrastructure" @@ -323,10 +323,6 @@ "path": "src/platform/billing/subscription/utils/subscriptionCheckoutTracker.ts", "role": "infrastructure" }, - { - "path": "src/platform/billing/subscription/utils/subscriptionCheckoutUtil.ts", - "role": "application" - }, { "path": "src/platform/billing/utils/**", "role": "infrastructure" @@ -479,7 +475,6 @@ "src/platform/billing/subscription/constants/tierPricing.test.ts", "src/platform/billing/subscription/utils/subscriptionTierRank.test.ts", "src/platform/billing/subscription/utils/subscriptionCheckoutTracker.test.ts", - "src/platform/billing/subscription/utils/subscriptionCheckoutUtil.test.ts", "src/platform/billing/subscription/utils/retentionOffer.test.ts", "src/platform/billing/subscription/composables/useSubscription.test.ts", "src/platform/billing/subscription/launchCancellationFlow.test.ts", diff --git a/docs/architecture/domains/records/cloud.domain.json b/docs/architecture/domains/records/cloud.domain.json index 6083803a8e3..454cfb876ca 100644 --- a/docs/architecture/domains/records/cloud.domain.json +++ b/docs/architecture/domains/records/cloud.domain.json @@ -7,10 +7,6 @@ "path": "src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue", "role": "presentation" }, - { - "path": "src/components/topbar/CloudBadge.vue", - "role": "presentation" - }, { "path": "src/extensions/core/cloudBadges.ts", "role": "integration" diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 0cb18c7d35c..60ffa5491fc 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -151,7 +151,7 @@ }, "src/composables/auth/useAuthActions.ts": { "comfy/no-new-error-throw": { - "count": 3 + "count": 1 } }, "src/composables/canvas/useFocusNode.test.ts": { @@ -571,16 +571,6 @@ "count": 1 } }, - "src/platform/billing/subscription/components/CreditsTile.vue": { - "comfy/no-new-error-throw": { - "count": 1 - } - }, - "src/platform/billing/subscription/components/PricingTable.test.ts": { - "comfy/no-unread-hoisted-mock-state": { - "count": 1 - } - }, "src/platform/billing/subscription/composables/usePricingTableUrlLoader.test.ts": { "comfy/no-unread-hoisted-mock-state": { "count": 2 @@ -606,11 +596,6 @@ "count": 1 } }, - "src/platform/billing/subscription/utils/subscriptionCheckoutUtil.test.ts": { - "comfy/no-unread-hoisted-mock-state": { - "count": 2 - } - }, "src/platform/cloud/oauth/oauthApi.ts": { "comfy/no-new-error-throw": { "count": 8 diff --git a/src/components/topbar/CloudBadge.vue b/src/components/topbar/CloudBadge.vue deleted file mode 100644 index 2caef3d321c..00000000000 --- a/src/components/topbar/CloudBadge.vue +++ /dev/null @@ -1,34 +0,0 @@ - - - diff --git a/src/composables/auth/__mocks__/useAuthActions.ts b/src/composables/auth/__mocks__/useAuthActions.ts index 29aaaeeba63..c1105c7e13e 100644 --- a/src/composables/auth/__mocks__/useAuthActions.ts +++ b/src/composables/auth/__mocks__/useAuthActions.ts @@ -6,11 +6,6 @@ import type { useAuthActions as realUseAuthActions } from '@/composables/auth/us const actions: ReturnType = { logout: vi.fn(async () => undefined), sendPasswordReset: vi.fn(async () => true), - purchaseCredits: vi.fn(async () => undefined), - purchaseCreditsDirect: vi.fn(async () => undefined), - accessBillingPortal: vi.fn(async () => true), - accessBillingPortalDirect: vi.fn(async () => true), - fetchBalance: vi.fn(async () => null), signInWithGoogle: vi.fn(async () => undefined), signInWithGithub: vi.fn(async () => undefined), signInWithEmail: vi.fn(async () => undefined), diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index 9d02bf29c55..48304246df5 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -29,8 +29,6 @@ let mockWorkflowStore: ReturnType const mockToastErrorHandler = vi.hoisted(() => vi.fn()) -const mockStartPendingTopup = vi.hoisted(() => vi.fn()) -const mockClearPendingTopup = vi.hoisted(() => vi.fn()) const mockDistributionState = vi.hoisted(() => ({ isCloud: false, isDesktop: false @@ -74,16 +72,6 @@ vi.mock(import('@/platform/distribution/types'), () => ({ vi.mock(import('@comfyorg/telemetry')) -vi.mock( - import('@/platform/billing/composables/usePendingTopup'), - () => ({ - usePendingTopup: () => ({ - startPendingTopup: mockStartPendingTopup, - clearPendingTopup: mockClearPendingTopup - }) - }) -) - vi.mock(import('@/platform/workflow/persistence/base/storageIO'), () => ({ clearAllWorkspaceStorage: mockClearAllWorkspaceStorage, prepareWorkflowLogoutTransition: mockPrepareWorkflowLogoutTransition @@ -127,9 +115,6 @@ beforeEach(() => { stubFirebaseAuthHarness() mockAuthStore = useAuthStore() mockWorkflowStore = useWorkflowStore() - vi.mocked(mockAuthStore.initiateCreditPurchase).mockResolvedValue({ - checkout_url: 'https://checkout.stripe.test' - }) vi.mocked(mockAuthStore.logout).mockResolvedValue(undefined) vi.mocked(mockAuthStore.sendPasswordReset).mockResolvedValue(undefined) const credential = fromPartial({ user: { uid: 'test-user' } }) @@ -140,81 +125,6 @@ beforeEach(() => { mockDistributionState.isDesktop = false }) -describe('useAuthActions.accessBillingPortalDirect', () => { - it('rejects without opening a tab when no billing portal URL is returned', async () => { - const open = vi.spyOn(window, 'open').mockImplementation(() => window) - vi.mocked(mockAuthStore.accessBillingPortal).mockResolvedValueOnce( - fromPartial({}) - ) - const { accessBillingPortalDirect } = useAuthActions() - - await expect(accessBillingPortalDirect()).rejects.toThrow( - 'toastMessages.failedToAccessBillingPortal:No billing portal URL returned' - ) - - expect(open).not.toHaveBeenCalled() - }) -}) - -describe('useAuthActions.purchaseCreditsDirect', () => { - it('starts top-up tracking before opening Stripe checkout', async () => { - const open = vi.spyOn(window, 'open').mockImplementation(() => window) - const { purchaseCreditsDirect } = useAuthActions() - - await purchaseCreditsDirect(25) - - expect(mockStartPendingTopup).toHaveBeenCalledOnce() - expect(open).toHaveBeenCalledWith('https://checkout.stripe.test', '_blank') - expect(mockStartPendingTopup.mock.invocationCallOrder[0]).toBeLessThan( - open.mock.invocationCallOrder[0] - ) - }) - - it('does not start tracking or open checkout when no checkout URL is returned', async () => { - const open = vi.spyOn(window, 'open').mockImplementation(() => null) - vi.mocked(mockAuthStore.initiateCreditPurchase).mockResolvedValueOnce({}) - const { purchaseCreditsDirect } = useAuthActions() - - await expect(purchaseCreditsDirect(25)).rejects.toThrow() - - expect(mockStartPendingTopup).not.toHaveBeenCalled() - expect(open).not.toHaveBeenCalled() - }) - - it('does not start tracking or open checkout when the purchase request rejects', async () => { - const open = vi.spyOn(window, 'open').mockImplementation(() => null) - vi.mocked(mockAuthStore.initiateCreditPurchase).mockRejectedValueOnce( - new Error('network down') - ) - const { purchaseCreditsDirect } = useAuthActions() - - await expect(purchaseCreditsDirect(25)).rejects.toThrow('network down') - - expect(mockStartPendingTopup).not.toHaveBeenCalled() - expect(open).not.toHaveBeenCalled() - }) - - it('reports a blocked checkout popup on the web', async () => { - vi.spyOn(window, 'open').mockImplementation(() => null) - const { purchaseCreditsDirect } = useAuthActions() - - await expect(purchaseCreditsDirect(25)).rejects.toThrow() - - expect(mockClearPendingTopup).toHaveBeenCalledOnce() - }) - - it('keeps tracking the top-up when Desktop hands checkout to the system browser', async () => { - mockDistributionState.isDesktop = true - const open = vi.spyOn(window, 'open').mockImplementation(() => null) - const { purchaseCreditsDirect } = useAuthActions() - - await purchaseCreditsDirect(25) - - expect(open).toHaveBeenCalledWith('https://checkout.stripe.test', '_blank') - expect(mockClearPendingTopup).not.toHaveBeenCalled() - }) -}) - describe('useAuthActions.logout', () => { beforeEach(() => { mockDistributionState.isCloud = true diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index 863c95ffaab..26f0ed08462 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -11,8 +11,6 @@ import type { AuthErrorCopy } from '@comfyorg/account-core/firebaseAuthError' -import { watchForTopupBalanceUpdate } from '@/platform/billing/composables/topupBalanceRefresh' -import { refreshBilling } from '@/platform/billing/billingRefresh' import { useErrorHandling } from '@/composables/useErrorHandling' import { st, t } from '@/i18n' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -20,7 +18,6 @@ import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@comfyorg/telemetry' import type { AuthFlowAction } from '@comfyorg/telemetry/types' -import { PaymentPopupBlockedError } from '@/platform/telemetry/utils/billingFailureCategory' import { useToast } from '@/components/ui/toast/toastStore' import { clearAllWorkspaceStorage, @@ -28,15 +25,9 @@ import { } from '@/platform/workflow/persistence/base/storageIO' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' -import { usePendingTopup } from '@/platform/billing/composables/usePendingTopup' import { useDialogService } from '@/services/dialogService' import { SsoRequiredAuthError, useAuthStore } from '@/stores/authStore' -import type { - BillingPortalTargetTier, - SocialSignInOptions -} from '@/stores/authStore' -import { usdToMicros } from '@/utils/formatUtil' -import { openBillingUrl } from '@/platform/billing/billingTab' +import type { SocialSignInOptions } from '@/stores/authStore' /** * The app's own auth.errors table, read through vue-i18n at resolution time. @@ -197,71 +188,6 @@ export const useAuthActions = () => { reportAuthFlowError('password_reset') ) - /** - * Raw (unwrapped) credit purchase. Exposed separately from `purchaseCredits` - * so callers that need to observe a rejection directly (e.g. to fire failure - * telemetry) aren't routed through `wrapWithErrorHandlingAsync`, which - * resolves instead of re-throwing on failure. - */ - const purchaseCreditsDirect = async (amount: number): Promise => { - const response = await authStore.initiateCreditPurchase({ - amount_micros: usdToMicros(amount), - currency: 'usd' - }) - - if (!response.checkout_url) { - throw new Error( - t('toastMessages.failedToPurchaseCredits', { - error: 'No checkout URL returned' - }) - ) - } - - const pendingTopup = usePendingTopup() - pendingTopup.startPendingTopup() - if (!openBillingUrl(response.checkout_url)) { - pendingTopup.clearPendingTopup() - throw new PaymentPopupBlockedError( - t('subscription.preview.paymentPopupBlocked') - ) - } - watchForTopupBalanceUpdate({ - onBalanceIncreased: () => refreshBilling('account') - }) - } - - const purchaseCredits = wrapWithErrorHandlingAsync( - purchaseCreditsDirect, - reportError - ) - - /** Unwrapped `accessBillingPortal`: rejects on failure, false when the tab is blocked. */ - const accessBillingPortalDirect = async ( - targetTier?: BillingPortalTargetTier, - options?: { cancelSubscription?: boolean } - ): Promise => { - const response = await authStore.accessBillingPortal(targetTier, options) - if (!response.billing_portal_url) { - throw new Error( - t('toastMessages.failedToAccessBillingPortal', { - error: 'No billing portal URL returned' - }) - ) - } - return window.open(response.billing_portal_url, '_blank') !== null - } - - const accessBillingPortal = wrapWithErrorHandlingAsync( - accessBillingPortalDirect, - reportError - ) - - const fetchBalance = wrapWithErrorHandlingAsync(async () => { - const result = await authStore.fetchBalance() - // Top-up completion tracking happens in UsageLogsTable when events are fetched - return result - }, reportError) - const signInWithGoogle = async (options?: SocialSignInOptions) => await wrapWithErrorHandlingAsync( async () => await authStore.loginWithGoogle(options), @@ -295,11 +221,6 @@ export const useAuthActions = () => { return { logout, sendPasswordReset, - purchaseCredits, - purchaseCreditsDirect, - accessBillingPortal, - accessBillingPortalDirect, - fetchBalance, signInWithGoogle, signInWithGithub, signInWithEmail, diff --git a/src/locales/ar/main.json b/src/locales/ar/main.json index cac8a68896f..db0e5a15470 100644 --- a/src/locales/ar/main.json +++ b/src/locales/ar/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "قيد الاستخدام", "additionalCreditsInfo": "حول الرصيد الإضافي", "additionalCreditsTooltip": "أرصدة تضيفها إلى جانب خطتك. تُستخدم بعد نفاد أرصدة خطتك. تنتهي صلاحية كل منها بعد عام من الشراء.", - "benefits": { - "benefit1": "رصيد شهري للعقد الشريكة - تجديد عند الحاجة", - "benefit1FreeTier": "رصيد شهري أكثر، مع إمكانية الشحن في أي وقت", - "benefit2": "حتى 30 دقيقة وقت تشغيل لكل مهمة", - "benefit3": "استخدم نماذجك الخاصة (Creator & Pro)" - }, "beta": "نسخة تجريبية", "billedMonthly": "يتم الفوترة شهريًا", "billedYearly": "{total} يتم الفوترة سنويًا", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "تم استهلاك الرصيد الشهري", "monthlyUsageProgress": "{used} من {total} من الرصيد الشهري مستخدم", "mostPopular": "الأكثر شيوعًا", - "needTeamWorkspace": "هل تحتاج إلى مساحة عمل للفريق؟", "nextBillingCycle": "دورة الفوترة التالية", "outOfCreditsDescription": "أضف المزيد من الرصيد للمتابعة في التوليد.", "outOfCreditsTitle": "نفد رصيدك. سيتم إعادة التعبئة {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "تم تفعيل الاشتراك بنجاح!", "pollingTimeout": "انتهت مهلة انتظار الاشتراك. يرجى التحديث والمحاولة مرة أخرى.", "subscribe": "اشتراك", - "title": "الاشتراك في", "waitingForSubscription": "أكمل اشتراكك في علامة التبويب الجديدة. سنكتشف تلقائيًا عند الانتهاء!" }, "resubscribe": "إعادة الاشتراك", @@ -5229,7 +5221,6 @@ "saveYearly": "وفّر 20%", "saveYearlyUpTo": "وفر حتى ٢٠٪", "scheduledChangeNotice": "تتغير خطتك إلى {plan} في {date}.", - "soloUseOnly": "للاستخدام الفردي فقط", "subscribe": "اشترك", "subscribeFailed": "فشل الاشتراك", "subscribeForMore": "ترقية", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "هذه مساحة العمل ليست مشتركة", "yearly": "سنوي", "yearlyCredits": "أرصدة سنويًا", - "yearlyCreditsLabel": "إجمالي الرصيد السنوي", "yearlyCreditsPerMemberLabel": "الأرصدة السنوية / العضو", "yearlyCreditsUsedUpTitle": "نفدت الأرصدة السنوية. تُجدَّد في {date}", "yearlyCreditsUsedUpTitleNoDate": "نفدت الأرصدة السنوية", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "فشل في تحويل العناصر إلى مخطط فرعي", "failedToCreateCustomer": "فشل في إنشاء العميل: {error}", "failedToExportModel": "فشل في تصدير النموذج بصيغة {format}", - "failedToFetchBalance": "فشل في جلب الرصيد: {error}", "failedToFetchLogs": "فشل في جلب سجلات الخادم", "failedToFetchSubscription": "فشل في جلب حالة الاشتراك: {error}", "failedToInitializeCameraAngleViewer": "تعذّر تهيئة عارض زاوية الكاميرا. حاول إعادة تحميل الصفحة.", "failedToInitializeCameraInfoViewer": "تعذّر تهيئة عارض معلومات الكاميرا. حاول إعادة تحميل الصفحة.", "failedToInitializeLightInfoViewer": "فشلت تهيئة عارض معلومات الإضاءة. حاول إعادة تحميل الصفحة.", "failedToInitializeLoad3dViewer": "فشل في تهيئة عارض ثلاثي الأبعاد", - "failedToInitiateCreditPurchase": "فشل في بدء شراء الرصيد: {error}", - "failedToInitiateSubscription": "فشل في بدء الاشتراك: {error}", "failedToLoadBackgroundImage": "فشل في تحميل صورة الخلفية", "failedToLoadHDRI": "فشل في تحميل ملف HDRI", "failedToLoadModel": "فشل في تحميل النموذج ثلاثي الأبعاد", - "failedToPurchaseCredits": "فشل في شراء الرصيد: {error}", "failedToQueue": "فشل في الإضافة إلى قائمة الانتظار", "failedToRegisterSubgraph": "فشل تسجيل الرسم البياني الفرعي", "failedToSaveDraft": "فشل في حفظ مسودة سير العمل", diff --git a/src/locales/de/main.json b/src/locales/de/main.json index 4d78aaa5c4b..09200187a2f 100644 --- a/src/locales/de/main.json +++ b/src/locales/de/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "In Verwendung", "additionalCreditsInfo": "Über zusätzliche Credits", "additionalCreditsTooltip": "Credits, die Sie zusätzlich zu Ihrem Plan hinzufügen. Sie werden verwendet, nachdem Ihre Plan-Credits aufgebraucht sind. Jeder verfällt ein Jahr nach dem Kauf.", - "benefits": { - "benefit1": "Monatliche Credits für Partner-Nodes — bei Bedarf aufladen", - "benefit1FreeTier": "Monatliche Credits, jederzeit aufladen", - "benefit2": "Bis zu 1 Stunde Laufzeit pro Job mit Pro", - "benefit3": "Eigene Modelle verwenden (Creator & Pro)" - }, "beta": "BETA", "billedMonthly": "Monatliche Abrechnung", "billedYearly": "{total} jährliche Abrechnung", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Monatliche Credits sind aufgebraucht", "monthlyUsageProgress": "{used} von {total} monatlichen Credits verwendet", "mostPopular": "Am beliebtesten", - "needTeamWorkspace": "Benötigen Sie einen Team-Workspace?", "nextBillingCycle": "nächster Abrechnungszeitraum", "outOfCreditsDescription": "Fügen Sie weitere Credits hinzu, um die Generierung fortzusetzen.", "outOfCreditsTitle": "Ihre Credits sind aufgebraucht. Credits werden am {date} aufgefüllt", @@ -5180,7 +5173,6 @@ "pollingSuccess": "Abonnement erfolgreich aktiviert!", "pollingTimeout": "Zeitüberschreitung beim Warten auf das Abonnement. Bitte aktualisieren Sie die Seite und versuchen Sie es erneut.", "subscribe": "Abonnieren", - "title": "Abonnieren Sie", "waitingForSubscription": "Schließen Sie Ihr Abonnement im neuen Tab ab. Wir erkennen automatisch, wenn Sie fertig sind!" }, "resubscribe": "Erneut abonnieren", @@ -5229,7 +5221,6 @@ "saveYearly": "20 % sparen", "saveYearlyUpTo": "Bis zu 20 % sparen", "scheduledChangeNotice": "Ihr Tarif wechselt am {date} zu {plan}.", - "soloUseOnly": "Nur für Einzelnutzung", "subscribe": "Abonnieren", "subscribeFailed": "Abonnement konnte nicht abgeschlossen werden", "subscribeForMore": "Upgraden", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Dieser Workspace hat kein Abonnement", "yearly": "Jährlich", "yearlyCredits": "Credits pro Jahr", - "yearlyCreditsLabel": "Jährliche Credits insgesamt", "yearlyCreditsPerMemberLabel": "Jährliche Credits / Mitglied", "yearlyCreditsUsedUpTitle": "Jährliche Credits sind aufgebraucht. Werden am {date} aufgefüllt", "yearlyCreditsUsedUpTitleNoDate": "Jährliche Credits sind aufgebraucht", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "Elemente konnten nicht in einen Subgraph konvertiert werden", "failedToCreateCustomer": "Kunde konnte nicht erstellt werden: {error}", "failedToExportModel": "Export des Modells als {format} fehlgeschlagen", - "failedToFetchBalance": "Guthaben konnte nicht abgerufen werden: {error}", "failedToFetchLogs": "Serverprotokolle konnten nicht abgerufen werden", "failedToFetchSubscription": "Abonnementstatus konnte nicht abgerufen werden: {error}", "failedToInitializeCameraAngleViewer": "Der Kamerawinkel-Viewer konnte nicht initialisiert werden. Versuchen Sie, die Seite neu zu laden.", "failedToInitializeCameraInfoViewer": "Camera-Info-Viewer konnte nicht initialisiert werden. Versuchen Sie, die Seite neu zu laden.", "failedToInitializeLightInfoViewer": "Light-Info-Viewer konnte nicht initialisiert werden. Versuchen Sie, die Seite neu zu laden.", "failedToInitializeLoad3dViewer": "3D-Viewer konnte nicht initialisiert werden", - "failedToInitiateCreditPurchase": "Credit-Kauf konnte nicht gestartet werden: {error}", - "failedToInitiateSubscription": "Abonnement konnte nicht gestartet werden: {error}", "failedToLoadBackgroundImage": "Hintergrundbild konnte nicht geladen werden", "failedToLoadHDRI": "HDRI-Datei konnte nicht geladen werden", "failedToLoadModel": "3D-Modell konnte nicht geladen werden", - "failedToPurchaseCredits": "Credits konnten nicht gekauft werden: {error}", "failedToQueue": "Hinzufügen zur Queue fehlgeschlagen", "failedToRegisterSubgraph": "Subgraph konnte nicht registriert werden", "failedToSaveDraft": "Workflow-Entwurf konnte nicht gespeichert werden", diff --git a/src/locales/en/main.json b/src/locales/en/main.json index ab1a0f851ce..24bcfdbeba7 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2662,15 +2662,11 @@ "migrateToLitegraphReroute": "Reroute nodes will be removed in future versions. Click to migrate to litegraph-native reroute.", "legacyMaskEditorDeprecated": "The legacy mask editor is deprecated and will be removed soon.", "userNotAuthenticated": "User not authenticated", - "failedToFetchBalance": "Failed to fetch balance: {error}", "noPersonalWorkspace": "This account has no personal billing. Manage billing from your team workspace.", "failedToCreateCustomer": "Failed to create customer: {error}", - "failedToInitiateCreditPurchase": "Failed to initiate credit purchase: {error}", "failedToAccessBillingPortal": "Failed to access billing portal: {error}", "invalidBillingPortalUrl": "Invalid portal URL", - "failedToPurchaseCredits": "Failed to purchase credits: {error}", "failedToFetchSubscription": "Failed to fetch subscription status: {error}", - "failedToInitiateSubscription": "Failed to initiate subscription: {error}", "unauthorizedDomain": "Your domain {domain} is not authorized to use this service. Please contact {email} to add your domain to the whitelist.", "useApiKeyTip": "Tip: Can't access normal login? Use the Comfy API Key option.", "nothingSelected": "Nothing selected", @@ -3144,8 +3140,6 @@ "plansForWorkspace": "Plans for {workspace}", "personalWorkspace": "Personal Workspace", "teamWorkspace": "Team Workspace", - "soloUseOnly": "Solo use only", - "needTeamWorkspace": "Need team workspace?", "inviteUpTo": "Invite up to", "title": "Subscription", "titleUnsubscribed": "Subscribe to Comfy Cloud", @@ -3314,12 +3308,6 @@ "invoiceHistory": "Invoice history", "fullUsageActivity": "Full usage activity", "refreshCredits": "Refresh credits", - "benefits": { - "benefit1": "Monthly credits for Partner Nodes — top up when needed", - "benefit1FreeTier": "Monthly credits, top up anytime", - "benefit2": "Up to 1 hour runtime per job on Pro", - "benefit3": "Bring your own models (Creator & Pro)" - }, "tiers": { "free": { "name": "Free" @@ -3345,7 +3333,6 @@ } }, "required": { - "title": "Subscribe to", "waitingForSubscription": "Complete your subscription in the new tab. We'll automatically detect when you're done!", "subscribe": "Subscribe", "pollingSuccess": "Subscription activated successfully!", @@ -3446,7 +3433,6 @@ "monthlyCreditsPerMemberLabel": "Monthly credits / member", "yearlyCreditsPerMemberLabel": "Yearly credits / member", "maxMembersLabel": "Max. members", - "yearlyCreditsLabel": "Total yearly credits", "memberCount": "{count} member | {count} members", "maxDurationLabel": "Max run duration", "gpuLabel": "RTX 6000 Pro (96GB VRAM)", diff --git a/src/locales/es/main.json b/src/locales/es/main.json index 9eb00f88a96..3f1c6a5a1dc 100644 --- a/src/locales/es/main.json +++ b/src/locales/es/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "En uso", "additionalCreditsInfo": "Acerca de los créditos adicionales", "additionalCreditsTooltip": "Créditos que añada además de su plan. Se usan después de que se agoten los créditos de su plan. Cada uno caduca un año después de la compra.", - "benefits": { - "benefit1": "Créditos mensuales para Nodos de Socio — recarga cuando sea necesario", - "benefit1FreeTier": "Más créditos mensuales, recarga en cualquier momento", - "benefit2": "Hasta 30 min de tiempo de ejecución por trabajo", - "benefit3": "Usa tus propios modelos (Creator & Pro)" - }, "beta": "BETA", "billedMonthly": "Facturado mensualmente", "billedYearly": "{total} facturado anualmente", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Los créditos mensuales se han agotado", "monthlyUsageProgress": "{used} de {total} créditos mensuales usados", "mostPopular": "Más popular", - "needTeamWorkspace": "¿Necesitas un espacio de trabajo en equipo?", "nextBillingCycle": "próximo ciclo de facturación", "outOfCreditsDescription": "Agrega más créditos para continuar generando.", "outOfCreditsTitle": "Te has quedado sin créditos. Recarga de créditos {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "¡Suscripción activada correctamente!", "pollingTimeout": "Tiempo de espera agotado para la suscripción. Por favor, actualiza e inténtalo de nuevo.", "subscribe": "Suscribirse", - "title": "Suscribirse a", "waitingForSubscription": "Completa tu suscripción en la nueva pestaña. ¡Detectaremos automáticamente cuando hayas terminado!" }, "resubscribe": "Volver a suscribirse", @@ -5229,7 +5221,6 @@ "saveYearly": "Ahorra 20%", "saveYearlyUpTo": "Ahorra hasta un 20%", "scheduledChangeNotice": "Tu plan cambia a {plan} el {date}.", - "soloUseOnly": "Solo para uso individual", "subscribe": "Suscribirse", "subscribeFailed": "No se pudo suscribir", "subscribeForMore": "Mejorar", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Este espacio de trabajo no tiene una suscripción", "yearly": "Anual", "yearlyCredits": "créditos por año", - "yearlyCreditsLabel": "Total de créditos anuales", "yearlyCreditsPerMemberLabel": "Créditos anuales / miembro", "yearlyCreditsUsedUpTitle": "Los créditos anuales se han agotado. Se reponen el {date}", "yearlyCreditsUsedUpTitleNoDate": "Los créditos anuales se han agotado", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "No se pudo convertir los elementos en subgrafo", "failedToCreateCustomer": "No se pudo crear el cliente: {error}", "failedToExportModel": "Error al exportar modelo como {format}", - "failedToFetchBalance": "No se pudo obtener el saldo: {error}", "failedToFetchLogs": "Error al obtener los registros del servidor", "failedToFetchSubscription": "Error al obtener el estado de suscripción: {error}", "failedToInitializeCameraAngleViewer": "No se pudo inicializar el visor de ángulo de cámara. Intenta recargar la página.", "failedToInitializeCameraInfoViewer": "No se pudo inicializar el visor de información de la cámara. Intenta recargar la página.", "failedToInitializeLightInfoViewer": "No se pudo inicializar el visor de información de iluminación. Intenta recargar la página.", "failedToInitializeLoad3dViewer": "Error al inicializar el visor 3D", - "failedToInitiateCreditPurchase": "No se pudo iniciar la compra de créditos: {error}", - "failedToInitiateSubscription": "Error al iniciar la suscripción: {error}", "failedToLoadBackgroundImage": "Error al cargar la imagen de fondo", "failedToLoadHDRI": "No se pudo cargar el archivo HDRI", "failedToLoadModel": "Error al cargar el modelo 3D", - "failedToPurchaseCredits": "No se pudo comprar créditos: {error}", "failedToQueue": "Error al encolar", "failedToRegisterSubgraph": "No se pudo registrar el subgrafo", "failedToSaveDraft": "No se pudo guardar el borrador del flujo de trabajo", diff --git a/src/locales/fa/main.json b/src/locales/fa/main.json index 51c4c1d0189..e8e287ff0d0 100644 --- a/src/locales/fa/main.json +++ b/src/locales/fa/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "در حال استفاده", "additionalCreditsInfo": "درباره اعتبارهای اضافی", "additionalCreditsTooltip": "اعتبارهایی که علاوه بر طرح خود اضافه می‌کنید. پس از تمام شدن اعتبارهای طرح شما استفاده می‌شوند. هرکدام یک سال پس از خرید منقضی می‌شوند.", - "benefits": { - "benefit1": "۱۰ دلار اعتبار ماهانه برای Partner Nodes — در صورت نیاز شارژ کنید", - "benefit1FreeTier": "اعتبار ماهانه بیشتر، شارژ مجدد در هر زمان", - "benefit2": "تا ۳۰ دقیقه زمان اجرا برای هر کار", - "benefit3": "امکان استفاده از مدل‌های شخصی (Creator و Pro)" - }, "beta": "بتا", "billedMonthly": "صورتحساب ماهانه", "billedYearly": "{total} صورتحساب سالانه", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "اعتبار ماهانه تمام شده است", "monthlyUsageProgress": "{used} از {total} اعتبار ماهانه مصرف شده است", "mostPopular": "محبوب‌ترین", - "needTeamWorkspace": "به فضای کاری تیمی نیاز دارید؟", "nextBillingCycle": "چرخه صورتحساب بعدی", "outOfCreditsDescription": "برای ادامه تولید، اعتبار بیشتری اضافه کنید.", "outOfCreditsTitle": "اعتبار شما تمام شده است. شارژ مجدد در {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "اشتراک با موفقیت فعال شد!", "pollingTimeout": "زمان انتظار برای فعال‌سازی اشتراک به پایان رسید. لطفاً صفحه را تازه‌سازی و دوباره تلاش کنید.", "subscribe": "اشتراک", - "title": "اشتراک در", "waitingForSubscription": "اشتراک خود را در تب جدید تکمیل کنید. ما به صورت خودکار اتمام را تشخیص می‌دهیم!" }, "resubscribe": "تمدید اشتراک", @@ -5229,7 +5221,6 @@ "saveYearly": "٪۲۰ صرفه‌جویی", "saveYearlyUpTo": "تا ۲۰٪ صرفه‌جویی کنید", "scheduledChangeNotice": "طرح شما در {date} به {plan} تغییر می‌کند.", - "soloUseOnly": "فقط برای استفاده فردی", "subscribe": "اشتراک", "subscribeFailed": "اشتراک‌گذاری ناموفق بود", "subscribeForMore": "ارتقاء", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "این محیط کاری اشتراک فعال ندارد", "yearly": "سالانه", "yearlyCredits": "اعتبار در سال", - "yearlyCreditsLabel": "کل اعتبار سالانه", "yearlyCreditsPerMemberLabel": "اعتبار سالانه / عضو", "yearlyCreditsUsedUpTitle": "اعتبارهای سالانه تمام شده‌اند. در {date} شارژ می‌شوند", "yearlyCreditsUsedUpTitleNoDate": "اعتبارهای سالانه تمام شده‌اند", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "تبدیل آیتم‌ها به subgraph انجام نشد", "failedToCreateCustomer": "ایجاد مشتری انجام نشد: {error}", "failedToExportModel": "صادرات مدل با فرمت {format} انجام نشد", - "failedToFetchBalance": "دریافت موجودی انجام نشد: {error}", "failedToFetchLogs": "دریافت گزارش‌های سرور انجام نشد", "failedToFetchSubscription": "دریافت وضعیت اشتراک انجام نشد: {error}", "failedToInitializeCameraAngleViewer": "راه‌اندازی نمایشگر زاویهٔ دوربین ناموفق بود. صفحه را دوباره بارگذاری کنید.", "failedToInitializeCameraInfoViewer": "راه‌اندازی نمایشگر اطلاعات دوربین ناموفق بود. صفحه را دوباره بارگذاری کنید.", "failedToInitializeLightInfoViewer": "راه‌اندازی نمایشگر اطلاعات نور ناموفق بود. صفحه را دوباره بارگذاری کنید.", "failedToInitializeLoad3dViewer": "راه‌اندازی نمایشگر سه‌بعدی انجام نشد", - "failedToInitiateCreditPurchase": "آغاز خرید اعتبار انجام نشد: {error}", - "failedToInitiateSubscription": "آغاز اشتراک انجام نشد: {error}", "failedToLoadBackgroundImage": "بارگذاری تصویر پس‌زمینه انجام نشد", "failedToLoadHDRI": "بارگذاری فایل HDRI ناموفق بود", "failedToLoadModel": "بارگذاری مدل سه‌بعدی انجام نشد", - "failedToPurchaseCredits": "خرید اعتبار انجام نشد: {error}", "failedToQueue": "صف‌بندی انجام نشد", "failedToRegisterSubgraph": "ثبت زیرگراف ناموفق بود", "failedToSaveDraft": "ذخیره پیش‌نویس workflow ناموفق بود", diff --git a/src/locales/fr/main.json b/src/locales/fr/main.json index d29bc5fc8ca..d0503e1d42c 100644 --- a/src/locales/fr/main.json +++ b/src/locales/fr/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "En cours d'utilisation", "additionalCreditsInfo": "À propos des crédits supplémentaires", "additionalCreditsTooltip": "Crédits ajoutés en plus de votre forfait. Utilisés après épuisement des crédits de votre forfait. Chacun expire un an après l’achat.", - "benefits": { - "benefit1": "Crédits mensuels pour les Nœuds Partenaires — rechargez si nécessaire", - "benefit1FreeTier": "Plus de crédits mensuels, recharge à tout moment", - "benefit2": "Jusqu'à 30 min d'exécution par tâche", - "benefit3": "Utilisez vos propres modèles (Creator & Pro)" - }, "beta": "BÊTA", "billedMonthly": "Facturé mensuellement", "billedYearly": "{total} facturé annuellement", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Crédits mensuels épuisés", "monthlyUsageProgress": "{used} sur {total} crédits mensuels utilisés", "mostPopular": "Le plus populaire", - "needTeamWorkspace": "Besoin d’un espace de travail d’équipe ?", "nextBillingCycle": "prochain cycle de facturation", "outOfCreditsDescription": "Ajoutez des crédits pour continuer à générer.", "outOfCreditsTitle": "Vous n'avez plus de crédits. Recharge le {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "Abonnement activé avec succès !", "pollingTimeout": "Délai d'attente de l'abonnement dépassé. Veuillez actualiser et réessayer.", "subscribe": "S'abonner", - "title": "S'abonner à", "waitingForSubscription": "Complétez votre abonnement dans le nouvel onglet. Nous détecterons automatiquement quand vous aurez terminé !" }, "resubscribe": "Se réabonner", @@ -5229,7 +5221,6 @@ "saveYearly": "Économisez 20 %", "saveYearlyUpTo": "Économisez jusqu’à 20 %", "scheduledChangeNotice": "Votre forfait passe à {plan} le {date}.", - "soloUseOnly": "Usage solo uniquement", "subscribe": "S’abonner", "subscribeFailed": "Échec de l'abonnement", "subscribeForMore": "Mettre à niveau", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Cet espace de travail n’a pas d’abonnement", "yearly": "Annuel", "yearlyCredits": "crédits par an", - "yearlyCreditsLabel": "Crédits annuels totaux", "yearlyCreditsPerMemberLabel": "Crédits annuels / membre", "yearlyCreditsUsedUpTitle": "Les crédits annuels sont épuisés. Renouvellement le {date}", "yearlyCreditsUsedUpTitleNoDate": "Les crédits annuels sont épuisés", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "Échec de la conversion des éléments en sous-graphe", "failedToCreateCustomer": "Échec de la création du client : {error}", "failedToExportModel": "Échec de l'exportation du modèle en {format}", - "failedToFetchBalance": "Échec de la récupération du solde : {error}", "failedToFetchLogs": "Échec de la récupération des journaux du serveur", "failedToFetchSubscription": "Échec de la récupération du statut d'abonnement : {error}", "failedToInitializeCameraAngleViewer": "Échec de l’initialisation de la visionneuse d’angle de caméra. Essayez de recharger la page.", "failedToInitializeCameraInfoViewer": "Impossible d’initialiser la visionneuse d’informations de la caméra. Essayez de recharger la page.", "failedToInitializeLightInfoViewer": "Échec de l’initialisation de la visionneuse d’informations d’éclairage. Essayez de recharger la page.", "failedToInitializeLoad3dViewer": "Échec de l'initialisation du visualiseur 3D", - "failedToInitiateCreditPurchase": "Échec de l'initiation de l'achat de crédits : {error}", - "failedToInitiateSubscription": "Échec de l'initialisation de l'abonnement : {error}", "failedToLoadBackgroundImage": "Échec du chargement de l'image d'arrière-plan", "failedToLoadHDRI": "Échec du chargement du fichier HDRI", "failedToLoadModel": "Échec du chargement du modèle 3D", - "failedToPurchaseCredits": "Échec de l'achat de crédits : {error}", "failedToQueue": "Échec de la mise en file d'attente", "failedToRegisterSubgraph": "Échec de l’enregistrement du sous-graphe", "failedToSaveDraft": "Échec de l’enregistrement du brouillon du flux de travail", diff --git a/src/locales/he/main.json b/src/locales/he/main.json index f24c6bd925a..96acfd5e0d9 100644 --- a/src/locales/he/main.json +++ b/src/locales/he/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "בשימוש", "additionalCreditsInfo": "אודות קרדיטים נוספים", "additionalCreditsTooltip": "קרדיטים שנוספו מעבר לתוכנית שלך. נעשה בהם שימוש לאחר שנגמרים הקרדיטים בתוכנית שלך. תוקפו של כל אחד מהם פג שנה לאחר הרכישה.", - "benefits": { - "benefit1": "קרדיטים חודשיים לצמתי שותפים — טען כשצריך", - "benefit1FreeTier": "יותר קרדיטים חודשיים, טען בכל עת", - "benefit2": "עד שעה אחת של זמן ריצה למשימה במסלול Pro", - "benefit3": "הבא מודלים משלך (Creator ו-Pro)" - }, "beta": "בטא", "billedMonthly": "חיוב חודשי", "billedYearly": "{total} בחיוב שנתי", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "הקרדיטים החודשיים נוצלו", "monthlyUsageProgress": "{used} מתוך {total} קרדיטים חודשיים נוצלו", "mostPopular": "הפופולרי ביותר", - "needTeamWorkspace": "צריך סביבת עבודה צוותית?", "nextBillingCycle": "מחזור החיוב הבא", "outOfCreditsDescription": "הוסף קרדיטים נוספים כדי להמשיך ביצירה.", "outOfCreditsTitle": "אזלו הקרדיטים. הקרדיטים יתמלאו מחדש ב-{date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "המנוי הופעל בהצלחה!", "pollingTimeout": "תם הזמן הקצוב בהמתנה למנוי. אנא רענן ונסה שוב.", "subscribe": "הרשמה", - "title": "הירשם ל", "waitingForSubscription": "השלם את ההרשמה שלך בכרטיסייה החדשה. נזהה אוטומטית כשתסיים!" }, "resubscribe": "הירשם מחדש", @@ -5229,7 +5221,6 @@ "saveYearly": "חסוך 20%", "saveYearlyUpTo": "חסוך עד 20%", "scheduledChangeNotice": "התוכנית שלך משתנה ל-{plan} בתאריך {date}.", - "soloUseOnly": "לשימוש יחיד בלבד", "subscribe": "הירשם", "subscribeFailed": "ההרשמה נכשלה", "subscribeForMore": "שדרוג", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "סביבת עבודה זו אינה במנוי", "yearly": "שנתי", "yearlyCredits": "קרדיטים לשנה", - "yearlyCreditsLabel": "סך הקרדיטים השנתיים", "yearlyCreditsPerMemberLabel": "קרדיטים שנתיים / חבר", "yearlyCreditsUsedUpTitle": "הקרדיטים השנתיים נוצלו. יתמלאו מחדש ב־{date}", "yearlyCreditsUsedUpTitleNoDate": "הקרדיטים השנתיים נוצלו", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "המרת הפריטים לתת-גרף נכשלה", "failedToCreateCustomer": "יצירת הלקוח נכשלה: {error}", "failedToExportModel": "ייצוא המודל כ-{format} נכשל", - "failedToFetchBalance": "אחזור היתרה נכשל: {error}", "failedToFetchLogs": "אחזור יומני השרת נכשל", "failedToFetchSubscription": "אחזור סטטוס המנוי נכשל: {error}", "failedToInitializeCameraAngleViewer": "אתחול מציג זווית המצלמה נכשל. נסה לטעון מחדש את הדף.", "failedToInitializeCameraInfoViewer": "אתחול מציג פרטי המצלמה נכשל. נסה לרענן את הדף.", "failedToInitializeLightInfoViewer": "אתחול מציג פרטי התאורה נכשל. יש לנסות לטעון מחדש את הדף.", "failedToInitializeLoad3dViewer": "אתחול מציג התלת-ממד נכשל", - "failedToInitiateCreditPurchase": "יזימת רכישת הקרדיטים נכשלה: {error}", - "failedToInitiateSubscription": "יזימת המנוי נכשלה: {error}", "failedToLoadBackgroundImage": "טעינת תמונת הרקע נכשלה", "failedToLoadHDRI": "טעינת קובץ ה-HDRI נכשלה", "failedToLoadModel": "טעינת מודל התלת-ממד נכשלה", - "failedToPurchaseCredits": "רכישת הקרדיטים נכשלה: {error}", "failedToQueue": "ההוספה לתור נכשלה", "failedToRegisterSubgraph": "הרישום של תת-הגרף נכשל", "failedToSaveDraft": "שמירת טיוטת תהליך העבודה נכשלה", diff --git a/src/locales/it/main.json b/src/locales/it/main.json index c356bb0f123..c27f0798775 100644 --- a/src/locales/it/main.json +++ b/src/locales/it/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "In uso", "additionalCreditsInfo": "Informazioni sui crediti aggiuntivi", "additionalCreditsTooltip": "Crediti aggiunti oltre il tuo piano. Vengono utilizzati dopo l'esaurimento dei crediti del piano. Ciascuno scade un anno dopo l'acquisto.", - "benefits": { - "benefit1": "Crediti mensili per Partner Nodes — ricarica quando necessario", - "benefit1FreeTier": "Crediti mensili, ricarica in qualsiasi momento", - "benefit2": "Fino a 1 ora di esecuzione per job su Pro", - "benefit3": "Porta i tuoi modelli (Creator & Pro)" - }, "beta": "BETA", "billedMonthly": "Fatturato mensilmente", "billedYearly": "{total} Fatturato annualmente", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Crediti mensili esauriti", "monthlyUsageProgress": "{used} di {total} crediti mensili utilizzati", "mostPopular": "Più popolare", - "needTeamWorkspace": "Hai bisogno di un workspace di team?", "nextBillingCycle": "prossimo ciclo di fatturazione", "outOfCreditsDescription": "Aggiungi altri crediti per continuare a generare.", "outOfCreditsTitle": "Crediti esauriti. Ricarica crediti {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "Abbonamento attivato con successo!", "pollingTimeout": "Tempo scaduto in attesa dell'abbonamento. Aggiorna e riprova.", "subscribe": "Abbonati", - "title": "Abbonati a", "waitingForSubscription": "Completa il tuo abbonamento nella nuova scheda. Rileveremo automaticamente quando hai finito!" }, "resubscribe": "Riattiva abbonamento", @@ -5229,7 +5221,6 @@ "saveYearly": "Risparmia il 20%", "saveYearlyUpTo": "Risparmia fino al 20%", "scheduledChangeNotice": "Il tuo piano cambia in {plan} il {date}.", - "soloUseOnly": "Solo uso personale", "subscribe": "Abbonati", "subscribeFailed": "Impossibile completare l'abbonamento", "subscribeForMore": "Aggiorna", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Questo workspace non ha un abbonamento attivo", "yearly": "Annuale", "yearlyCredits": "crediti all'anno", - "yearlyCreditsLabel": "Crediti annuali totali", "yearlyCreditsPerMemberLabel": "Crediti annuali / membro", "yearlyCreditsUsedUpTitle": "Crediti annuali esauriti. Nuovamente disponibili il {date}", "yearlyCreditsUsedUpTitleNoDate": "Crediti annuali esauriti", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "Impossibile convertire gli elementi in subgraph", "failedToCreateCustomer": "Impossibile creare il cliente: {error}", "failedToExportModel": "Impossibile esportare il modello come {format}", - "failedToFetchBalance": "Impossibile recuperare il saldo: {error}", "failedToFetchLogs": "Impossibile recuperare i log del server", "failedToFetchSubscription": "Impossibile recuperare lo stato dell'abbonamento: {error}", "failedToInitializeCameraAngleViewer": "Impossibile inizializzare il visualizzatore dell'angolo della fotocamera. Prova a ricaricare la pagina.", "failedToInitializeCameraInfoViewer": "Impossibile inizializzare il visualizzatore delle informazioni della fotocamera. Prova a ricaricare la pagina.", "failedToInitializeLightInfoViewer": "Impossibile inizializzare il visualizzatore delle informazioni sull'illuminazione. Prova a ricaricare la pagina.", "failedToInitializeLoad3dViewer": "Impossibile inizializzare il visualizzatore 3D", - "failedToInitiateCreditPurchase": "Impossibile avviare l'acquisto di crediti: {error}", - "failedToInitiateSubscription": "Impossibile avviare l'abbonamento: {error}", "failedToLoadBackgroundImage": "Impossibile caricare l'immagine di sfondo", "failedToLoadHDRI": "Impossibile caricare il file HDRI", "failedToLoadModel": "Impossibile caricare il modello 3D", - "failedToPurchaseCredits": "Impossibile acquistare crediti: {error}", "failedToQueue": "Impossibile mettere in coda", "failedToRegisterSubgraph": "Impossibile registrare il sottografo", "failedToSaveDraft": "Impossibile salvare la bozza del workflow", diff --git a/src/locales/ja/main.json b/src/locales/ja/main.json index 1e6b487c4cb..b85ee9af714 100644 --- a/src/locales/ja/main.json +++ b/src/locales/ja/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "使用中", "additionalCreditsInfo": "追加クレジットについて", "additionalCreditsTooltip": "プランに追加するクレジットです。プランのクレジットを使い切った後に使用されます。各クレジットは購入から1年後に失効します。", - "benefits": { - "benefit1": "パートナーノード用月間クレジット — 必要に応じて追加購入可能", - "benefit1FreeTier": "毎月のクレジット増加、いつでもチャージ可能", - "benefit2": "ジョブあたり最大30分の実行時間", - "benefit3": "独自のモデルを利用可能(Creator & Pro)" - }, "beta": "ベータ版", "billedMonthly": "毎月請求", "billedYearly": "{total} 年間請求", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "月間クレジットが使い切られました", "monthlyUsageProgress": "月間クレジット {total} 中 {used} 使用済み", "mostPopular": "最も人気", - "needTeamWorkspace": "チームワークスペースが必要ですか?", "nextBillingCycle": "次の請求サイクル", "outOfCreditsDescription": "生成を続けるにはクレジットを追加してください。", "outOfCreditsTitle": "クレジットがありません。{date}に補充されます", @@ -5180,7 +5173,6 @@ "pollingSuccess": "サブスクリプションが有効化されました!", "pollingTimeout": "サブスクリプションの待機がタイムアウトしました。再読み込みして再試行してください。", "subscribe": "購読する", - "title": "購読する", "waitingForSubscription": "新しいタブで購読を完了してください。完了を自動的に検知します!" }, "resubscribe": "再購読する", @@ -5229,7 +5221,6 @@ "saveYearly": "20%お得", "saveYearlyUpTo": "最大20%お得", "scheduledChangeNotice": "プランは{date}に{plan}へ変更されます。", - "soloUseOnly": "個人利用のみ", "subscribe": "購読する", "subscribeFailed": "購読に失敗しました", "subscribeForMore": "アップグレード", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "このワークスペースはサブスクリプションに加入していません", "yearly": "年額", "yearlyCredits": "年間クレジット", - "yearlyCreditsLabel": "年間合計クレジット", "yearlyCreditsPerMemberLabel": "メンバーあたりの年間クレジット", "yearlyCreditsUsedUpTitle": "年間クレジットを使い切りました。{date}に補充されます", "yearlyCreditsUsedUpTitleNoDate": "年間クレジットを使い切りました", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "アイテムをサブグラフに変換できませんでした", "failedToCreateCustomer": "顧客の作成に失敗しました: {error}", "failedToExportModel": "{format}としてモデルのエクスポートに失敗しました", - "failedToFetchBalance": "残高の取得に失敗しました: {error}", "failedToFetchLogs": "サーバーログの取得に失敗しました", "failedToFetchSubscription": "サブスクリプションステータスの取得に失敗しました: {error}", "failedToInitializeCameraAngleViewer": "カメラアングルビューアの初期化に失敗しました。ページを再読み込みしてください。", "failedToInitializeCameraInfoViewer": "カメラ情報ビューアーの初期化に失敗しました。ページを再読み込みしてください。", "failedToInitializeLightInfoViewer": "Light Infoビューアの初期化に失敗しました。ページを再読み込みしてみてください。", "failedToInitializeLoad3dViewer": "3Dビューアの初期化に失敗しました", - "failedToInitiateCreditPurchase": "クレジット購入の開始に失敗しました: {error}", - "failedToInitiateSubscription": "サブスクリプションの開始に失敗しました: {error}", "failedToLoadBackgroundImage": "背景画像の読み込みに失敗しました", "failedToLoadHDRI": "HDRIファイルの読み込みに失敗しました", "failedToLoadModel": "3Dモデルの読み込みに失敗しました", - "failedToPurchaseCredits": "クレジットの購入に失敗しました: {error}", "failedToQueue": "キューに追加できませんでした", "failedToRegisterSubgraph": "サブグラフの登録に失敗しました", "failedToSaveDraft": "ワークフロードラフトの保存に失敗しました", diff --git a/src/locales/ko/main.json b/src/locales/ko/main.json index b549ec7863d..fe62b7a15dd 100644 --- a/src/locales/ko/main.json +++ b/src/locales/ko/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "사용 중", "additionalCreditsInfo": "추가 크레딧 안내", "additionalCreditsTooltip": "플랜에 추가로 더하는 크레딧입니다. 플랜 크레딧 소진 후 사용됩니다. 각각 구매 후 1년이 지나면 만료됩니다.", - "benefits": { - "benefit1": "파트너 노드 월간 크레딧 — 필요 시 충전", - "benefit1FreeTier": "더 많은 월간 크레딧, 언제든지 충전 가능", - "benefit2": "작업당 최대 30분 실행 시간", - "benefit3": "직접 모델 가져오기(Creator & Pro)" - }, "beta": "베타", "billedMonthly": "매월 결제", "billedYearly": "{total} 연간 결제", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "월간 크레딧이 모두 사용되었습니다", "monthlyUsageProgress": "월간 크레딧 {total} 중 {used} 사용됨", "mostPopular": "가장 인기 있음", - "needTeamWorkspace": "팀 워크스페이스가 필요하신가요?", "nextBillingCycle": "다음 결제 주기", "outOfCreditsDescription": "생성을 계속하려면 크레딧을 추가하세요.", "outOfCreditsTitle": "크레딧이 모두 소진되었습니다. {date}에 크레딧이 리필됩니다", @@ -5180,7 +5173,6 @@ "pollingSuccess": "구독이 성공적으로 활성화되었습니다!", "pollingTimeout": "구독 대기 시간이 초과되었습니다. 새로고침 후 다시 시도하세요.", "subscribe": "구독", - "title": "구독하기", "waitingForSubscription": "새 탭에서 구독을 완료해주세요. 완료되면 자동으로 감지합니다!" }, "resubscribe": "다시 구독하기", @@ -5229,7 +5221,6 @@ "saveYearly": "20% 절감", "saveYearlyUpTo": "최대 20% 절약", "scheduledChangeNotice": "{date}에 요금제가 {plan}(으)로 변경됩니다.", - "soloUseOnly": "개인용 전용", "subscribe": "구독하기", "subscribeFailed": "구독에 실패했습니다", "subscribeForMore": "업그레이드", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "이 워크스페이스는 구독 중이 아닙니다", "yearly": "연간", "yearlyCredits": "연간 크레딧", - "yearlyCreditsLabel": "연간 총 크레딧", "yearlyCreditsPerMemberLabel": "구성원당 연간 크레딧", "yearlyCreditsUsedUpTitle": "연간 크레딧이 모두 소진되었습니다. {date}에 충전됩니다", "yearlyCreditsUsedUpTitleNoDate": "연간 크레딧이 모두 소진되었습니다", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "항목을 서브그래프로 변환하지 못했습니다", "failedToCreateCustomer": "고객 생성에 실패했습니다: {error}", "failedToExportModel": "{format} 형식으로 모델 내보내기에 실패했습니다", - "failedToFetchBalance": "잔액을 가져오지 못했습니다: {error}", "failedToFetchLogs": "서버 로그를 가져오는 데 실패했습니다", "failedToFetchSubscription": "구독 상태를 가져오지 못함: {error}", "failedToInitializeCameraAngleViewer": "카메라 앵글 뷰어를 초기화하지 못했습니다. 페이지를 새로고침해 보세요.", "failedToInitializeCameraInfoViewer": "카메라 정보 뷰어를 초기화하지 못했습니다. 페이지를 새로고침해 보세요.", "failedToInitializeLightInfoViewer": "Light Info 뷰어를 초기화하지 못했습니다. 페이지를 새로고침해 보세요.", "failedToInitializeLoad3dViewer": "3D 뷰어 초기화 실패", - "failedToInitiateCreditPurchase": "크레딧 구매를 시작하지 못했습니다: {error}", - "failedToInitiateSubscription": "구독을 시작하지 못함: {error}", "failedToLoadBackgroundImage": "배경 이미지를 로드하지 못함", "failedToLoadHDRI": "HDRI 파일을 불러오지 못했습니다", "failedToLoadModel": "3D 모델을 로드하지 못함", - "failedToPurchaseCredits": "크레딧 구매에 실패했습니다: {error}", "failedToQueue": "대기열 추가 실패", "failedToRegisterSubgraph": "하위 그래프를 등록하지 못했습니다", "failedToSaveDraft": "워크플로우 초안 저장에 실패했습니다", diff --git a/src/locales/pt-BR/main.json b/src/locales/pt-BR/main.json index 80a80108bca..bc3f29b6e57 100644 --- a/src/locales/pt-BR/main.json +++ b/src/locales/pt-BR/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "Em uso", "additionalCreditsInfo": "Sobre créditos adicionais", "additionalCreditsTooltip": "Créditos adicionados além do seu plano. Usados após os créditos do seu plano acabarem. Cada um expira um ano após a compra.", - "benefits": { - "benefit1": "$10 em créditos mensais para Partner Nodes — recarregue quando necessário", - "benefit1FreeTier": "Mais créditos mensais, recarregue a qualquer momento", - "benefit2": "Até 30 min de execução por tarefa", - "benefit3": "Use seus próprios modelos (Creator & Pro)" - }, "beta": "BETA", "billedMonthly": "Cobrado mensalmente", "billedYearly": "{total} Cobrado anualmente", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Créditos mensais esgotados", "monthlyUsageProgress": "{used} de {total} créditos mensais usados", "mostPopular": "Mais popular", - "needTeamWorkspace": "Precisa de um espaço de trabalho em equipe?", "nextBillingCycle": "próximo ciclo de cobrança", "outOfCreditsDescription": "Adicione mais créditos para continuar gerando.", "outOfCreditsTitle": "Você está sem créditos. Recarga em {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "Assinatura ativada com sucesso!", "pollingTimeout": "Tempo esgotado aguardando a assinatura. Atualize e tente novamente.", "subscribe": "Assinar", - "title": "Assinar", "waitingForSubscription": "Conclua sua assinatura na nova aba. Detectaremos automaticamente quando você terminar!" }, "resubscribe": "Reassinar", @@ -5229,7 +5221,6 @@ "saveYearly": "Economize 20%", "saveYearlyUpTo": "Economize até 20%", "scheduledChangeNotice": "Seu plano muda para {plan} em {date}.", - "soloUseOnly": "Apenas para uso individual", "subscribe": "Assinar", "subscribeFailed": "Falha ao assinar", "subscribeForMore": "Fazer upgrade", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Este espaço de trabalho não possui uma assinatura", "yearly": "Anual", "yearlyCredits": "créditos por ano", - "yearlyCreditsLabel": "Total de créditos anuais", "yearlyCreditsPerMemberLabel": "Créditos anuais / membro", "yearlyCreditsUsedUpTitle": "Os créditos anuais se esgotaram. Reposição em {date}", "yearlyCreditsUsedUpTitleNoDate": "Os créditos anuais se esgotaram", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "Falha ao converter itens para subgrafo", "failedToCreateCustomer": "Falha ao criar cliente: {error}", "failedToExportModel": "Falha ao exportar o modelo como {format}", - "failedToFetchBalance": "Falha ao buscar saldo: {error}", "failedToFetchLogs": "Falha ao buscar logs do servidor", "failedToFetchSubscription": "Falha ao buscar status da assinatura: {error}", "failedToInitializeCameraAngleViewer": "Falha ao inicializar o visualizador de ângulo da câmera. Tente recarregar a página.", "failedToInitializeCameraInfoViewer": "Falha ao inicializar o visualizador de informações da câmera. Tente recarregar a página.", "failedToInitializeLightInfoViewer": "Não foi possível inicializar o visualizador de informações de iluminação. Tente recarregar a página.", "failedToInitializeLoad3dViewer": "Falha ao inicializar o Visualizador 3D", - "failedToInitiateCreditPurchase": "Falha ao iniciar compra de créditos: {error}", - "failedToInitiateSubscription": "Falha ao iniciar assinatura: {error}", "failedToLoadBackgroundImage": "Falha ao carregar imagem de fundo", "failedToLoadHDRI": "Falha ao carregar o arquivo HDRI", "failedToLoadModel": "Falha ao carregar modelo 3D", - "failedToPurchaseCredits": "Falha ao comprar créditos: {error}", "failedToQueue": "Falha ao enfileirar", "failedToRegisterSubgraph": "Não foi possível registrar o subgrafo", "failedToSaveDraft": "Falha ao salvar o rascunho do fluxo de trabalho", diff --git a/src/locales/ru/main.json b/src/locales/ru/main.json index 8aefb0baf78..f3f6f019d57 100644 --- a/src/locales/ru/main.json +++ b/src/locales/ru/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "Используются", "additionalCreditsInfo": "О дополнительных кредитах", "additionalCreditsTooltip": "Кредиты, добавленные сверх вашего плана. Используются после окончания кредитов плана. Срок действия каждого истекает через год после покупки.", - "benefits": { - "benefit1": "Ежемесячные кредиты для Партнёрских узлов — пополняйте по необходимости", - "benefit1FreeTier": "Больше кредитов в месяц, пополнение в любое время", - "benefit2": "До 30 минут выполнения на задание", - "benefit3": "Используйте свои модели (Creator & Pro)" - }, "beta": "БЕТА", "billedMonthly": "Оплата ежемесячно", "billedYearly": "{total} Оплата ежегодно", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Ежемесячные кредиты израсходованы", "monthlyUsageProgress": "Использовано {used} из {total} ежемесячных кредитов", "mostPopular": "Самый популярный", - "needTeamWorkspace": "Нужно командное рабочее пространство?", "nextBillingCycle": "следующий платёжный цикл", "outOfCreditsDescription": "Добавьте кредиты, чтобы продолжить генерацию.", "outOfCreditsTitle": "Кредиты закончились. Пополнение {date}", @@ -5180,7 +5173,6 @@ "pollingSuccess": "Подписка успешно активирована!", "pollingTimeout": "Время ожидания подписки истекло. Пожалуйста, обновите страницу и попробуйте снова.", "subscribe": "Подписаться", - "title": "Подписаться на", "waitingForSubscription": "Завершите оформление подписки в новой вкладке. Мы автоматически определим, когда вы закончите!" }, "resubscribe": "Возобновить подписку", @@ -5229,7 +5221,6 @@ "saveYearly": "Экономия 20%", "saveYearlyUpTo": "Экономьте до 20%", "scheduledChangeNotice": "Ваш план изменится на {plan} {date}.", - "soloUseOnly": "Только для индивидуального использования", "subscribe": "Подписаться", "subscribeFailed": "Не удалось подписаться", "subscribeForMore": "Обновить", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Это рабочее пространство не имеет подписки", "yearly": "Ежегодно", "yearlyCredits": "кредитов в год", - "yearlyCreditsLabel": "Годовые кредиты", "yearlyCreditsPerMemberLabel": "Годовые кредиты / участник", "yearlyCreditsUsedUpTitle": "Годовые кредиты израсходованы. Пополнение — {date}", "yearlyCreditsUsedUpTitleNoDate": "Годовые кредиты израсходованы", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "Не удалось преобразовать элементы в подграф", "failedToCreateCustomer": "Не удалось создать клиента: {error}", "failedToExportModel": "Не удалось экспортировать модель как {format}", - "failedToFetchBalance": "Не удалось получить баланс: {error}", "failedToFetchLogs": "Не удалось получить серверные логи", "failedToFetchSubscription": "Не удалось получить статус подписки: {error}", "failedToInitializeCameraAngleViewer": "Не удалось инициализировать средство просмотра ракурса камеры. Попробуйте перезагрузить страницу.", "failedToInitializeCameraInfoViewer": "Не удалось инициализировать просмотрщик сведений о камере. Попробуйте перезагрузить страницу.", "failedToInitializeLightInfoViewer": "Не удалось инициализировать средство просмотра Light Info. Попробуйте перезагрузить страницу.", "failedToInitializeLoad3dViewer": "Не удалось инициализировать 3D просмотрщик", - "failedToInitiateCreditPurchase": "Не удалось начать покупку кредитов: {error}", - "failedToInitiateSubscription": "Не удалось инициировать подписку: {error}", "failedToLoadBackgroundImage": "Не удалось загрузить фоновое изображение", "failedToLoadHDRI": "Не удалось загрузить файл HDRI", "failedToLoadModel": "Не удалось загрузить 3D-модель", - "failedToPurchaseCredits": "Не удалось купить кредиты: {error}", "failedToQueue": "Не удалось поставить в очередь", "failedToRegisterSubgraph": "Не удалось зарегистрировать подграф", "failedToSaveDraft": "Не удалось сохранить черновик рабочего процесса", diff --git a/src/locales/tr/main.json b/src/locales/tr/main.json index 583de7e94ec..06e8e525769 100644 --- a/src/locales/tr/main.json +++ b/src/locales/tr/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "Kullanımda", "additionalCreditsInfo": "Ek krediler hakkında", "additionalCreditsTooltip": "Planınıza ek olarak satın aldığınız krediler. Plan kredileriniz tükendikten sonra kullanılır. Her biri satın alma tarihinden bir yıl sonra sona erer.", - "benefits": { - "benefit1": "Partner Düğümleri için aylık krediler — ihtiyaç duyulduğunda yükleyin", - "benefit1FreeTier": "Daha fazla aylık kredi, istediğiniz zaman yükleyin", - "benefit2": "İş başına en fazla 30 dakika çalışma süresi", - "benefit3": "Kendi modellerinizi getirin (Creator & Pro)" - }, "beta": "BETA", "billedMonthly": "Aylık faturalandırılır", "billedYearly": "{total} Yıllık faturalandırılır", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "Aylık krediler tükendi", "monthlyUsageProgress": "Aylık kredilerin {total} üzerinden {used} kullanıldı", "mostPopular": "En popüler", - "needTeamWorkspace": "Takım çalışma alanına mı ihtiyacınız var?", "nextBillingCycle": "sonraki fatura döngüsü", "outOfCreditsDescription": "Devam etmek için daha fazla kredi ekleyin.", "outOfCreditsTitle": "Kredileriniz tükendi. {date} tarihinde yenilenecek", @@ -5180,7 +5173,6 @@ "pollingSuccess": "Abonelik başarıyla etkinleştirildi!", "pollingTimeout": "Abonelik için bekleme süresi doldu. Lütfen sayfayı yenileyip tekrar deneyin.", "subscribe": "Abone Ol", - "title": "Abone ol", "waitingForSubscription": "Aboneliğinizi yeni sekmede tamamlayın. İşleminiz bittiğinde otomatik olarak algılayacağız!" }, "resubscribe": "Yeniden abone ol", @@ -5229,7 +5221,6 @@ "saveYearly": "%20 tasarruf", "saveYearlyUpTo": "%20'ye kadar tasarruf edin", "scheduledChangeNotice": "Planınız {date} tarihinde {plan} olarak değişecek.", - "soloUseOnly": "Sadece bireysel kullanım", "subscribe": "Abone ol", "subscribeFailed": "Abonelik başarısız oldu", "subscribeForMore": "Yükselt", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "Bu çalışma alanı bir aboneliğe sahip değil", "yearly": "Yıllık", "yearlyCredits": "yıllık kredi", - "yearlyCreditsLabel": "Toplam yıllık krediler", "yearlyCreditsPerMemberLabel": "Yıllık krediler / üye", "yearlyCreditsUsedUpTitle": "Yıllık krediler tükendi. {date} tarihinde yenilenir", "yearlyCreditsUsedUpTitleNoDate": "Yıllık krediler tükendi", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "Öğeler alt grafiğe dönüştürülemedi", "failedToCreateCustomer": "Müşteri oluşturulamadı: {error}", "failedToExportModel": "Model {format} olarak dışa aktarılamadı", - "failedToFetchBalance": "Bakiye alınamadı: {error}", "failedToFetchLogs": "Sunucu günlükleri alınamadı", "failedToFetchSubscription": "Abonelik durumu alınamadı: {error}", "failedToInitializeCameraAngleViewer": "Kamera Açısı görüntüleyicisi başlatılamadı. Sayfayı yeniden yüklemeyi deneyin.", "failedToInitializeCameraInfoViewer": "Kamera Bilgisi görüntüleyicisi başlatılamadı. Sayfayı yeniden yüklemeyi deneyin.", "failedToInitializeLightInfoViewer": "Işık Bilgisi görüntüleyicisi başlatılamadı. Sayfayı yeniden yüklemeyi deneyin.", "failedToInitializeLoad3dViewer": "3D Görüntüleyici başlatılamadı", - "failedToInitiateCreditPurchase": "Kredi satın alma başlatılamadı: {error}", - "failedToInitiateSubscription": "Abonelik başlatılamadı: {error}", "failedToLoadBackgroundImage": "Arka plan görseli yüklenemedi", "failedToLoadHDRI": "HDRI dosyası yüklenemedi", "failedToLoadModel": "3B model yüklenemedi", - "failedToPurchaseCredits": "Kredi satın alınamadı: {error}", "failedToQueue": "Kuyruğa alınamadı", "failedToRegisterSubgraph": "Alt grafik kaydedilemedi", "failedToSaveDraft": "Çalışma taslağı kaydedilemedi", diff --git a/src/locales/zh-TW/main.json b/src/locales/zh-TW/main.json index 8ae1eb5ea05..458cfce6fde 100644 --- a/src/locales/zh-TW/main.json +++ b/src/locales/zh-TW/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "使用中", "additionalCreditsInfo": "關於額外點數", "additionalCreditsTooltip": "您在方案之外加購的點數。方案點數用完後使用。每筆點數會在購買一年後到期。", - "benefits": { - "benefit1": "合作節點每月點數 — 需要時可隨時加值", - "benefit1FreeTier": "每月更多點數,隨時加值", - "benefit2": "每項任務最多運行 30 分鐘", - "benefit3": "可自帶模型(Creator & Pro)" - }, "beta": "測試版", "billedMonthly": "每月收費", "billedYearly": "每年收費 {total}", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "本月點數已用完", "monthlyUsageProgress": "本月已用 {used} / {total} 點數", "mostPopular": "最受歡迎", - "needTeamWorkspace": "需要團隊工作區?", "nextBillingCycle": "下個計費週期", "outOfCreditsDescription": "請新增點數以繼續產生。", "outOfCreditsTitle": "您的點數已用完。點數將於 {date} 補充", @@ -5180,7 +5173,6 @@ "pollingSuccess": "訂閱已成功啟用!", "pollingTimeout": "等待訂閱逾時。請重新整理並再試一次。", "subscribe": "訂閱", - "title": "訂閱", "waitingForSubscription": "請在新分頁中完成訂閱。完成後我們會自動偵測!" }, "resubscribe": "重新訂閱", @@ -5229,7 +5221,6 @@ "saveYearly": "節省 20%", "saveYearlyUpTo": "最高可省 20%", "scheduledChangeNotice": "您的方案將於 {date} 變更為 {plan}。", - "soloUseOnly": "僅限個人使用", "subscribe": "訂閱", "subscribeFailed": "訂閱失敗", "subscribeForMore": "升級", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "此工作區尚未訂閱", "yearly": "每年", "yearlyCredits": "每年點數", - "yearlyCreditsLabel": "年度總點數", "yearlyCreditsPerMemberLabel": "年度點數 / 成員", "yearlyCreditsUsedUpTitle": "年度點數已用完。將於 {date} 補充", "yearlyCreditsUsedUpTitleNoDate": "年度點數已用完", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "轉換項目為子圖失敗", "failedToCreateCustomer": "建立客戶失敗:{error}", "failedToExportModel": "無法將模型匯出為 {format}", - "failedToFetchBalance": "取得餘額失敗:{error}", "failedToFetchLogs": "無法取得伺服器日誌", "failedToFetchSubscription": "無法取得訂閱狀態:{error}", "failedToInitializeCameraAngleViewer": "無法初始化相機角度檢視器。請嘗試重新載入頁面。", "failedToInitializeCameraInfoViewer": "無法初始化相機資訊檢視器。請嘗試重新載入頁面。", "failedToInitializeLightInfoViewer": "初始化 Light Info 檢視器失敗。請嘗試重新載入頁面。", "failedToInitializeLoad3dViewer": "無法初始化 3D 檢視器", - "failedToInitiateCreditPurchase": "啟動點數購買失敗:{error}", - "failedToInitiateSubscription": "無法啟用訂閱:{error}", "failedToLoadBackgroundImage": "無法載入背景圖片", "failedToLoadHDRI": "載入 HDRI 檔案失敗", "failedToLoadModel": "無法載入 3D 模型", - "failedToPurchaseCredits": "購買點數失敗:{error}", "failedToQueue": "加入佇列失敗", "failedToRegisterSubgraph": "註冊子圖失敗", "failedToSaveDraft": "無法儲存工作流程草稿", diff --git a/src/locales/zh/main.json b/src/locales/zh/main.json index 254894e5bda..accc21aac9f 100644 --- a/src/locales/zh/main.json +++ b/src/locales/zh/main.json @@ -4846,12 +4846,6 @@ "additionalCreditsInUse": "正在使用", "additionalCreditsInfo": "关于额外点数", "additionalCreditsTooltip": "在套餐额度之外额外添加的额度。套餐额度用尽后使用。每笔额度自购买之日起一年后到期。", - "benefits": { - "benefit1": "合作伙伴节点的月度积分 — 按需充值", - "benefit1FreeTier": "每月更多积分,随时补充", - "benefit2": "每个队列最长运行 30 分钟", - "benefit3": "支持自带模型(Creator & Pro)" - }, "beta": "测试版", "billedMonthly": "每月付款", "billedYearly": "{total} 每年付款", @@ -5014,7 +5008,6 @@ "monthlyCreditsUsedUpTitleNoDate": "本月点数已用完", "monthlyUsageProgress": "本月已用 {used} / {total} 点数", "mostPopular": "最受欢迎", - "needTeamWorkspace": "需要团队工作区?", "nextBillingCycle": "下一个计费周期", "outOfCreditsDescription": "请添加更多点数以继续生成。", "outOfCreditsTitle": "您的点数已用完。点数将于 {date} 补充", @@ -5180,7 +5173,6 @@ "pollingSuccess": "订阅激活成功!", "pollingTimeout": "等待订阅超时。请刷新并重试。", "subscribe": "订阅", - "title": "订阅", "waitingForSubscription": "请在新标签页中完成订阅。我们会自动检测到您已完成!" }, "resubscribe": "重新订阅", @@ -5229,7 +5221,6 @@ "saveYearly": "立省 20%", "saveYearlyUpTo": "最高可节省 20%", "scheduledChangeNotice": "你的套餐将于 {date} 变更为 {plan}。", - "soloUseOnly": "仅限个人使用", "subscribe": "订阅", "subscribeFailed": "订阅失败", "subscribeForMore": "升级", @@ -5329,7 +5320,6 @@ "workspaceNotSubscribed": "此工作区未订阅", "yearly": "年度", "yearlyCredits": "每年额度", - "yearlyCreditsLabel": "总共年度积分", "yearlyCreditsPerMemberLabel": "年度额度 / 成员", "yearlyCreditsUsedUpTitle": "年度额度已用尽。将于 {date} 补充", "yearlyCreditsUsedUpTitleNoDate": "年度额度已用尽", @@ -5497,19 +5487,15 @@ "failedToConvertToSubgraph": "无法将项目转换为子工作流", "failedToCreateCustomer": "创建客户失败:{error}", "failedToExportModel": "无法将模型导出为 {format}", - "failedToFetchBalance": "获取余额失败:{error}", "failedToFetchLogs": "无法获取服务器日志", "failedToFetchSubscription": "获取订阅状态失败:{error}", "failedToInitializeCameraAngleViewer": "无法初始化相机角度查看器。请尝试重新加载页面。", "failedToInitializeCameraInfoViewer": "初始化相机信息查看器失败。请尝试重新加载页面。", "failedToInitializeLightInfoViewer": "初始化光照信息查看器失败。请尝试重新加载页面。", "failedToInitializeLoad3dViewer": "初始化3D查看器失败", - "failedToInitiateCreditPurchase": "发起积分购买失败:{error}", - "failedToInitiateSubscription": "订阅启动失败:{error}", "failedToLoadBackgroundImage": "无法加载背景图片", "failedToLoadHDRI": "HDRI文件加载失败", "failedToLoadModel": "无法加载3D模型", - "failedToPurchaseCredits": "购买积分失败:{error}", "failedToQueue": "排队失败", "failedToRegisterSubgraph": "注册子图失败", "failedToSaveDraft": "保存工作流草稿失败", diff --git a/src/main.ts b/src/main.ts index 4b30457c04a..37dceafb209 100644 --- a/src/main.ts +++ b/src/main.ts @@ -10,7 +10,6 @@ import { flushProxyWidgetMigration } from '@/core/graph/subgraph/migration/proxy import { autoExposeKnownPreviewNodes } from '@/core/graph/subgraph/promotionUtils' import { LGraph } from '@/lib/litegraph/src/litegraph' import { installCloudApiAuth } from '@/platform/auth/cloudApiAuthProvider' -import { provideTeamWorkspaceDialog } from '@/platform/billing/ports/teamWorkspaceDialog' import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { configValueOrDefault, @@ -167,11 +166,6 @@ async function bootstrap(): Promise { installCloudApiAuth() } installWorkspaceApiAuth() - provideTeamWorkspaceDialog(async (onConfirm) => { - const { useWorkspaceDialogs } = - await import('@/platform/account/composables/useWorkspaceDialogs') - return useWorkspaceDialogs().showTeamWorkspacesDialog(onConfirm) - }) bootstrapTracer.armWatchdog() diff --git a/src/platform/auth/currentUserAccess.ts b/src/platform/auth/currentUserAccess.ts index 87fc797d124..a76212f79fb 100644 --- a/src/platform/auth/currentUserAccess.ts +++ b/src/platform/auth/currentUserAccess.ts @@ -5,6 +5,7 @@ import { assert } from '@/base/assert' interface CurrentUserAccess { readonly userEmail: ComputedRef readonly isApiKeyLogin: ComputedRef + readonly isLoggedIn: ComputedRef } let providedUseCurrentUser: (() => CurrentUserAccess) | undefined diff --git a/src/platform/auth/webSessionFlagOff.test.ts b/src/platform/auth/webSessionFlagOff.test.ts index 5eba46c1b25..17fa5b36f0a 100644 --- a/src/platform/auth/webSessionFlagOff.test.ts +++ b/src/platform/auth/webSessionFlagOff.test.ts @@ -768,58 +768,6 @@ describe.for([ }) } ) -describe.for([ - { name: 'unified_cloud_auth off', features: { unified_cloud_auth: false } }, - { name: 'unified_cloud_auth on', features: { unified_cloud_auth: true } } -])('billing with unified_web_session off ($name)', ({ features }) => { - const onFirebaseToken = (method: string, path: string): RecordedRequest => ({ - method, - path: `${getComfyApiBaseUrl()}${path}`, - headers: { - authorization: 'Bearer firebase-id-token', - 'content-type': 'application/json' - }, - credentials: null - }) - - beforeEach(() => { - identity.reset() - }) - - afterEach(() => { - remoteConfig.value = {} - }) - - it('sends balance, top-up, portal and the 409 recovery on the Firebase token and mints nothing', async () => { - const recorder = installFetchRecorder(features) - await refreshRemoteConfig({ useAuth: false }) - const authStore = useAuthStore() - await authStore.login('user-a@example.com', 'password') - await vi.waitFor(() => - expect(recorder.pending).toContainEqual(CUSTOMER_PROVISIONING) - ) - recorder.take() - - await authStore.fetchBalance() - await authStore.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - await authStore.accessBillingPortal() - recorder.loseCustomer() - await authStore.fetchBalance() - - expect(recorder.take()).toEqual([ - onFirebaseToken('GET', '/customers/balance'), - onFirebaseToken('POST', '/customers/credit'), - onFirebaseToken('POST', '/customers/billing'), - onFirebaseToken('GET', '/customers/balance'), - onFirebaseToken('POST', '/customers'), - onFirebaseToken('GET', '/customers/balance') - ]) - }) -}) - describe('an interactive sign-in with unified_web_session off', () => { beforeEach(() => { identity.reset() diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index 116ab2de589..c9793b1d07e 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -83,7 +83,6 @@ import { getSessionOverride } from '@/utils/sessionFeatureFlagOverride' import type { ComfyApp } from '@/scripts/app' import { useExtensionService } from '@/platform/extensions/services/extensionService' import { createDisposablePinia } from '@/testing/pinia' -import { useCustomerEventsService } from '@/services/customerEventsService' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { NO_PERSONAL_WORKSPACE, useAuthStore } from '@/stores/authStore' import { getWorkspaceId } from '@/platform/workflow/persistence/base/storageKeys' @@ -2555,28 +2554,10 @@ describe('billing on a tab that arrived by session', () => { it.for([ { - name: 'balance', + name: 'customer provisioning', call: (authStore: ReturnType) => - authStore.fetchBalance(), - sent: [onSessionToken('GET', '/customers/balance')] - }, - { - name: 'top-up', - call: (authStore: ReturnType) => - authStore.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }), - sent: [ - onSessionToken('POST', '/customers'), - onSessionToken('POST', '/customers/credit') - ] - }, - { - name: 'billing portal', - call: (authStore: ReturnType) => - authStore.accessBillingPortal(), - sent: [onSessionToken('POST', '/customers/billing')] + authStore.createCustomer(), + sent: [onSessionToken('POST', '/customers')] } ])( 'the $name call is sent with the session-minted token', @@ -2596,14 +2577,14 @@ describe('billing on a tab that arrived by session', () => { { sso: true, reported: true, sendsCustomers: true }, { sso: true, reported: false, sendsCustomers: false } ])( - 'sso_enabled $sso with has_personal_workspace $reported: balance reaches /customers is $sendsCustomers', + 'sso_enabled $sso with has_personal_workspace $reported: a customer setup reaches /customers is $sendsCustomers', async ({ sso, reported, sendsCustomers }) => { const { ingest, authStore } = await bootSessionOnly( { sso_enabled: sso }, reported ) - await authStore.fetchBalance() + await authStore.createCustomer().catch(() => undefined) expect( ingest.requests.some(({ path }) => path.startsWith('/customers')) @@ -2611,72 +2592,20 @@ describe('billing on a tab that arrived by session', () => { } ) - it.for([ - { - name: 'top-up', - call: (authStore: ReturnType) => - authStore.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - }, - { - name: 'billing portal', - call: (authStore: ReturnType) => - authStore.accessBillingPortal() - }, - { - name: 'subscription checkout', - call: (authStore: ReturnType) => - authStore.fetchWithCustomerRecovery( - '/customers/cloud-subscription-checkout', - { method: 'POST' } - ) - } - ])( - 'the $name call is refused before /customers without a personal workspace', - async ({ call }) => { - const { ingest, authStore } = await bootSessionOnly( - { sso_enabled: true }, - false - ) - - await expect(call(authStore)).rejects.toMatchObject({ - code: NO_PERSONAL_WORKSPACE - }) - expect( - ingest.requests.filter(({ path }) => path.startsWith('/customers')) - ).toEqual([]) - } - ) - - it('loads no customer events without a personal workspace', async () => { - const { ingest } = await bootSessionOnly({ sso_enabled: true }, false) - const events = useCustomerEventsService() - - await expect(events.getMyEvents()).resolves.toBeNull() - expect(events.error.value).toBe( - 'This account has no personal billing. Manage billing from your team workspace.' + it('refuses customer setup before /customers without a personal workspace', async () => { + const { ingest, authStore } = await bootSessionOnly( + { sso_enabled: true }, + false ) + + await expect(authStore.createCustomer()).rejects.toMatchObject({ + code: NO_PERSONAL_WORKSPACE + }) expect( ingest.requests.filter(({ path }) => path.startsWith('/customers')) ).toEqual([]) }) - it('provisions a missing customer on the session token and retries once', async () => { - const { ingest, authStore } = await bootSessionOnly() - ingest.customerMissing = true - - await authStore.fetchBalance() - - expect(authorizationsOf(ingest)).toEqual([ - SESSION_MINT, - onSessionToken('GET', '/customers/balance'), - onSessionToken('POST', '/customers'), - onSessionToken('GET', '/customers/balance') - ]) - }) - it.for([ { name: 'resolves', @@ -2793,51 +2722,6 @@ describe.for([{ unified: false }, { unified: true }])( expect(user.isEmailProvider.value).toBe(false) }) - it('discards a late balance response after the Firebase credential changes', async () => { - const { authStore } = await bootSessionOnly() - identity.signIn(USER_A) - const sessionFetch = vi.mocked(fetch).getMockImplementation() - assert.exists(sessionFetch) - let signalBalanceRequested: () => void = () => {} - const balanceRequested = new Promise((resolve) => { - signalBalanceRequested = resolve - }) - let resolveBalance: (value: unknown) => void = () => {} - const balance = new Promise((resolve) => { - resolveBalance = resolve - }) - vi.mocked(fetch).mockImplementation(async (input, init) => { - const url = new URL(String(input), location.href) - if (url.pathname === '/api/auth/token') { - return jsonResponse({ - token: 'session-jwt-1', - expires_at: new Date(Date.now() + TEN_MINUTES_MS).toISOString(), - user_id: 'uid-1', - workspace: { - id: 'ws-personal', - name: 'Personal', - type: 'personal' - }, - role: 'owner', - permissions: [] - }) - } - if (url.pathname === '/customers/balance') { - signalBalanceRequested() - return fromPartial({ ok: true, json: () => balance }) - } - return sessionFetch(input, init) - }) - - const pending = authStore.fetchBalance() - await balanceRequested - identity.signIn(USER_B) - resolveBalance({ balance: 4242 }) - - await expect(pending).resolves.toBeNull() - expect(authStore.balance).toBeNull() - }) - it('signs out on the session alone', async () => { const { server, authStore } = await bootSessionOnly() diff --git a/src/platform/billing/components/settings/UsageLogsTable.test.ts b/src/platform/billing/components/settings/UsageLogsTable.test.ts index d84a9d098ad..32030102c35 100644 --- a/src/platform/billing/components/settings/UsageLogsTable.test.ts +++ b/src/platform/billing/components/settings/UsageLogsTable.test.ts @@ -1,6 +1,6 @@ import { getActivePinia } from 'pinia' import { assert, beforeEach, describe, expect, it, vi } from 'vitest' -import { computed, nextTick, ref } from 'vue' +import { computed, defineComponent, h, nextTick, reactive, ref } from 'vue' import userEvent from '@testing-library/user-event' import { render, screen, waitFor } from '@testing-library/vue' @@ -16,7 +16,8 @@ import { useTelemetry } from '@comfyorg/telemetry' import type { BillingEventsResponse } from '@comfyorg/billing-core' import { billingApi } from '@/platform/billing/api/billingApi' import type { BillingReadRail } from '@/platform/billing/composables/useBillingReadRail' -import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity' +import type { WorkspaceIdentityAccess } from '@/platform/workspace/ports/workspaceIdentity' import UsageLogsTable from './UsageLogsTable.vue' @@ -24,6 +25,8 @@ vi.mock(import('@/services/customerEventsService')) vi.mock(import('@comfyorg/telemetry')) +vi.mock(import('@/platform/workspace/ports/workspaceIdentity')) + const CONFIRMED_AT_MS = Date.parse('2024-06-15T12:30:00Z') const mockPendingTopup = vi.hoisted(() => ({ @@ -83,6 +86,11 @@ function makeEventsResponse( } describe('UsageLogsTable', () => { + let workspaceIdentity: WorkspaceIdentityAccess & { + initSettled: boolean + activeWorkspaceId: string | null + } + const mockEventsResponse = makeEventsResponse([ { event_id: 'event-1', @@ -106,10 +114,17 @@ describe('UsageLogsTable', () => { ]) beforeEach(() => { - setWorkspaceBilling(false) - vi.when(useCustomerEventsService().getMyEvents) - .calledWith({ page: 1, limit: 7 }) - .thenResolve(mockEventsResponse) + workspaceIdentity = reactive({ + workspaces: [], + activeWorkspace: null as WorkspaceIdentityAccess['activeWorkspace'], + activeWorkspaceId: null as string | null, + initSettled: false, + isInPersonalWorkspace: false, + workspaceTransitionGeneration: 0, + identityGeneration: 0 + }) + vi.mocked(useWorkspaceIdentity).mockReturnValue(workspaceIdentity) + setWorkspaceBilling(true) vi.mocked(billingApi.getBillingEvents).mockResolvedValue(mockEventsResponse) mockBillingReadRail.readEvents.mockResolvedValue({ status: 'ok', @@ -138,41 +153,80 @@ describe('UsageLogsTable', () => { it('loads activity on mount without an external refresh', async () => { await renderLoaded() - expect(useCustomerEventsService().getMyEvents).toHaveBeenCalledTimes(1) + expect(billingApi.getBillingEvents).toHaveBeenCalledTimes(1) }) - it('loads activity on mount on the workspace billing rail', async () => { - setWorkspaceBilling(true) + it('loads nothing until workspace routing is known', async () => { + const workspaceBilling = ref(false) + useBillingRouting().shouldUseWorkspaceBilling = computed( + () => workspaceBilling.value + ) - await renderLoaded() + renderComponent() + await flushMicrotasks() + + expect(billingApi.getBillingEvents).not.toHaveBeenCalled() + expect(screen.getByRole('progressbar')).toBeInTheDocument() + workspaceBilling.value = true + + await waitFor(() => { + expect(screen.getByRole('table')).toBeInTheDocument() + }) expect(billingApi.getBillingEvents).toHaveBeenCalledTimes(1) }) - it('shows a loading spinner while the initial load is in flight', () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockReturnValue( - new Promise(() => {}) + it('reads nothing when a parent refreshes while routing is unknown', async () => { + setWorkspaceBilling(false) + const table = ref>() + render( + defineComponent({ + setup: () => () => h(UsageLogsTable, { ref: table }) + }), + { global: { plugins: [testI18n, getActivePinia()!] } } ) + await flushMicrotasks() - renderComponent() + assert.exists(table.value) + await table.value.refresh() + expect(billingApi.getBillingEvents).not.toHaveBeenCalled() expect(screen.getByRole('progressbar')).toBeInTheDocument() - expect(screen.queryByRole('table')).not.toBeInTheDocument() + expect( + screen.queryByText('Failed to load activity. Please try again.') + ).not.toBeInTheDocument() }) - it('shows error message when service returns null', async () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValue(null) - useCustomerEventsService().error.value = 'Failed to load events' + it('shows the load error once workspace init has settled with no workspace', async () => { + setWorkspaceBilling(false) renderComponent() + await flushMicrotasks() + expect(screen.getByRole('progressbar')).toBeInTheDocument() + + workspaceIdentity.initSettled = true await waitFor(() => { - expect(screen.getByText('Failed to load events')).toBeInTheDocument() + expect( + screen.getByText('Failed to load activity. Please try again.') + ).toBeInTheDocument() }) + expect(billingApi.getBillingEvents).not.toHaveBeenCalled() + }) + + it('shows a loading spinner while the initial load is in flight', () => { + vi.mocked(billingApi.getBillingEvents).mockReturnValue( + new Promise(() => {}) + ) + + renderComponent() + + expect(screen.getByRole('progressbar')).toBeInTheDocument() + expect(screen.queryByRole('table')).not.toBeInTheDocument() }) it('shows a localized fallback instead of a raw Error message', async () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockRejectedValue( + vi.mocked(billingApi.getBillingEvents).mockRejectedValue( new Error('Network error') ) @@ -188,9 +242,8 @@ describe('UsageLogsTable', () => { expect(screen.queryByText('Network error')).not.toBeInTheDocument() }) - it('shows a localized fallback when the service reports no message', async () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValue(null) - useCustomerEventsService().error.value = null + it('shows a localized fallback when the read returns nothing', async () => { + vi.mocked(billingApi.getBillingEvents).mockResolvedValue(null as never) renderComponent() @@ -202,7 +255,7 @@ describe('UsageLogsTable', () => { }) it('shows data table without a paginator when one page holds every event', async () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValue( + vi.mocked(billingApi.getBillingEvents).mockResolvedValue( makeEventsResponse(mockEventsResponse.events, { total: 7 }) ) @@ -225,7 +278,7 @@ describe('UsageLogsTable', () => { it.for([1000, '1000'])( 'renders credit added details with the formatted amount %j', async (amount) => { - vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValue( + vi.mocked(billingApi.getBillingEvents).mockResolvedValue( makeEventsResponse([ { event_id: 'event-1', @@ -253,7 +306,7 @@ describe('UsageLogsTable', () => { }) it('renders account created details', async () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValue( + vi.mocked(billingApi.getBillingEvents).mockResolvedValue( makeEventsResponse([ { event_id: 'event-3', @@ -307,7 +360,7 @@ describe('UsageLogsTable', () => { }) it('keeps params outside the allowlist out of the tooltip', async () => { - vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValue( + vi.mocked(billingApi.getBillingEvents).mockResolvedValue( makeEventsResponse([ { event_id: 'event-4', @@ -347,28 +400,10 @@ describe('UsageLogsTable', () => { }) describe('pagination', () => { - it('calls getMyEvents with initial page params', async () => { - await renderLoaded() - - expect(useCustomerEventsService().getMyEvents).toHaveBeenCalledWith({ - page: 1, - limit: 7 - }) - }) - const pagedResponse = (page?: number) => makeEventsResponse(mockEventsResponse.events, { page, total: 20 }) it.for([ - { - workspaceBilling: false, - rail: false, - source: 'getMyEvents', - mockReader: () => - vi - .mocked(useCustomerEventsService().getMyEvents) - .mockImplementation(async (params) => pagedResponse(params?.page)) - }, { workspaceBilling: true, rail: false, @@ -413,52 +448,52 @@ describe('UsageLogsTable', () => { describe('billing events source', () => { it('uses billingApi.getBillingEvents on the workspace billing flow', async () => { - setWorkspaceBilling(true) - await renderLoaded() expect(billingApi.getBillingEvents).toHaveBeenCalledWith({ page: 1, limit: 7 }) - expect(useCustomerEventsService().getMyEvents).not.toHaveBeenCalled() }) - it('discards a stale legacy response when routing flips mid-fetch', async () => { - const workspaceBilling = ref(false) + it('discards a stale response when routing flips mid-fetch', async () => { + const workspaceBilling = ref(true) useBillingRouting().shouldUseWorkspaceBilling = computed( () => workspaceBilling.value ) - let resolveLegacy!: (value: ReturnType) => void - vi.mocked(useCustomerEventsService().getMyEvents).mockReturnValue( - new Promise((resolve) => { - resolveLegacy = resolve - }) - ) - vi.mocked(billingApi.getBillingEvents).mockResolvedValue( - makeEventsResponse([ - { - event_id: 'workspace-1', - event_type: EventType.API_USAGE_COMPLETED, - params: { api_name: 'WorkspaceAPI', model: 'workspace-model' }, - createdAt: '2024-02-01T10:00:00Z' - } - ]) - ) + let resolveStale!: (value: ReturnType) => void + vi.mocked(billingApi.getBillingEvents) + .mockReturnValueOnce( + new Promise((resolve) => { + resolveStale = resolve + }) + ) + .mockResolvedValue( + makeEventsResponse([ + { + event_id: 'workspace-1', + event_type: EventType.API_USAGE_COMPLETED, + params: { api_name: 'WorkspaceAPI', model: 'workspace-model' }, + createdAt: '2024-02-01T10:00:00Z' + } + ]) + ) renderComponent() + workspaceBilling.value = false + await nextTick() workspaceBilling.value = true await waitFor(() => { expect(screen.getByText('WorkspaceAPI')).toBeInTheDocument() }) - resolveLegacy( + resolveStale( makeEventsResponse([ { - event_id: 'legacy-1', + event_id: 'stale-1', event_type: EventType.API_USAGE_COMPLETED, - params: { api_name: 'LegacyAPI', model: 'legacy-model' }, + params: { api_name: 'StaleAPI', model: 'stale-model' }, createdAt: '2024-01-01T10:00:00Z' } ]) @@ -467,54 +502,57 @@ describe('UsageLogsTable', () => { await flushMicrotasks() expect(screen.getByText('WorkspaceAPI')).toBeInTheDocument() - expect(screen.queryByText('LegacyAPI')).not.toBeInTheDocument() + expect(screen.queryByText('StaleAPI')).not.toBeInTheDocument() }) it('runs top-up completion telemetry for a superseded response', async () => { - const workspaceBilling = ref(false) + const workspaceBilling = ref(true) useBillingRouting().shouldUseWorkspaceBilling = computed( () => workspaceBilling.value ) mockPendingTopup.consumeCompletedTopup.mockReturnValue({ startedAtMs: Date.now() }) - let resolveLegacy!: (value: ReturnType) => void - vi.mocked(useCustomerEventsService().getMyEvents).mockReturnValue( - new Promise((resolve) => { - resolveLegacy = resolve - }) - ) - vi.mocked(billingApi.getBillingEvents).mockResolvedValue( - makeEventsResponse([ - { - event_id: 'workspace-1', - event_type: EventType.API_USAGE_COMPLETED, - params: { api_name: 'WorkspaceAPI', model: 'workspace-model' }, - createdAt: '2024-02-01T10:00:00Z' - } - ]) - ) + let resolveStale!: (value: ReturnType) => void + vi.mocked(billingApi.getBillingEvents) + .mockReturnValueOnce( + new Promise((resolve) => { + resolveStale = resolve + }) + ) + .mockResolvedValue( + makeEventsResponse([ + { + event_id: 'workspace-1', + event_type: EventType.API_USAGE_COMPLETED, + params: { api_name: 'WorkspaceAPI', model: 'workspace-model' }, + createdAt: '2024-02-01T10:00:00Z' + } + ]) + ) renderComponent() + workspaceBilling.value = false + await nextTick() workspaceBilling.value = true await waitFor(() => { expect(screen.getByText('WorkspaceAPI')).toBeInTheDocument() }) - const legacyResponse = makeEventsResponse([ + const staleResponse = makeEventsResponse([ { - event_id: 'legacy-1', + event_id: 'stale-1', event_type: EventType.CREDIT_ADDED, params: { amount: 1000 }, createdAt: '2024-01-01T10:00:00Z' } ]) - resolveLegacy(legacyResponse) + resolveStale(staleResponse) await waitFor(() => { expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith( - legacyResponse.events + staleResponse.events ) expect(useTelemetry()?.trackApiCreditTopupSucceeded).toHaveBeenCalled() }) @@ -522,7 +560,7 @@ describe('UsageLogsTable', () => { it.for([ { - name: 'a completed legacy top-up closes as succeeded, measured from its start', + name: 'a completed top-up closes as succeeded, measured from its start', completedTopup: { startedAtMs: CONFIRMED_AT_MS - 90_000 }, expectedEvents: [ [ @@ -584,7 +622,6 @@ describe('UsageLogsTable', () => { ) const readers = { - legacy: () => useCustomerEventsService().getMyEvents, workspaceApi: () => billingApi.getBillingEvents, rail: () => mockBillingReadRail.readEvents } @@ -601,8 +638,6 @@ describe('UsageLogsTable', () => { } it.for([ - { workspaceBilling: false, rail: false, serves: 'legacy' }, - { workspaceBilling: false, rail: true, serves: 'legacy' }, { workspaceBilling: true, rail: false, serves: 'workspaceApi' }, { workspaceBilling: true, rail: true, serves: 'rail' } ] as const)( @@ -620,7 +655,7 @@ describe('UsageLogsTable', () => { } ) - it('renders the reader page the way the legacy rail renders its own', async () => { + it('renders the reader page', async () => { onTheRail() await renderLoaded() @@ -677,7 +712,7 @@ describe('UsageLogsTable', () => { // of the workspace being left stayed on screen. it('reloads and drops the rows when the active workspace changes', async () => { onTheRail() - Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-1' }) + workspaceIdentity.activeWorkspaceId = 'ws-1' await renderLoaded() expect(screen.getByText('RailAPI')).toBeInTheDocument() @@ -686,7 +721,7 @@ describe('UsageLogsTable', () => { status: 'ok', value: { events: [], page: 1, limit: 7, total: 0, totalPages: 0 } }) - Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-2' }) + workspaceIdentity.activeWorkspaceId = 'ws-2' await waitFor(() => { expect(screen.queryByText('RailAPI')).not.toBeInTheDocument() diff --git a/src/platform/billing/components/settings/UsageLogsTable.vue b/src/platform/billing/components/settings/UsageLogsTable.vue index d59c7147063..e9313fa745f 100644 --- a/src/platform/billing/components/settings/UsageLogsTable.vue +++ b/src/platform/billing/components/settings/UsageLogsTable.vue @@ -87,7 +87,7 @@ diff --git a/src/platform/billing/subscription/components/PricingTable.test.ts b/src/platform/billing/subscription/components/PricingTable.test.ts deleted file mode 100644 index c5d4f4b020e..00000000000 --- a/src/platform/billing/subscription/components/PricingTable.test.ts +++ /dev/null @@ -1,737 +0,0 @@ -import { AuthStoreError, useAuthStore } from '@/stores/authStore' -import { render, screen } from '@testing-library/vue' -import userEvent from '@testing-library/user-event' -import { assert, beforeEach, describe, expect, it, vi } from 'vitest' -import { computed, nextTick, ref } from 'vue' -import { createI18n } from 'vue-i18n' - -import { useBillingContext } from '@/platform/billing/composables/useBillingContext' -import { useErrorHandling } from '@/composables/useErrorHandling' -import { useTelemetry } from '@comfyorg/telemetry' -import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' -import PricingTable from '@/platform/billing/subscription/components/PricingTable.vue' -import Button from '@comfyorg/design-system/button/Button' -import type { IngestSubscriptionTier } from '@/platform/billing/subscription/constants/tierPricing' -import { PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY } from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker' - -async function flushPromises() { - await new Promise((r) => setTimeout(r, 0)) -} - -function createDeferredPromise() { - let resolve!: (value: T) => void - const promise = new Promise((res) => { - resolve = res - }) - - return { promise, resolve } -} - -type BillingPortalResponse = Awaited< - ReturnType['accessBillingPortal']> -> - -const billingPortal: BillingPortalResponse = { - billing_portal_url: 'https://billing.stripe.com/p/session' -} - -const mockCanAccessSubscriptionFeatures = ref(false) -const mockSubscriptionTier = ref(null) -const mockSubscriptionDuration = ref<'MONTHLY' | 'ANNUAL'>('MONTHLY') - -const mockGetCheckoutAttribution = vi.hoisted(() => vi.fn(() => ({}))) -const mockLocalStorage = vi.hoisted(() => { - const store = new Map() - - return { - getItem: vi.fn((key: string) => store.get(key) ?? null), - setItem: vi.fn((key: string, value: string) => { - store.set(key, value) - }), - removeItem: vi.fn((key: string) => { - store.delete(key) - }), - clear: vi.fn(() => { - store.clear() - }), - __reset: () => { - store.clear() - } - } -}) - -Object.defineProperty(window, 'localStorage', { - value: mockLocalStorage, - writable: true -}) - -Object.defineProperty(globalThis, 'localStorage', { - value: mockLocalStorage, - writable: true -}) - -vi.mock(import('@/platform/billing/composables/useBillingContext')) - -vi.mock(import('@/composables/useErrorHandling')) - -vi.mock(import('@comfyorg/telemetry')) - -vi.mock( - import('@/platform/telemetry/utils/checkoutAttribution'), - () => ({ - getCheckoutAttribution: mockGetCheckoutAttribution - }) -) - -vi.mock(import('@/platform/distribution/types'), () => ({ - isCloud: true -})) - -const i18n = createI18n({ - legacy: false, - locale: 'en', - messages: { - en: { - subscription: { - yearly: 'Yearly', - monthly: 'Monthly', - mostPopular: 'Most Popular', - usdPerMonth: '/ month', - billedYearly: 'Billed yearly ({total})', - billedMonthly: 'Billed monthly', - currentPlan: 'Current Plan', - subscribeTo: 'Subscribe to {plan}', - changeTo: 'Change to {plan}', - tierNameYearly: '{name} Yearly', - yearlyCreditsLabel: 'Total yearly credits', - monthlyCreditsLabel: 'Monthly credits', - maxDurationLabel: 'Max duration', - gpuLabel: 'GPU', - addCreditsLabel: 'Add more credits', - customLoRAsLabel: 'Custom LoRAs', - videoEstimateLabel: 'Video estimate', - videoEstimateHelp: 'How is this calculated?', - videoEstimateExplanation: 'Based on average usage.', - videoEstimateTryTemplate: 'Try template', - soloUseOnly: 'Solo use only', - needTeamWorkspace: 'Need team workspace?', - maxDuration: { - standard: '30 min', - creator: '30 min', - pro: '1 hr' - }, - tiers: { - standard: { name: 'Standard' }, - creator: { name: 'Creator' }, - pro: { name: 'Pro' } - }, - benefits: { - monthlyCredits: '{credits} monthly credits', - maxDuration: '{duration} max duration', - gpu: 'RTX 6000 Pro GPU', - addCredits: 'Add more credits anytime', - customLoRAs: 'Import custom LoRAs' - } - } - } - } -}) - -function renderComponent() { - return render(PricingTable, { - props: { - onChooseTeamWorkspace: onChooseTeamWorkspace - }, - global: { - plugins: [i18n], - components: { - Button - } - } - }) -} - -const onChooseTeamWorkspace = vi.fn() - -beforeEach(() => { - useErrorHandling().wrapWithErrorHandlingAsync = - (action, errorHandler) => - async (...args) => { - try { - return await action(...args) - } catch (error) { - errorHandler?.(error) - } - } - const billing = useBillingContext() - billing.canAccessSubscriptionFeatures = computed( - () => mockCanAccessSubscriptionFeatures.value - ) - billing.isFreeTier = computed(() => mockSubscriptionTier.value === 'FREE') - billing.tier = computed(() => mockSubscriptionTier.value) - billing.subscription = computed(() => - mockSubscriptionTier.value - ? { - isActive: mockCanAccessSubscriptionFeatures.value, - tier: mockSubscriptionTier.value, - duration: mockSubscriptionDuration.value, - planSlug: null, - scheduledChange: null, - renewalDate: null, - endDate: null, - isCancelled: false, - hasFunds: true, - agentHasFunds: true - } - : null - ) - vi.mocked(useBillingContext).mockReturnValue(billing) - Object.assign(useAuthStore(), { userId: 'user-123' }) - vi.mocked(useAuthStore().getFirebaseAuthHeader).mockResolvedValue({ - Authorization: 'Bearer test-token' as const - }) - vi.mocked(useAuthStore().fetchWithCustomerRecovery).mockImplementation( - (input, init) => fetch(input, init) - ) - vi.mocked(useAuthStore().accessBillingPortal).mockResolvedValue(billingPortal) - vi.spyOn(window, 'open').mockImplementation(() => window) -}) - -describe('PricingTable', () => { - beforeEach(() => { - mockCanAccessSubscriptionFeatures.value = false - mockSubscriptionTier.value = null - mockSubscriptionDuration.value = 'MONTHLY' - Object.assign(useAuthStore(), { userId: 'user-123' }) - Object.assign(useTeamWorkspaceStore(), { - activeWorkspaceId: 'workspace-123' - }) - mockLocalStorage.__reset() - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: 'https://checkout.stripe.com/test' }) - } as Response) - }) - - describe('billing portal deep linking', () => { - it('should call accessBillingPortal with yearly tier suffix when billing cycle is yearly (default)', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'STANDARD' - - renderComponent() - await flushPromises() - - const creatorButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Creator')) - - expect(creatorButton).toBeDefined() - await userEvent.click(creatorButton!) - await flushPromises() - - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith({ - user_id: 'user-123', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change', - checkout_attempt_id: expect.any(String), - previous_tier: 'standard' - }) - expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( - 'creator-yearly', - undefined - ) - }) - - it('should call accessBillingPortal with different tiers correctly', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'STANDARD' - - renderComponent() - await flushPromises() - - const proButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Pro')) - - await userEvent.click(proButton!) - await flushPromises() - - expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( - 'pro-yearly', - undefined - ) - }) - - it('records the plan snapshot that was actually opened', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'STANDARD' - - const portalOpen = createDeferredPromise() - vi.mocked(useAuthStore().accessBillingPortal).mockReturnValueOnce( - portalOpen.promise - ) - - renderComponent() - await flushPromises() - - const creatorButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Creator')) - - await userEvent.click(creatorButton!) - await flushPromises() - - const monthlyToggle = screen.getByRole('button', { name: 'Monthly' }) - await userEvent.click(monthlyToggle) - await flushPromises() - - portalOpen.resolve(billingPortal) - await flushPromises() - - expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( - 'creator-yearly', - undefined - ) - expect( - JSON.parse( - window.localStorage.getItem( - PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY - ) ?? '{}' - ) - ).toMatchObject({ - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change', - previous_tier: 'standard', - previous_cycle: 'monthly' - }) - }) - - it('keeps the initiating account and workspace while the portal opens', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'STANDARD' - Object.assign(useAuthStore(), { userId: 'user-early' }) - Object.assign(useTeamWorkspaceStore(), { - activeWorkspaceId: 'workspace-early' - }) - const portalOpen = createDeferredPromise() - vi.mocked(useAuthStore().accessBillingPortal).mockReturnValueOnce( - portalOpen.promise - ) - - renderComponent() - await flushPromises() - - const creatorButton = screen - .getAllByRole('button') - .find((button) => button.textContent.includes('Creator')) - await userEvent.click(creatorButton!) - await flushPromises() - - Object.assign(useAuthStore(), { userId: 'user-late' }) - Object.assign(useTeamWorkspaceStore(), { - activeWorkspaceId: 'workspace-late' - }) - portalOpen.resolve(billingPortal) - await flushPromises() - - expect( - JSON.parse( - window.localStorage.getItem( - PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY - ) ?? '{}' - ) - ).toMatchObject({ - owner_id: 'user-early', - workspace_id: 'workspace-early' - }) - }) - - it('does not record a pending upgrade when the billing portal does not open', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'STANDARD' - vi.spyOn(window, 'open').mockImplementation(() => null) - - renderComponent() - await flushPromises() - - const creatorButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Creator')) - - await userEvent.click(creatorButton!) - await flushPromises() - - expect( - window.localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) - ).toBeNull() - expect(useTelemetry()?.trackBeginCheckout).not.toHaveBeenCalled() - }) - - it('should use the latest userId value when it changes after mount', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'STANDARD' - Object.assign(useAuthStore(), { userId: 'user-early' }) - - renderComponent() - await flushPromises() - - Object.assign(useAuthStore(), { userId: 'user-late' }) - - const creatorButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Creator')) - - await userEvent.click(creatorButton!) - await flushPromises() - - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledTimes(1) - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith({ - user_id: 'user-late', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change', - checkout_attempt_id: expect.any(String), - previous_tier: 'standard' - }) - }) - - it('should not call accessBillingPortal when clicking current plan', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'CREATOR' - mockSubscriptionDuration.value = 'ANNUAL' - - renderComponent() - await flushPromises() - - const currentPlanButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Current Plan')) - - expect(currentPlanButton).toBeDefined() - expect(currentPlanButton).toBeDisabled() - await userEvent.click(currentPlanButton!) - await flushPromises() - - expect(useAuthStore().accessBillingPortal).not.toHaveBeenCalled() - }) - - it('does not highlight a current plan when the facade duration differs from the selected cycle', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'CREATOR' - mockSubscriptionDuration.value = 'MONTHLY' - - renderComponent() - await flushPromises() - - const currentPlanButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Current Plan')) - - expect(currentPlanButton).toBeUndefined() - }) - - it('should initiate checkout instead of billing portal for new subscribers', async () => { - mockCanAccessSubscriptionFeatures.value = false - - const windowOpenSpy = vi - .spyOn(window, 'open') - .mockImplementation(() => null) - - renderComponent() - await flushPromises() - - const subscribeButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Subscribe')) - - await userEvent.click(subscribeButton!) - await flushPromises() - - expect(useAuthStore().accessBillingPortal).not.toHaveBeenCalled() - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-checkout/'), - expect.any(Object) - ) - expect(windowOpenSpy).toHaveBeenCalledWith( - 'https://checkout.stripe.com/test', - '_blank' - ) - - windowOpenSpy.mockRestore() - }) - - it('tracks and rethrows a subscription checkout failure for new subscribers', async () => { - mockCanAccessSubscriptionFeatures.value = false - vi.mocked(global.fetch).mockResolvedValue({ - ok: false, - status: 400, - statusText: 'Bad Request', - json: async () => ({ message: 'declined for person@example.com' }), - text: async () => '' - } as Response) - - renderComponent() - await flushPromises() - - const subscribeButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Subscribe')) - - await userEvent.click(subscribeButton!) - await flushPromises() - - expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ - operation: 'subscription_checkout', - stage: 'failed', - outcome: 'failure', - tier: 'standard', - cycle: 'yearly', - checkout_type: 'new', - payment_intent_source: undefined, - checkout_attempt_id: expect.any(String), - failure_category: 'api_rejected', - duration_ms: expect.any(Number) - }) - expect(useErrorHandling().toastErrorHandler).toHaveBeenCalled() - }) - - it('categorizes a connectivity failure as network, not api_rejected', async () => { - mockCanAccessSubscriptionFeatures.value = false - vi.mocked(global.fetch).mockRejectedValue( - new TypeError('Failed to fetch') - ) - - renderComponent() - await flushPromises() - - const subscribeButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Subscribe')) - - await userEvent.click(subscribeButton!) - await flushPromises() - - expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith( - expect.objectContaining({ failure_category: 'network' }) - ) - }) - - it('should pass correct tier for each subscription level', async () => { - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = 'PRO' - - renderComponent() - await flushPromises() - - const standardButton = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Standard')) - - await userEvent.click(standardButton!) - await flushPromises() - - expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( - 'standard-yearly', - undefined - ) - }) - - it.for([ - { - name: 'the portal opens and the attempt waits for its success', - currentTier: 'STANDARD', - currentDuration: 'MONTHLY', - target: 'Creator', - portal: () => Promise.resolve(billingPortal), - openedWindow: window, - expectedEvents: [ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000006', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change' - } - ] - ], - storedAttempt: expect.objectContaining({ - attempt_id: '00000000-0000-4000-8000-000000000006', - start_reported: true - }) - }, - { - name: 'the browser blocks the portal tab', - currentTier: 'STANDARD', - currentDuration: 'MONTHLY', - target: 'Creator', - portal: () => Promise.resolve(billingPortal), - openedWindow: null, - expectedEvents: [ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000006', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'failed', - outcome: 'failure', - checkout_attempt_id: '00000000-0000-4000-8000-000000000006', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change', - failure_category: 'redirect', - error_code: 'payment_popup_blocked', - duration_ms: expect.any(Number) - } - ] - ], - storedAttempt: null - }, - { - name: 'the portal request is rejected', - currentTier: 'STANDARD', - currentDuration: 'MONTHLY', - target: 'Creator', - portal: () => - Promise.reject(new AuthStoreError('portal unavailable', 503)), - openedWindow: window, - expectedEvents: [ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000006', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'failed', - outcome: 'failure', - checkout_attempt_id: '00000000-0000-4000-8000-000000000006', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'change', - failure_category: 'api_rejected', - duration_ms: expect.any(Number) - } - ] - ], - storedAttempt: null - }, - { - name: 'a downgrade opens the plain portal and reports nothing', - currentTier: 'PRO', - currentDuration: 'ANNUAL', - target: 'Standard', - portal: () => Promise.resolve(billingPortal), - openedWindow: window, - expectedEvents: [], - storedAttempt: null - } - ] as const)( - 'reports a portal plan change attempt once: $name', - async ({ - currentTier, - currentDuration, - target, - portal, - openedWindow, - expectedEvents, - storedAttempt - }) => { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000006' - ) - mockCanAccessSubscriptionFeatures.value = true - mockSubscriptionTier.value = currentTier - mockSubscriptionDuration.value = currentDuration - vi.mocked(useAuthStore().accessBillingPortal).mockImplementation(portal) - vi.spyOn(window, 'open').mockImplementation(() => openedWindow) - - renderComponent() - await flushPromises() - const targetButton = screen - .getAllByRole('button') - .find((button) => button.textContent.includes(target)) - await userEvent.click(targetButton!) - await flushPromises() - - const telemetry = useTelemetry() - assert.exists(telemetry) - expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual( - expectedEvents - ) - expect( - JSON.parse( - window.localStorage.getItem( - PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY - ) ?? 'null' - ) - ).toEqual(storedAttempt) - } - ) - }) - - describe('credit allotment display', () => { - it('states the whole-year allotment and a matching video estimate on the yearly cycle', async () => { - renderComponent() - await flushPromises() - - expect(screen.getAllByText('Total yearly credits')).toHaveLength(3) - expect(screen.getByText('50,400')).toBeTruthy() - expect(screen.getByText('~4,560')).toBeTruthy() - expect(screen.getByText('253,200')).toBeTruthy() - expect(screen.getByText('~22,980')).toBeTruthy() - }) - - it('keeps the monthly allotment when Monthly is selected again', async () => { - renderComponent() - await flushPromises() - - const monthly = screen.getByRole('button', { name: 'Monthly' }) - await userEvent.click(monthly) - await userEvent.click(monthly) - await nextTick() - - expect(monthly).toHaveAttribute('aria-pressed', 'true') - expect(screen.getAllByText('Monthly credits')).toHaveLength(3) - expect(screen.getByText('4,200')).toBeTruthy() - expect(screen.getByText('~380')).toBeTruthy() - }) - }) - - describe('team workspace link', () => { - it('should emit chooseTeamWorkspace when clicking "Need team workspace?" link', async () => { - renderComponent() - await flushPromises() - - const teamLink = screen - .getAllByRole('button') - .find((b) => b.textContent.includes('Need team workspace?')) - - expect(teamLink).toBeDefined() - await userEvent.click(teamLink!) - - expect(onChooseTeamWorkspace).toHaveBeenCalledOnce() - }) - }) -}) -vi.mock(import('firebase/auth')) diff --git a/src/platform/billing/subscription/components/PricingTable.vue b/src/platform/billing/subscription/components/PricingTable.vue deleted file mode 100644 index e100cbd81a6..00000000000 --- a/src/platform/billing/subscription/components/PricingTable.vue +++ /dev/null @@ -1,526 +0,0 @@ - - - diff --git a/src/platform/billing/subscription/components/SubscriptionBenefits.vue b/src/platform/billing/subscription/components/SubscriptionBenefits.vue deleted file mode 100644 index edfa6cc2211..00000000000 --- a/src/platform/billing/subscription/components/SubscriptionBenefits.vue +++ /dev/null @@ -1,34 +0,0 @@ - - - diff --git a/src/platform/billing/subscription/components/SubscriptionRequiredDialogContent.test.ts b/src/platform/billing/subscription/components/SubscriptionRequiredDialogContent.test.ts deleted file mode 100644 index bbf5ce8776c..00000000000 --- a/src/platform/billing/subscription/components/SubscriptionRequiredDialogContent.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { render, screen } from '@testing-library/vue' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createI18n } from 'vue-i18n' - -import GlobalDialog from '@/components/dialog/GlobalDialog.vue' -import type { PaymentIntentSource } from '@comfyorg/telemetry/types' -import { useDialogStore } from '@/stores/dialogStore' - -import SubscriptionRequiredDialogContent from './SubscriptionRequiredDialogContent.vue' - -vi.mock(import('@/platform/billing/composables/useBillingContext')) -vi.mock(import('@comfyorg/telemetry')) - -vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) - -const i18n = createI18n({ - legacy: false, - locale: 'en', - messages: { - en: { - g: { close: 'Close', or: 'or' }, - credits: { - topUp: { - insufficientTitle: 'Insufficient Credits', - insufficientMessage: 'You are out of credits' - } - }, - subscription: { - required: { title: 'Subscription required' }, - plansForWorkspace: 'Plans for {workspace}', - personalWorkspace: 'Personal', - perMonth: 'per month', - haveQuestions: 'Questions?', - contactUs: 'Contact us', - viewEnterprise: 'View enterprise' - } - } - } -}) - -const PricingTableStub = { - name: 'PricingTable', - props: ['reason'], - template: '
{{ reason ?? "none" }}
' -} - -const stubs = { - CreditsLockedNotice: { - template: '
' - }, - PricingTable: PricingTableStub, - CloudBadge: { template: '
' }, - SubscribeButton: { template: '
' }, - SubscriptionBenefits: { template: '
' } -} - -function renderComponent(props: { - reason?: PaymentIntentSource - paymentIntentSource: PaymentIntentSource | undefined - creditsLocked?: boolean -}) { - return render(SubscriptionRequiredDialogContent, { - props: { onClose: vi.fn(), ...props }, - global: { - plugins: [i18n], - stubs - } - }) -} - -describe('SubscriptionRequiredDialogContent', () => { - const originalConfig = window.__CONFIG__ - - beforeEach(() => { - window.__CONFIG__ = { subscription_required: true } - }) - - afterEach(() => { - window.__CONFIG__ = originalConfig - }) - - it('gives the pricing table the source, not the copy reason', () => { - renderComponent({ - reason: 'out_of_credits', - paymentIntentSource: 'agent_paywall' - }) - - expect(screen.getByTestId('pricing-table')).toHaveTextContent( - 'agent_paywall' - ) - }) - - it('explains locked credits above the pricing table', () => { - renderComponent({ paymentIntentSource: undefined, creditsLocked: true }) - - expect(screen.getByTestId('credits-locked-notice')).toBeInTheDocument() - }) - - it('names the legacy panel dialog by its reason-specific title', async () => { - window.__CONFIG__ = { subscription_required: false } - - render(GlobalDialog, { global: { plugins: [i18n], stubs } }) - useDialogStore().showDialog({ - key: 'subscription-required', - component: SubscriptionRequiredDialogContent, - props: { - onClose: vi.fn(), - reason: 'out_of_credits', - paymentIntentSource: 'agent_paywall' - }, - dialogComponentProps: { headless: true } - }) - - expect( - await screen.findByRole('dialog', { name: 'Insufficient Credits' }) - ).toBeInTheDocument() - expect(screen.queryByTestId('pricing-table')).not.toBeInTheDocument() - }) -}) diff --git a/src/platform/billing/subscription/components/SubscriptionRequiredDialogContent.vue b/src/platform/billing/subscription/components/SubscriptionRequiredDialogContent.vue deleted file mode 100644 index 2ad36d72bda..00000000000 --- a/src/platform/billing/subscription/components/SubscriptionRequiredDialogContent.vue +++ /dev/null @@ -1,249 +0,0 @@ - - - diff --git a/src/platform/billing/subscription/composables/__mocks__/useSubscription.ts b/src/platform/billing/subscription/composables/__mocks__/useSubscription.ts index 3b1816e9fd4..881629b53e6 100644 --- a/src/platform/billing/subscription/composables/__mocks__/useSubscription.ts +++ b/src/platform/billing/subscription/composables/__mocks__/useSubscription.ts @@ -22,14 +22,10 @@ function reactiveDefaults() { const subscription: ReturnType = { ...reactiveDefaults(), isSubscriptionEnabled: vi.fn(() => false), - subscribe: vi.fn(async () => {}), - subscribeDirect: vi.fn(async () => {}), fetchStatus: vi.fn(async () => undefined), fetchStatusDirect: vi.fn(async () => null), - manageSubscription: vi.fn(async () => {}), handleViewUsageHistory: vi.fn(), - handleLearnMore: vi.fn(), - handleInvoiceHistory: vi.fn(async () => {}) + handleLearnMore: vi.fn() } export const useSubscription = vi.fn(() => { diff --git a/src/platform/billing/subscription/composables/__mocks__/useSubscriptionDialog.ts b/src/platform/billing/subscription/composables/__mocks__/useSubscriptionDialog.ts index 73b9fbb7672..d198ae6c34b 100644 --- a/src/platform/billing/subscription/composables/__mocks__/useSubscriptionDialog.ts +++ b/src/platform/billing/subscription/composables/__mocks__/useSubscriptionDialog.ts @@ -8,7 +8,6 @@ const subscriptionDialog: ReturnType = { show: vi.fn(async () => true), showPricingTable: vi.fn(async () => true), hide: vi.fn(), - startTeamWorkspaceUpgradeFlow: vi.fn(), resumePendingPricingFlow: vi.fn(async () => {}) } diff --git a/src/platform/billing/subscription/composables/useSubscription.test.ts b/src/platform/billing/subscription/composables/useSubscription.test.ts index a8c0541b501..48bd166a5e8 100644 --- a/src/platform/billing/subscription/composables/useSubscription.test.ts +++ b/src/platform/billing/subscription/composables/useSubscription.test.ts @@ -1,12 +1,9 @@ import { useWorkspaceBillingStateStore } from '@/platform/billing/stores/workspaceBillingStateStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' -import { AuthStoreError, useAuthStore } from '@/stores/authStore' +import { useAuthStore } from '@/stores/authStore' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computed, effectScope, nextTick } from 'vue' -import { SessionTokenError } from '@comfyorg/account-core/sessionTokenMint' - -import { useAuthActions } from '@/composables/auth/useAuthActions' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useErrorHandling } from '@/composables/useErrorHandling' import { webSessionResourceHeader } from '@comfyorg/api-client/webSessionFetch' @@ -19,8 +16,6 @@ import { PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY, claimPendingCheckoutTerminal } from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker' -import { performSubscriptionCheckout } from '@/platform/billing/subscription/utils/subscriptionCheckoutUtil' -import { PaymentPopupBlockedError } from '@/platform/telemetry/utils/billingFailureCategory' const { mockGetCheckoutAttribution, @@ -34,8 +29,7 @@ const { mockLocalStorage, mockReportTelemetryError, - mockReportError, - mockAccessBillingPortalDirect + mockReportError } = await vi.hoisted(async () => { const { ref } = await import('vue') const mockIsLoggedIn = ref(false) @@ -48,7 +42,6 @@ const { mockReportTelemetryError: vi.fn(), mockReportError: vi.fn(), - mockAccessBillingPortalDirect: vi.fn(), mockGetCheckoutAttribution: vi.fn(() => ({ im_ref: 'impact-click-001', utm_source: 'impact' @@ -128,8 +121,7 @@ vi.mock(import('@comfyorg/telemetry/reportError'), () => ({ vi.mock(import('@/composables/auth/useAuthActions'), () => ({ useAuthActions: vi.fn(() => ({ - reportError: mockReportError, - accessBillingPortalDirect: mockAccessBillingPortalDirect + reportError: mockReportError })) })) @@ -239,10 +231,6 @@ beforeEach(() => { vi.mocked(useAuthStore().getFirebaseAuthHeader).mockResolvedValue({ Authorization: 'Bearer test-token' as const }) - vi.mocked(useAuthStore().fetchWithCustomerRecovery).mockImplementation( - (input, init) => fetch(input, init) - ) - mockAccessBillingPortalDirect.mockResolvedValue(true) }) describe('useSubscription', () => { @@ -752,267 +740,6 @@ describe('useSubscription', () => { }) }) - describe('subscribe', () => { - it('should initiate subscription checkout successfully', async () => { - const checkoutUrl = 'https://checkout.stripe.com/test' - - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - - // Mock window.open - const windowOpenSpy = vi - .spyOn(window, 'open') - .mockImplementation(() => window) - - const { subscribe } = useSubscriptionWithScope() - - await subscribe() - - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-checkout'), - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ - Authorization: 'Bearer test-token' as const, - 'Content-Type': 'application/json' - }), - body: JSON.stringify({ - im_ref: 'impact-click-001', - utm_source: 'impact' - }) - }) - ) - - expect(windowOpenSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') - expect( - JSON.parse( - localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) ?? - '{}' - ) - ).toMatchObject({ - tier: 'standard', - cycle: 'monthly', - checkout_type: 'new' - }) - - windowOpenSpy.mockRestore() - }) - - it('should throw error when checkout URL is not returned', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({}) - } as Response) - - const { subscribe } = useSubscriptionWithScope() - - await expect(subscribe()).rejects.toThrow() - }) - }) - - describe('subscribeDirect', () => { - it('performs the same checkout as subscribe on success', async () => { - const checkoutUrl = 'https://checkout.stripe.com/direct' - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - const windowOpenSpy = vi - .spyOn(window, 'open') - .mockImplementation(() => window) - - const { subscribeDirect } = useSubscriptionWithScope() - - await expect(subscribeDirect()).resolves.toBeUndefined() - expect(windowOpenSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') - - windowOpenSpy.mockRestore() - }) - - it('rejects on failure without going through the error-swallowing wrapper', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({}) - } as Response) - - const { subscribeDirect } = useSubscriptionWithScope() - - await expect(subscribeDirect()).rejects.toThrow() - expect(useAuthActions().reportError).not.toHaveBeenCalled() - }) - - it.for([ - { - name: 'no web session sends the Firebase header', - session: undefined, - authorization: 'Bearer test-token', - firebaseCalls: 1 - }, - { - name: 'a web session sends its own header instead', - session: { Authorization: 'Bearer session-jwt' }, - authorization: 'Bearer session-jwt', - firebaseCalls: 0 - } - ])( - 'authorizes the checkout: $name', - async ({ session, authorization, firebaseCalls }) => { - vi.mocked(webSessionResourceHeader).mockResolvedValue(session) - vi.mocked(global.fetch).mockResolvedValue( - new Response( - JSON.stringify({ checkout_url: 'https://checkout.stripe.com/x' }) - ) - ) - const windowOpenSpy = vi - .spyOn(window, 'open') - .mockImplementation(() => window) - - await useSubscriptionWithScope().subscribeDirect() - - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-checkout'), - expect.objectContaining({ - headers: { - Authorization: authorization, - 'Content-Type': 'application/json' - } - }) - ) - expect(useAuthStore().getFirebaseAuthHeader).toHaveBeenCalledTimes( - firebaseCalls - ) - windowOpenSpy.mockRestore() - } - ) - - it('rejects with the mint failure and sends no checkout request', async () => { - vi.mocked(webSessionResourceHeader).mockRejectedValue( - new SessionTokenError({ - status: 'error', - code: 'SESSION_REVOKED', - retryable: false - }) - ) - - await expect( - useSubscriptionWithScope().subscribeDirect() - ).rejects.toMatchObject({ - failure: { code: 'SESSION_REVOKED' } - }) - expect(global.fetch).not.toHaveBeenCalled() - }) - - it('tags the pending attempt as a resubscribe when called with operation/source', async () => { - const checkoutUrl = 'https://checkout.stripe.com/direct' - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - const windowOpenSpy = vi - .spyOn(window, 'open') - .mockImplementation(() => window) - - const { subscribeDirect } = useSubscriptionWithScope() - - await subscribeDirect({ - operation: 'resubscribe', - source: 'settings_billing_panel' - }) - - const stored = JSON.parse( - localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) ?? '{}' - ) - expect(stored.operation).toBe('resubscribe') - expect(stored.resubscribe_source).toBe('settings_billing_panel') - expect(stored.previous_cancel_at).toBeUndefined() - expect(stored.owner_id).toBe('user-123') - expect(stored.workspace_id).toBe('workspace-123') - - windowOpenSpy.mockRestore() - }) - - it.for([ - { - name: 'the checkout request is rejected', - checkoutResponse: () => - ({ - ok: false, - status: 400, - statusText: 'Bad Request', - json: async () => ({ message: 'declined' }), - text: async () => '' - }) as Response, - openedWindow: window, - rejection: 'Failed to initiate subscription', - failure: { failure_category: 'api_rejected' } - }, - { - name: 'no checkout URL comes back', - checkoutResponse: () => new Response(JSON.stringify({})), - openedWindow: window, - rejection: 'No checkout URL returned', - failure: { - failure_category: 'unknown', - error_code: 'missing_checkout_response' - } - }, - { - name: 'the browser blocks the checkout tab', - checkoutResponse: () => - new Response( - JSON.stringify({ checkout_url: 'https://checkout.stripe.com/x' }) - ), - openedWindow: null, - rejection: "Couldn't open the payment page", - failure: { - failure_category: 'redirect', - error_code: 'payment_popup_blocked' - } - } - ])( - 'closes a resubscribe checkout that never opened with one failure: $name', - async ({ checkoutResponse, openedWindow, rejection, failure }) => { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000005' - ) - vi.mocked(global.fetch).mockResolvedValue(checkoutResponse()) - vi.spyOn(window, 'open').mockImplementation(() => openedWindow) - - await expect( - useSubscriptionWithScope().subscribeDirect({ - operation: 'resubscribe', - source: 'settings_billing_panel' - }) - ).rejects.toThrow(rejection) - - const attemptEvent = { - operation: 'subscription_checkout', - checkout_attempt_id: '00000000-0000-4000-8000-000000000005', - tier: 'standard', - cycle: 'monthly', - checkout_type: 'new' - } - expect(mockTelemetry.trackBillingEvent.mock.calls).toEqual([ - [{ ...attemptEvent, stage: 'started', outcome: 'pending' }], - [ - { - ...attemptEvent, - stage: 'failed', - outcome: 'failure', - ...failure, - duration_ms: expect.any(Number) - } - ] - ]) - expect( - localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) - ).toBeNull() - } - ) - }) - describe('pending checkout recovery', () => { it('evicts a hung bootstrap read before retrying recovery', async () => { localStorage.setItem( @@ -2124,30 +1851,28 @@ describe('useSubscription', () => { ) }) - async function openCheckoutThenConfirm( - open: (subscription: ReturnType) => Promise, + async function confirmReportedCheckout( + attempt: Record, activeStatus: Partial ) { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000003' - ) - vi.spyOn(window, 'open').mockImplementation(() => window) - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: 'https://checkout.stripe.com/test' }) - } as Response) - useCurrentUser().isLoggedIn = computed(() => true) - const subscription = useSubscriptionWithScope() - await subscription.fetchStatus() - + localStorage.setItem( + PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY, + JSON.stringify({ + attempt_id: '00000000-0000-4000-8000-000000000003', + started_at_ms: Date.now(), + checkout_type: 'new', + start_reported: true, + ...attempt + }) + ) mockGetBillingStatus.mockResolvedValue({ is_active: true, has_funds: true, renewal_date: '2025-11-16', ...activeStatus }) - await open(subscription) - await subscription.fetchStatus() + useCurrentUser().isLoggedIn = computed(() => true) + useSubscriptionWithScope() await vi.waitFor(() => { expect( localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) @@ -2155,96 +1880,40 @@ describe('useSubscription', () => { }) } - it.for([ - { - name: 'performSubscriptionCheckout reported the start, so it closes with one success', - open: () => - performSubscriptionCheckout('creator', 'yearly', { - paymentIntentSource: 'out_of_credits' - }), - activeStatus: { - subscription_tier: 'CREATOR', - subscription_duration: 'ANNUAL' - } satisfies Partial, - expectedEvents: [ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000003', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'new', - payment_intent_source: 'out_of_credits' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'succeeded', - outcome: 'success', - checkout_attempt_id: '00000000-0000-4000-8000-000000000003', - tier: 'creator', - cycle: 'yearly', - checkout_type: 'new', - payment_intent_source: 'out_of_credits', - duration_ms: expect.any(Number) - } - ] - ] - }, - { - name: 'subscribeDirect reported the start, so it closes with one success', - open: (subscription: ReturnType) => - subscription.subscribeDirect(), - activeStatus: { - subscription_tier: 'STANDARD', - subscription_duration: 'MONTHLY' - } satisfies Partial, - expectedEvents: [ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000003', - tier: 'standard', - cycle: 'monthly', - checkout_type: 'new' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'succeeded', - outcome: 'success', - checkout_attempt_id: '00000000-0000-4000-8000-000000000003', - tier: 'standard', - cycle: 'monthly', - checkout_type: 'new', - duration_ms: expect.any(Number) - } - ] - ] - } - ])( - 'closes a confirmed checkout only in the funnel it opened: $name', - async ({ open, activeStatus, expectedEvents }) => { - await openCheckoutThenConfirm(open, activeStatus) + it('closes a confirmed checkout that reported its start with one success', async () => { + await confirmReportedCheckout( + { + tier: 'creator', + cycle: 'yearly', + payment_intent_source: 'out_of_credits' + }, + { subscription_tier: 'CREATOR', subscription_duration: 'ANNUAL' } + ) - expect(mockTelemetry.trackBillingEvent.mock.calls).toEqual( - expectedEvents - ) - } - ) + expect(mockTelemetry.trackBillingEvent.mock.calls).toEqual([ + [ + { + operation: 'subscription_checkout', + stage: 'succeeded', + outcome: 'success', + checkout_attempt_id: '00000000-0000-4000-8000-000000000003', + tier: 'creator', + cycle: 'yearly', + checkout_type: 'new', + payment_intent_source: 'out_of_credits', + duration_ms: expect.any(Number) + } + ] + ]) + }) it('keeps the start marker out of the monthly_subscription_succeeded payload', async () => { - await openCheckoutThenConfirm( - () => - performSubscriptionCheckout('creator', 'yearly', { - paymentIntentSource: 'out_of_credits' - }), + await confirmReportedCheckout( + { + tier: 'creator', + cycle: 'yearly', + payment_intent_source: 'out_of_credits' + }, { subscription_tier: 'CREATOR', subscription_duration: 'ANNUAL' } ) @@ -2738,264 +2407,6 @@ describe('useSubscription', () => { windowOpenSpy.mockRestore() }) - - it('should open the billing portal for invoice history', async () => { - const { handleInvoiceHistory } = useSubscriptionWithScope() - - await handleInvoiceHistory() - - expect(useAuthActions().accessBillingPortalDirect).toHaveBeenCalled() - }) - - it('should open the billing portal for manage subscription', async () => { - const { manageSubscription } = useSubscriptionWithScope() - - await manageSubscription() - - expect(useAuthActions().accessBillingPortalDirect).toHaveBeenCalled() - }) - - it('passes the cancel option to the portal only when asked', async () => { - const { manageSubscription, handleInvoiceHistory } = - useSubscriptionWithScope() - const open = vi.mocked(useAuthActions().accessBillingPortalDirect) - - await manageSubscription({ cancelSubscription: true }) - expect(open).toHaveBeenLastCalledWith(undefined, { - cancelSubscription: true - }) - - await manageSubscription() - expect(open).toHaveBeenLastCalledWith(undefined, undefined) - - await handleInvoiceHistory() - expect(open).toHaveBeenLastCalledWith(undefined, undefined) - }) - - describe('portal telemetry', () => { - type PortalAction = 'manageSubscription' | 'handleInvoiceHistory' - - function portalEvents() { - return mockTelemetry.trackBillingEvent.mock.calls - .map(([event]) => event) - .filter((event) => event.operation === 'portal') - } - - function leaveAndReturn() { - window.dispatchEvent(new Event('blur')) - window.dispatchEvent(new Event('focus')) - } - - it.for<{ action: PortalAction; target: string }>([ - { action: 'manageSubscription', target: 'manage_subscription' }, - { action: 'handleInvoiceHistory', target: 'invoices' } - ])( - 'reports $action opening the portal and one return', - async ({ action, target }) => { - await useSubscriptionWithScope()[action]() - leaveAndReturn() - leaveAndReturn() - - expect(portalEvents()).toEqual([ - { - operation: 'portal', - stage: 'opened', - outcome: 'pending', - target, - billing_client: 'legacy' - }, - { - operation: 'portal', - stage: 'returned', - outcome: 'pending', - target, - billing_client: 'legacy' - } - ]) - } - ) - - it.for<{ - action: PortalAction - target: string - settles: (run: Promise) => Promise - }>([ - { - action: 'manageSubscription', - target: 'manage_subscription', - settles: (run) => expect(run).rejects.toThrow() - }, - { - action: 'handleInvoiceHistory', - target: 'invoices', - settles: (run) => expect(run).resolves.toBeUndefined() - } - ])( - 'reports $action as a failed open when the tab is blocked', - async ({ action, target, settles }) => { - mockAccessBillingPortalDirect.mockResolvedValueOnce(false) - - await settles(useSubscriptionWithScope()[action]()) - leaveAndReturn() - - expect(portalEvents()).toEqual([ - { - operation: 'portal', - stage: 'failed', - outcome: 'failure', - target, - billing_client: 'legacy', - failure_category: 'redirect', - error_code: 'payment_popup_blocked' - } - ]) - } - ) - - it.for([ - { - name: 'a refused portal request', - failure: new AuthStoreError('Portal refused', 500), - category: { failure_category: 'api_rejected' } - }, - { - name: 'a rail-mismatch refusal', - failure: new AuthStoreError( - 'refused', - 409, - 'WORKSPACE_BILLING_REQUIRED' - ), - category: {} - } - ])( - 'reports $name as a failed open and rejects without reporting the error', - async ({ failure, category }) => { - mockAccessBillingPortalDirect.mockRejectedValueOnce(failure) - - await expect( - useSubscriptionWithScope().manageSubscription() - ).rejects.toBe(failure) - - expect(portalEvents()).toMatchObject([ - { - operation: 'portal', - stage: 'failed', - outcome: 'failure', - target: 'manage_subscription', - billing_client: 'legacy', - ...category - } - ]) - expect(mockReportError).not.toHaveBeenCalled() - } - ) - - it('rejects a blocked manage subscription tab with the blocked-tab message, without reporting it', async () => { - mockAccessBillingPortalDirect.mockResolvedValueOnce(false) - - await expect( - useSubscriptionWithScope().manageSubscription() - ).rejects.toEqual( - new PaymentPopupBlockedError( - "Couldn't open the billing page. Allow pop-ups for this site and try again." - ) - ) - expect(mockReportError).not.toHaveBeenCalled() - }) - }) - - it('does not start cancellation watching when the billing portal does not open', async () => { - useCurrentUser().isLoggedIn = computed(() => true) - mockAccessBillingPortalDirect.mockResolvedValueOnce(false) - - mockGetBillingStatus.mockResolvedValue({ - is_active: true, - has_funds: true, - renewal_date: '2025-11-16' - }) - - const { fetchStatus, manageSubscription } = useSubscriptionWithScope() - - await fetchStatus() - mockGetBillingStatus.mockClear() - - const blockedOpen = manageSubscription() - await expect(blockedOpen).rejects.toBeInstanceOf(PaymentPopupBlockedError) - await expect(blockedOpen).rejects.toThrow( - "Couldn't open the billing page. Allow pop-ups for this site and try again." - ) - await vi.advanceTimersByTimeAsync(5000) - - expect(mockGetBillingStatus).not.toHaveBeenCalled() - expect( - useTelemetry()?.trackMonthlySubscriptionCancelled - ).not.toHaveBeenCalled() - }) - - it('tracks cancellation after manage subscription when status flips', async () => { - useCurrentUser().isLoggedIn = computed(() => true) - - const activeStatus = { - is_active: true, - has_funds: true, - renewal_date: '2025-11-16' - } - - const cancelledStatus = { - is_active: false, - has_funds: true, - renewal_date: '2025-11-16', - cancel_at: '2025-12-01' - } - - mockGetBillingStatus - .mockResolvedValueOnce(activeStatus) - .mockResolvedValueOnce(cancelledStatus) - - const { fetchStatus, manageSubscription } = useSubscriptionWithScope() - - await fetchStatus() - await manageSubscription() - - await vi.advanceTimersByTimeAsync(5000) - - expect( - useTelemetry()?.trackMonthlySubscriptionCancelled - ).toHaveBeenCalledTimes(1) - }) - - it('handles rapid focus events during cancellation polling', async () => { - useCurrentUser().isLoggedIn = computed(() => true) - - const activeStatus = { - is_active: true, - has_funds: true, - renewal_date: '2025-11-16' - } - - const cancelledStatus = { - is_active: false, - has_funds: true, - renewal_date: '2025-11-16', - cancel_at: '2025-12-01' - } - - mockGetBillingStatus - .mockResolvedValueOnce(activeStatus) - .mockResolvedValueOnce(cancelledStatus) - - const { fetchStatus, manageSubscription } = useSubscriptionWithScope() - - await fetchStatus() - await manageSubscription() - - window.dispatchEvent(new Event('focus')) - await vi.waitFor(() => { - expect( - useTelemetry()?.trackMonthlySubscriptionCancelled - ).toHaveBeenCalledTimes(1) - }) - }) }) }) vi.mock(import('firebase/auth')) diff --git a/src/platform/billing/subscription/composables/useSubscription.ts b/src/platform/billing/subscription/composables/useSubscription.ts index 7044244cb9e..ec0ea9b36fc 100644 --- a/src/platform/billing/subscription/composables/useSubscription.ts +++ b/src/platform/billing/subscription/composables/useSubscription.ts @@ -7,39 +7,24 @@ import { useEventListener } from '@vueuse/core' -import type { BillingPortalTarget } from '@comfyorg/account-core/billing' - import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useErrorHandling } from '@/composables/useErrorHandling' -import { getComfyApiBaseUrl } from '@/config/comfyApi' import { t } from '@/i18n' -import { webSessionResourceHeader } from '@comfyorg/api-client/webSessionFetch' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@comfyorg/telemetry' import { reportError as reportTelemetryError } from '@comfyorg/telemetry/reportError' -import { createBillingPortalReporter } from '@/platform/telemetry/utils/billingPortalTelemetry' -import type { - CheckoutAttributionMetadata, - ResubscribeClickMetadata, - SubscriptionSuccessMetadata -} from '@comfyorg/telemetry/types' +import type { SubscriptionSuccessMetadata } from '@comfyorg/telemetry/types' import type { BillingStatusResponse } from '@comfyorg/billing-core' import { billingApi } from '@/platform/billing/api/billingApi' import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError' import { readOnRail } from '@/platform/billing/composables/readOnRail' import { useBillingReadRail } from '@/platform/billing/composables/useBillingReadRail' -import { - PaymentPopupBlockedError, - categorizeBillingApiError -} from '@/platform/telemetry/utils/billingFailureCategory' +import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity' import { platformLink } from '@/platform/workspace/utils/platformLink' import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { toTierKey } from '@/platform/billing/subscription/constants/tierPricing' -import type { BillingCycle } from '@/platform/billing/subscription/utils/subscriptionTierRank' -import type { operations } from '@/types/comfyRegistryTypes' -import { parseErrorResponse } from '@/platform/remote/comfyui/errors' import { PENDING_SUBSCRIPTION_CHECKOUT_EVENT, PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY, @@ -48,21 +33,9 @@ import { getPendingSubscriptionCheckoutAttempt, claimPendingCheckoutTerminal, getPendingCheckoutTerminal, - hasPendingSubscriptionCheckoutAttempt, - persistPendingSubscriptionCheckoutAttempt + hasPendingSubscriptionCheckoutAttempt } from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker' -import type { ReportedCheckoutAttemptInput } from '@/platform/billing/subscription/utils/subscriptionCheckoutUtil' import type { BillingStatusReadOptions } from '@/platform/billing/composables/types' -import { - missingCheckoutUrlError, - runReportedCheckoutAttempt -} from '@/platform/billing/subscription/utils/subscriptionCheckoutUtil' -import { useSubscriptionCancellationWatcher } from './useSubscriptionCancellationWatcher' -import { openBillingUrl } from '@/platform/billing/billingTab' - -type CloudSubscriptionCheckoutResponse = NonNullable< - operations['createCloudSubscriptionCheckout']['responses']['201']['content']['application/json'] -> const PENDING_SUBSCRIPTION_CHECKOUT_RETRY_DELAYS_MS = [3000, 10000, 30000] @@ -115,11 +88,10 @@ function useSubscriptionInternal() { return subscriptionStatus.value?.is_active ?? false }) - const { reportError, accessBillingPortalDirect } = useAuthActions() + const { reportError } = useAuthActions() const authStore = useAuthStore() const workspaceStore = useWorkspaceIdentity() - const { getFirebaseAuthHeader, fetchWithCustomerRecovery } = authStore const { wrapWithErrorHandlingAsync } = useErrorHandling() const { isLoggedIn } = useCurrentUser() @@ -187,22 +159,6 @@ function useSubscriptionInternal() { : baseName }) - function buildApiUrl(path: string): string { - return `${getComfyApiBaseUrl()}${path}` - } - - const getCheckoutAttributionForCloud = - async (): Promise => { - if (__DISTRIBUTION__ !== 'cloud') { - return {} - } - - const { getCheckoutAttribution } = - await import('@/platform/telemetry/utils/checkoutAttribution') - - return getCheckoutAttribution() - } - interface PendingCheckoutSchedule { timeoutId: number | null retryRung: number @@ -477,134 +433,17 @@ function useSubscriptionInternal() { stopPendingCheckoutRecovery() } - const buildAuthHeaders = async (): Promise> => { - const authHeader = - (await webSessionResourceHeader()) ?? (await getFirebaseAuthHeader()) - if (!authHeader) { - throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) - } - - return { - ...authHeader, - 'Content-Type': 'application/json' - } - } - const fetchStatus = wrapWithErrorHandlingAsync( fetchSubscriptionStatus, reportError ) - interface SubscribeDirectOptions { - /** Set when this call originates from the resubscribe flow, not a plain subscribe. */ - operation?: 'resubscribe' - /** Click-time source for a resubscribe attempt; carried through to the terminal event. */ - source?: ResubscribeClickMetadata['source'] - } - - const getPreviousCycle = (): BillingCycle | undefined => { - if (subscriptionDuration.value === 'ANNUAL') return 'yearly' - if (subscriptionDuration.value === 'MONTHLY') return 'monthly' - } - - const resubscribeAttemptDetails = ( - options: SubscribeDirectOptions | undefined - ) => { - if (options?.operation !== 'resubscribe') return {} - const previousCancelAt = subscriptionStatus.value - ? (subscriptionStatus.value.cancel_at ?? null) - : undefined - - return { - operation: options.operation, - resubscribe_source: options.source, - ...(previousCancelAt !== undefined - ? { previous_cancel_at: previousCancelAt } - : {}) - } - } - - const standardCheckoutAttemptInput = ( - options: SubscribeDirectOptions | undefined - ): ReportedCheckoutAttemptInput => { - const previousTier = subscriptionTier.value - ? toTierKey(subscriptionTier.value) - : null - - return { - tier: 'standard', - cycle: 'monthly', - checkout_type: canAccessSubscriptionFeatures.value ? 'change' : 'new', - previous_tier: previousTier ?? undefined, - previous_cycle: getPreviousCycle(), - ...resubscribeAttemptDetails(options), - owner_id: authStore.userId ?? undefined, - workspace_id: workspaceStore.activeWorkspaceId - } - } - - /** Unwrapped `subscribe`, for callers that need rejections to propagate (e.g. telemetry). */ - const subscribeDirect = (options?: SubscribeDirectOptions): Promise => - runReportedCheckoutAttempt( - standardCheckoutAttemptInput(options), - async (attempt) => { - const response = await initiateSubscriptionCheckout() - - if (!response.checkout_url) throw missingCheckoutUrlError() - - if (!openBillingUrl(response.checkout_url)) { - throw new PaymentPopupBlockedError( - t('subscription.preview.paymentPopupBlocked') - ) - } - - persistPendingSubscriptionCheckoutAttempt(attempt) - } - ) - - const subscribe = wrapWithErrorHandlingAsync(subscribeDirect, reportError) - /** * Whether cloud subscription mode is enabled (cloud distribution with subscription_required config). */ const isSubscriptionEnabled = (): boolean => Boolean(isCloud && window.__CONFIG__?.subscription_required) - const { startCancellationWatcher, stopCancellationWatcher } = - useSubscriptionCancellationWatcher({ - fetchStatus, - canAccessSubscriptionFeatures: canAccessSubscriptionFeatures, - subscriptionStatus, - telemetry, - shouldWatchCancellation: isSubscriptionEnabled - }) - - const openBillingPortal = async ( - target: BillingPortalTarget, - options?: { cancelSubscription?: boolean } - ) => { - const portal = createBillingPortalReporter(telemetry, target) - let opened: boolean - try { - opened = await accessBillingPortalDirect(undefined, options) - } catch (error) { - portal.failed(error, 'legacy') - throw error - } - if (opened) portal.opened('legacy') - else portal.blocked('legacy') - return opened - } - - const manageSubscription = async (options?: { - cancelSubscription?: boolean - }) => { - if (!(await openBillingPortal('manage_subscription', options))) { - throw new PaymentPopupBlockedError(t('subscription.billingTabBlocked')) - } - startCancellationWatcher() - } - const handleViewUsageHistory = () => { window.open(platformLink('/profile/usage'), '_blank') } @@ -613,10 +452,6 @@ function useSubscriptionInternal() { window.open('https://docs.comfy.org', '_blank') } - const handleInvoiceHistory = wrapWithErrorHandlingAsync(async () => { - await openBillingPortal('invoices') - }, reportError) - type PendingCheckoutRecoverySource = | 'bootstrap' | 'pageshow' @@ -1080,41 +915,12 @@ function useSubscriptionInternal() { subscriptionStatus.value = null clearPendingSubscriptionCheckoutAttempt() stopPendingCheckoutRecovery() - stopCancellationWatcher() isInitialized.value = true } }, { immediate: true } ) - const initiateSubscriptionCheckout = - async (): Promise => { - const headers = await buildAuthHeaders() - const checkoutAttribution = await getCheckoutAttributionForCloud() - - const response = await fetchWithCustomerRecovery( - buildApiUrl('/customers/cloud-subscription-checkout'), - { - method: 'POST', - headers, - body: JSON.stringify(checkoutAttribution) - } - ) - - if (!response.ok) { - const { message, code } = await parseErrorResponse(response) - throw new AuthStoreError( - t('toastMessages.failedToInitiateSubscription', { - error: message - }), - response.status, - code - ) - } - - return response.json() - } - return { // State canAccessSubscriptionFeatures: canAccessSubscriptionFeatures, @@ -1133,14 +939,10 @@ function useSubscriptionInternal() { isSubscriptionEnabled, // Actions - subscribe, - subscribeDirect, fetchStatus, fetchStatusDirect: fetchSubscriptionStatus, - manageSubscription, handleViewUsageHistory, - handleLearnMore, - handleInvoiceHistory + handleLearnMore } } diff --git a/src/platform/billing/subscription/composables/useSubscriptionActions.test.ts b/src/platform/billing/subscription/composables/useSubscriptionActions.test.ts index 79d58af9111..1c0c89132a4 100644 --- a/src/platform/billing/subscription/composables/useSubscriptionActions.test.ts +++ b/src/platform/billing/subscription/composables/useSubscriptionActions.test.ts @@ -3,7 +3,6 @@ import { useBillingDialogs } from '@/platform/billing/composables/useBillingDial import { useCommandStore } from '@/platform/keybindings/commandStore' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { useAuthActions } from '@/composables/auth/useAuthActions' import { useSubscriptionActions } from '@/platform/billing/subscription/composables/useSubscriptionActions' import { useTelemetry } from '@comfyorg/telemetry' import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' @@ -158,7 +157,6 @@ describe('useSubscriptionActions', () => { expect(billing.fetchBalance).toHaveBeenCalledOnce() expect(billing.fetchStatus).toHaveBeenCalledOnce() - expect(useAuthActions().fetchBalance).not.toHaveBeenCalled() }) it('swallows refresh failures without surfacing a toast', async () => { diff --git a/src/platform/billing/subscription/composables/useSubscriptionCancellationWatcher.test.ts b/src/platform/billing/subscription/composables/useSubscriptionCancellationWatcher.test.ts deleted file mode 100644 index e43d3109a30..00000000000 --- a/src/platform/billing/subscription/composables/useSubscriptionCancellationWatcher.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { computed, effectScope, ref } from 'vue' -import type { EffectScope } from 'vue' - -import { useSubscriptionCancellationWatcher } from '@/platform/billing/subscription/composables/useSubscriptionCancellationWatcher' -import type { TelemetryDispatcher } from '@comfyorg/telemetry/types' -import type { BillingStatusResponse } from '@comfyorg/billing-core' - -describe('useSubscriptionCancellationWatcher', () => { - const trackMonthlySubscriptionCancelled = vi.fn() - const telemetryMock: Pick< - TelemetryDispatcher, - 'trackMonthlySubscriptionCancelled' - > = { - trackMonthlySubscriptionCancelled - } - - const baseStatus: BillingStatusResponse = { - ended_at: null, - is_active: true, - has_funds: true, - max_seats: 0, - occupied_seats: 0, - team_credit_stop: null, - scheduled_change: null, - renewal_date: '2025-11-16' - } - - const subscriptionStatus = ref(baseStatus) - const isActive = ref(true) - const canAccessSubscriptionFeatures = computed(() => isActive.value) - - let shouldWatch = true - const shouldWatchCancellation = () => shouldWatch - - const activeScopes: EffectScope[] = [] - - const initWatcher = ( - options: Parameters[0] - ): ReturnType => { - const scope = effectScope() - const result = scope.run(() => useSubscriptionCancellationWatcher(options)) - if (!result) throw new Error('Expected watcher scope to run') - - activeScopes.push(scope) - return result - } - - beforeEach(() => { - subscriptionStatus.value = { ...baseStatus } - isActive.value = true - shouldWatch = true - }) - - afterEach(() => { - activeScopes.forEach((scope) => scope.stop()) - activeScopes.length = 0 - }) - - it('polls with exponential backoff and fires telemetry once cancellation detected', async () => { - const fetchStatus = vi.fn(async () => { - if (fetchStatus.mock.calls.length === 2) { - isActive.value = false - subscriptionStatus.value = { - ...baseStatus, - is_active: false, - cancel_at: '2025-12-01' - } - } - }) - - const { startCancellationWatcher } = initWatcher({ - fetchStatus, - canAccessSubscriptionFeatures, - subscriptionStatus, - telemetry: telemetryMock, - shouldWatchCancellation - }) - - startCancellationWatcher() - - await vi.advanceTimersByTimeAsync(5000) - expect(fetchStatus).toHaveBeenCalledTimes(1) - - await vi.advanceTimersByTimeAsync(15000) - expect(fetchStatus).toHaveBeenCalledTimes(2) - expect( - telemetryMock.trackMonthlySubscriptionCancelled - ).toHaveBeenCalledTimes(1) - }) - - it('triggers a check immediately when window regains focus', async () => { - const fetchStatus = vi.fn(async () => { - isActive.value = false - subscriptionStatus.value = { - ...baseStatus, - is_active: false, - cancel_at: '2025-12-01' - } - }) - - const { startCancellationWatcher } = initWatcher({ - fetchStatus, - canAccessSubscriptionFeatures, - subscriptionStatus, - telemetry: telemetryMock, - shouldWatchCancellation - }) - - startCancellationWatcher() - - window.dispatchEvent(new Event('focus')) - await Promise.resolve() - - expect(fetchStatus).toHaveBeenCalledTimes(1) - expect( - telemetryMock.trackMonthlySubscriptionCancelled - ).toHaveBeenCalledTimes(1) - }) - - it('stops after max attempts when subscription stays active', async () => { - const fetchStatus = vi.fn(async () => {}) - - const { startCancellationWatcher } = initWatcher({ - fetchStatus, - canAccessSubscriptionFeatures, - subscriptionStatus, - telemetry: telemetryMock, - shouldWatchCancellation - }) - - startCancellationWatcher() - - const delays = [5000, 15000, 45000, 135000] - for (const delay of delays) { - await vi.advanceTimersByTimeAsync(delay) - } - - expect(fetchStatus).toHaveBeenCalledTimes(4) - expect(trackMonthlySubscriptionCancelled).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(200000) - expect(fetchStatus).toHaveBeenCalledTimes(4) - }) - - it('does not start watcher when guard fails or subscription inactive', async () => { - const fetchStatus = vi.fn() - - const { startCancellationWatcher } = initWatcher({ - fetchStatus, - canAccessSubscriptionFeatures, - subscriptionStatus, - telemetry: telemetryMock, - shouldWatchCancellation - }) - - shouldWatch = false - startCancellationWatcher() - await vi.advanceTimersByTimeAsync(60000) - expect(fetchStatus).not.toHaveBeenCalled() - - shouldWatch = true - isActive.value = false - subscriptionStatus.value = { - ...baseStatus, - is_active: false - } - startCancellationWatcher() - await vi.advanceTimersByTimeAsync(60000) - expect(fetchStatus).not.toHaveBeenCalled() - }) -}) diff --git a/src/platform/billing/subscription/composables/useSubscriptionCancellationWatcher.ts b/src/platform/billing/subscription/composables/useSubscriptionCancellationWatcher.ts deleted file mode 100644 index eba7804ed17..00000000000 --- a/src/platform/billing/subscription/composables/useSubscriptionCancellationWatcher.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { onScopeDispose, ref } from 'vue' -import type { ComputedRef, Ref } from 'vue' -import { defaultWindow, useEventListener, useTimeoutFn } from '@vueuse/core' - -import type { TelemetryDispatcher } from '@comfyorg/telemetry/types' -import type { BillingStatusResponse } from '@comfyorg/billing-core' - -const MAX_CANCELLATION_ATTEMPTS = 4 -const CANCELLATION_BASE_DELAY_MS = 5000 -const CANCELLATION_BACKOFF_MULTIPLIER = 3 // 5s, 15s, 45s, 135s intervals - -type CancellationWatcherOptions = { - fetchStatus: () => Promise - canAccessSubscriptionFeatures: ComputedRef - subscriptionStatus: Ref - telemetry: Pick< - TelemetryDispatcher, - 'trackMonthlySubscriptionCancelled' - > | null - shouldWatchCancellation: () => boolean -} - -export function useSubscriptionCancellationWatcher({ - fetchStatus, - canAccessSubscriptionFeatures, - subscriptionStatus, - telemetry, - shouldWatchCancellation -}: CancellationWatcherOptions) { - const watcherActive = ref(false) - const cancellationAttempts = ref(0) - const cancellationTracked = ref(false) - const cancellationCheckInFlight = ref(false) - const nextDelay = ref(CANCELLATION_BASE_DELAY_MS) - let detachFocusListener: (() => void) | null = null - - const { start: startTimer, stop: stopTimer } = useTimeoutFn( - () => { - void checkForCancellation() - }, - nextDelay, - { immediate: false } - ) - - const stopCancellationWatcher = () => { - watcherActive.value = false - stopTimer() - cancellationAttempts.value = 0 - cancellationCheckInFlight.value = false - if (detachFocusListener) { - detachFocusListener() - detachFocusListener = null - } - } - - const scheduleNextCancellationCheck = () => { - if (!watcherActive.value) return - - if (cancellationAttempts.value >= MAX_CANCELLATION_ATTEMPTS) { - stopCancellationWatcher() - return - } - - nextDelay.value = - CANCELLATION_BASE_DELAY_MS * - CANCELLATION_BACKOFF_MULTIPLIER ** cancellationAttempts.value - cancellationAttempts.value += 1 - startTimer() - } - - const checkForCancellation = async (triggeredFromFocus = false) => { - if (!watcherActive.value || cancellationCheckInFlight.value) return - - cancellationCheckInFlight.value = true - try { - await fetchStatus() - - if (!canAccessSubscriptionFeatures.value) { - if (!cancellationTracked.value) { - cancellationTracked.value = true - try { - telemetry?.trackMonthlySubscriptionCancelled() - } catch (telemetryError) { - console.error( - '[Subscription] Failed to track cancellation telemetry:', - telemetryError - ) - } - } - stopCancellationWatcher() - return - } - - if (!triggeredFromFocus) { - scheduleNextCancellationCheck() - } - } catch (error) { - console.error('[Subscription] Error checking cancellation status:', error) - scheduleNextCancellationCheck() - } finally { - cancellationCheckInFlight.value = false - } - } - - const startCancellationWatcher = () => { - if (!shouldWatchCancellation() || !subscriptionStatus.value?.is_active) { - return - } - - stopCancellationWatcher() - watcherActive.value = true - cancellationTracked.value = false - cancellationAttempts.value = 0 - if (!detachFocusListener && defaultWindow) { - detachFocusListener = useEventListener(defaultWindow, 'focus', () => { - if (!watcherActive.value) return - void checkForCancellation(true) - }) - } - scheduleNextCancellationCheck() - } - - onScopeDispose(() => { - stopCancellationWatcher() - }) - - return { - startCancellationWatcher, - stopCancellationWatcher - } -} diff --git a/src/platform/billing/subscription/composables/useSubscriptionCredits.ts b/src/platform/billing/subscription/composables/useSubscriptionCredits.ts index 23941c828d0..da292271454 100644 --- a/src/platform/billing/subscription/composables/useSubscriptionCredits.ts +++ b/src/platform/billing/subscription/composables/useSubscriptionCredits.ts @@ -9,12 +9,6 @@ import { useBillingContext } from '@/platform/billing/composables/useBillingCont /** * Composable for handling subscription credit calculations and formatting. - * - * Uses useBillingContext which automatically selects the correct billing source: - * - If team workspaces feature is disabled: uses legacy (/customers) - * - If team workspaces feature is enabled: - * - Personal workspace: uses legacy (/customers) - * - Team workspace: uses workspace (/billing) */ /** * Formats a cent value to display credits. diff --git a/src/platform/billing/subscription/composables/useSubscriptionDialog.loading.test.ts b/src/platform/billing/subscription/composables/useSubscriptionDialog.loading.test.ts index eddc4c7f783..61a461e2271 100644 --- a/src/platform/billing/subscription/composables/useSubscriptionDialog.loading.test.ts +++ b/src/platform/billing/subscription/composables/useSubscriptionDialog.loading.test.ts @@ -13,7 +13,7 @@ vi.mock(import('@/platform/billing/composables/useBillingUI')) vi.mock(import('@comfyorg/telemetry')) vi.mock(import('@/services/dialogService')) vi.mock( - import('@/platform/billing/subscription/components/SubscriptionRequiredDialogContent.vue'), + import('@/platform/billing/components/SubscriptionRequiredDialogContentUnified.vue'), () => { throw new Error('pricing chunk unavailable') } diff --git a/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts b/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts index b8679f43d4c..cf7455673b2 100644 --- a/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts +++ b/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts @@ -1,4 +1,3 @@ -import { useDialogStore } from '@/stores/dialogStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import type { BillingOperationRecordView } from '@/platform/billing/sdk/operationRecordView' import { fakeBillingSdk } from '@/platform/billing/sdk/billingSdkTestUtils' @@ -19,7 +18,6 @@ import { useBillingContext } from '@/platform/billing/composables/useBillingCont import { useBillingUI } from '@/platform/billing/composables/useBillingUI' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useDialogService } from '@/services/dialogService' -import { openTeamWorkspaceDialog } from '@/platform/billing/ports/teamWorkspaceDialog' import type { SubscriptionInfo } from '@/platform/billing/composables/types' import type { BillingSubscriptionStatus, @@ -45,13 +43,8 @@ vi.mock( import('@/platform/billing/components/SubscriptionRequiredDialogContentUnified.vue'), () => ({ default: defineComponent({ setup: () => () => null }) }) ) -vi.mock( - import('@/platform/billing/subscription/components/SubscriptionRequiredDialogContent.vue'), - () => ({ default: defineComponent({ setup: () => () => null }) }) -) const mockShowLayoutDialog = vi.fn() -const mockShowTeamWorkspacesDialog = vi.fn() const mockIsFreeTier = vi.hoisted(() => ({ value: false })) const mockTier = vi.hoisted<{ value: SubscriptionInfo['tier'] }>(() => ({ @@ -83,7 +76,6 @@ vi.mock(import('@datadog/browser-rum'), () => ({ vi.mock(import('@/composables/auth/useCurrentUser')) vi.mock(import('@/services/dialogService')) -vi.mock(import('@/platform/billing/ports/teamWorkspaceDialog')) vi.mock(import('@/platform/billing/composables/useBillingRouting')) @@ -129,9 +121,6 @@ beforeEach(() => { vi.mocked(useDialogService().showLayoutDialog).mockImplementation( mockShowLayoutDialog ) - vi.mocked(openTeamWorkspaceDialog).mockImplementation( - mockShowTeamWorkspacesDialog - ) const billing = useBillingContext() billing.isFreeTier = computed(() => mockIsFreeTier.value) billing.isLegacyTeamPlan = computed(() => mockIsLegacyTeamPlan.value) @@ -350,31 +339,37 @@ describe('useSubscriptionDialog', () => { expect(props.initialPlanMode).toBe('personal') }) - it('keeps personal checkout deep links table-only on the legacy billing flow', async () => { - Object.assign(useTeamWorkspaceStore(), { isInPersonalWorkspace: true }) + it('opens the table once routing resolves for an early click', async () => { + let resolveRouting!: (known: boolean) => void + vi.mocked(useBillingContext().whenRoutingKnown).mockReturnValueOnce( + new Promise((resolve) => { + resolveRouting = resolve + }) + ) const { showPricingTable } = useSubscriptionDialog() - await showPricingTable({ - reason: 'deep_link', - initialCheckout: { - planMode: 'personal', - tierKey: 'creator', - billingCycle: 'monthly' - } - }) + const opened = showPricingTable({ reason: 'subscribe_now_button' }) + await Promise.resolve() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() - const props = mockShowLayoutDialog.mock.calls[0][0].props - expect(props).toHaveProperty('onChooseTeam') - expect(props).not.toHaveProperty('initialCheckout') - const { dialogComponentProps } = mockShowLayoutDialog.mock.calls[0][0] - expect(dialogComponentProps.dismissOnPointerDownOutside).toBe(false) - expect(useTelemetry()?.trackSubscription).toHaveBeenCalledWith( - 'modal_opened', - expect.objectContaining({ reason: 'deep_link' }) + resolveRouting(true) + + await expect(opened).resolves.toBe(true) + expect(mockShowLayoutDialog).toHaveBeenCalledTimes(1) + }) + + it('opens nothing when routing never resolves', async () => { + vi.mocked(useBillingContext().whenRoutingKnown).mockResolvedValueOnce( + false ) + const { showPricingTable } = useSubscriptionDialog() + + await expect(showPricingTable()).resolves.toBe(false) + + expect(mockShowLayoutDialog).not.toHaveBeenCalled() }) - it('uses the unified table when pricing is unified but billing remains legacy', async () => { + it('uses the unified table in a personal workspace', async () => { useBillingRouting().shouldUseUnifiedPricing = computed(() => true) Object.assign(useTeamWorkspaceStore(), { isInPersonalWorkspace: true }) const { showPricingTable } = useSubscriptionDialog() @@ -624,7 +619,7 @@ describe('useSubscriptionDialog', () => { }) }) - it('carries it to the legacy pricing table', async () => { + it('carries it to the pricing table', async () => { const { showPricingTable } = useSubscriptionDialog() await showPricingTable({ @@ -849,51 +844,6 @@ describe('useSubscriptionDialog', () => { }) }) - describe('startTeamWorkspaceUpgradeFlow', () => { - it('closes existing dialogs before opening team workspace dialog', () => { - mockShowTeamWorkspacesDialog.mockResolvedValue(undefined) - const { startTeamWorkspaceUpgradeFlow } = useSubscriptionDialog() - - startTeamWorkspaceUpgradeFlow() - - expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ - key: 'subscription-required' - }) - expect(mockShowTeamWorkspacesDialog).toHaveBeenCalledWith( - expect.any(Function) - ) - }) - - it('persists resume intent to sessionStorage via onConfirm callback', () => { - mockShowTeamWorkspacesDialog.mockResolvedValue(undefined) - const { startTeamWorkspaceUpgradeFlow } = useSubscriptionDialog() - - startTeamWorkspaceUpgradeFlow() - - const onConfirm = mockShowTeamWorkspacesDialog.mock.calls[0][0] - onConfirm() - - expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBe('1') - }) - - it('reopens pricing table on dialog rejection', async () => { - mockShowTeamWorkspacesDialog.mockRejectedValue(new Error('dialog error')) - - const { startTeamWorkspaceUpgradeFlow } = useSubscriptionDialog() - startTeamWorkspaceUpgradeFlow() - - await vi.waitFor(() => { - expect(console.error).toHaveBeenCalledWith( - '[useSubscriptionDialog] Failed to open team workspaces dialog:', - expect.any(Error) - ) - expect(mockShowLayoutDialog).toHaveBeenCalledWith( - expect.objectContaining({ key: 'subscription-required' }) - ) - }) - }) - }) - describe('resumePendingPricingFlow', () => { it('does nothing when no resume intent is stored', async () => { const { resumePendingPricingFlow } = useSubscriptionDialog() @@ -903,49 +853,6 @@ describe('useSubscriptionDialog', () => { expect(mockShowLayoutDialog).not.toHaveBeenCalled() }) - it('shows pricing table and clears intent when in team workspace', async () => { - sessionStorage.setItem('comfy:resume-team-pricing', '1') - Object.assign(useTeamWorkspaceStore(), { isInPersonalWorkspace: false }) - useBillingRouting().type = computed(() => 'workspace') - useBillingRouting().shouldUseWorkspaceBilling = computed(() => true) - useBillingRouting().shouldUseUnifiedPricing = computed(() => true) - mockCurrentPlanSlug.value = 'creator-monthly' - - const { resumePendingPricingFlow } = useSubscriptionDialog() - await resumePendingPricingFlow() - - expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBeNull() - expect(mockShowLayoutDialog).toHaveBeenCalledWith( - expect.objectContaining({ - key: 'subscription-required', - props: expect.objectContaining({ initialPlanMode: 'team' }) - }) - ) - }) - - it('clears intent but does not show pricing if still in personal workspace', async () => { - sessionStorage.setItem('comfy:resume-team-pricing', '1') - Object.assign(useTeamWorkspaceStore(), { isInPersonalWorkspace: true }) - - const { resumePendingPricingFlow } = useSubscriptionDialog() - await resumePendingPricingFlow() - - expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBeNull() - expect(mockShowLayoutDialog).not.toHaveBeenCalled() - }) - - it('consumes intent so second call is a no-op', async () => { - sessionStorage.setItem('comfy:resume-team-pricing', '1') - Object.assign(useTeamWorkspaceStore(), { isInPersonalWorkspace: false }) - - const { resumePendingPricingFlow } = useSubscriptionDialog() - await resumePendingPricingFlow() - mockShowLayoutDialog.mockClear() - - await resumePendingPricingFlow() - expect(mockShowLayoutDialog).not.toHaveBeenCalled() - }) - it('reconciles a failed redirect and reopens the attempted checkout', async () => { useBillingRouting().type = computed(() => 'workspace') useBillingRouting().shouldUseWorkspaceBilling = computed(() => true) diff --git a/src/platform/billing/subscription/composables/useSubscriptionDialog.ts b/src/platform/billing/subscription/composables/useSubscriptionDialog.ts index 350ae94e469..9adf2dd672b 100644 --- a/src/platform/billing/subscription/composables/useSubscriptionDialog.ts +++ b/src/platform/billing/subscription/composables/useSubscriptionDialog.ts @@ -1,5 +1,4 @@ import { useDialogService } from '@/services/dialogService' -import { openTeamWorkspaceDialog } from '@/platform/billing/ports/teamWorkspaceDialog' import { useDialogStore } from '@/stores/dialogStore' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' import { useBillingRouting } from '@/platform/billing/composables/useBillingRouting' @@ -32,7 +31,6 @@ import { import type { PendingSubscriptionCheckout } from '@/platform/billing/utils/pendingSubscriptionCheckout' const DIALOG_KEY = 'subscription-required' -const RESUME_PRICING_KEY = 'comfy:resume-team-pricing' function paymentIntentSourceOf( options?: SubscriptionDialogOptions @@ -53,8 +51,7 @@ function getInitialPlanMode( } export const useSubscriptionDialog = () => { - const { shouldUseWorkspaceBilling, shouldUseUnifiedPricing } = - useBillingRouting() + const { shouldUseWorkspaceBilling } = useBillingRouting() const dialogService = useDialogService() const dialogStore = useDialogStore() const workspaceStore = useWorkspaceIdentity() @@ -121,6 +118,13 @@ export const useSubscriptionDialog = () => { ): Promise { if (!isCloud) return false try { + const { + whenRoutingKnown, + currentPlanSlug, + isLegacyTeamPlan, + isTeamPlan + } = useBillingContext() + if (!(await whenRoutingKnown())) return false const paymentIntentSource = paymentIntentSourceOf(options) if (await showInactiveMemberDialog(paymentIntentSource)) return true @@ -134,56 +138,30 @@ export const useSubscriptionDialog = () => { const trackEntry = () => trackPaywallEntry(reason, paymentIntentSource, refusalType) - const legacyPricingDialogProps = { + const nonDismissableDialogProps = { dismissOnPointerDownOutside: false } as const - if (shouldUseUnifiedPricing.value) { - const { currentPlanSlug, isLegacyTeamPlan, isTeamPlan } = - useBillingContext() - if (isLegacyTeamPlan.value) { - const personalInitialCheckout = - options?.initialCheckout?.planMode === 'personal' - ? options.initialCheckout - : undefined - dialogService.showLayoutDialog({ - key: DIALOG_KEY, - component: ( - await import('@/platform/billing/components/SubscriptionRequiredDialogContentWorkspace.vue') - ).default, - props: { - ...dialogProps, - ...(personalInitialCheckout - ? { - initialCheckout: personalInitialCheckout, - isPersonal: true - } - : {}) - }, - dialogComponentProps: legacyPricingDialogProps - }) - trackEntry() - return true - } - + if (isLegacyTeamPlan.value) { + const personalInitialCheckout = + options?.initialCheckout?.planMode === 'personal' + ? options.initialCheckout + : undefined dialogService.showLayoutDialog({ key: DIALOG_KEY, component: ( - await import('@/platform/billing/components/SubscriptionRequiredDialogContentUnified.vue') + await import('@/platform/billing/components/SubscriptionRequiredDialogContentWorkspace.vue') ).default, props: { ...dialogProps, - initialCheckout: options?.initialCheckout, - initialPlanMode: getInitialPlanMode( - options?.planMode, - isTeamPlan.value, - currentPlanSlug.value !== null, - workspaceStore.isInPersonalWorkspace - ) + ...(personalInitialCheckout + ? { + initialCheckout: personalInitialCheckout, + isPersonal: true + } + : {}) }, - dialogComponentProps: { - dismissOnPointerDownOutside: false - } + dialogComponentProps: nonDismissableDialogProps }) trackEntry() return true @@ -192,13 +170,21 @@ export const useSubscriptionDialog = () => { dialogService.showLayoutDialog({ key: DIALOG_KEY, component: ( - await import('@/platform/billing/subscription/components/SubscriptionRequiredDialogContent.vue') + await import('@/platform/billing/components/SubscriptionRequiredDialogContentUnified.vue') ).default, props: { ...dialogProps, - onChooseTeam: () => startTeamWorkspaceUpgradeFlow() + initialCheckout: options?.initialCheckout, + initialPlanMode: getInitialPlanMode( + options?.planMode, + isTeamPlan.value, + currentPlanSlug.value !== null, + workspaceStore.isInPersonalWorkspace + ) }, - dialogComponentProps: legacyPricingDialogProps + dialogComponentProps: { + dismissOnPointerDownOutside: false + } }) trackEntry() return true @@ -211,23 +197,6 @@ export const useSubscriptionDialog = () => { } } - function startTeamWorkspaceUpgradeFlow() { - hide() - openTeamWorkspaceDialog(() => { - try { - sessionStorage.setItem(RESUME_PRICING_KEY, '1') - } catch { - return - } - }).catch((error) => { - console.error( - '[useSubscriptionDialog] Failed to open team workspaces dialog:', - error - ) - void showPricingTable() - }) - } - async function restoreCheckoutSelection( pending: PendingSubscriptionCheckout ): Promise { @@ -316,28 +285,12 @@ export const useSubscriptionDialog = () => { async function resumePendingPricingFlow(): Promise { const pendingCheckout = getPendingSubscriptionCheckout() if (pendingCheckout) return resumePendingCheckout(pendingCheckout) - - try { - const pending = sessionStorage.getItem(RESUME_PRICING_KEY) - if (!pending) return - sessionStorage.removeItem(RESUME_PRICING_KEY) - - if (!workspaceStore.isInPersonalWorkspace) { - await showPricingTable({ - reason: 'team_upgrade_resume', - planMode: 'team' - }) - } - } catch { - return - } } return { show: showPricingTable, showPricingTable, hide, - startTeamWorkspaceUpgradeFlow, resumePendingPricingFlow } } diff --git a/src/platform/billing/subscription/constants/subscriptionPricesConfig.ts b/src/platform/billing/subscription/constants/subscriptionPricesConfig.ts deleted file mode 100644 index 46e8b45977e..00000000000 --- a/src/platform/billing/subscription/constants/subscriptionPricesConfig.ts +++ /dev/null @@ -1 +0,0 @@ -export const MONTHLY_SUBSCRIPTION_PRICE = 20 diff --git a/src/platform/billing/subscription/utils/checkoutAttributionLoader.ts b/src/platform/billing/subscription/utils/checkoutAttributionLoader.ts deleted file mode 100644 index 9f7f6a5d594..00000000000 --- a/src/platform/billing/subscription/utils/checkoutAttributionLoader.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function loadCheckoutAttributionModule() { - return import('@/platform/telemetry/utils/checkoutAttribution') -} diff --git a/src/platform/billing/subscription/utils/subscriptionCheckoutTracker.ts b/src/platform/billing/subscription/utils/subscriptionCheckoutTracker.ts index 12cda5bbb0d..6c2cd4e14bf 100644 --- a/src/platform/billing/subscription/utils/subscriptionCheckoutTracker.ts +++ b/src/platform/billing/subscription/utils/subscriptionCheckoutTracker.ts @@ -10,7 +10,6 @@ import type { } from '@/platform/billing/subscription/constants/tierPricing' import type { BillingCycle } from '@/platform/billing/subscription/utils/subscriptionTierRank' import type { - BeginCheckoutMetadata, PaymentIntentSource, ResubscribeClickMetadata, SubscriptionSuccessMetadata @@ -401,7 +400,7 @@ export const claimPendingCheckoutTerminal = ( export const hasPendingSubscriptionCheckoutAttempt = (): boolean => getPendingSubscriptionCheckoutAttempt() !== null -export const createPendingSubscriptionCheckoutAttempt = ( +const createPendingSubscriptionCheckoutAttempt = ( input: PendingSubscriptionCheckoutAttemptInput ): PendingSubscriptionCheckoutAttempt => { return { @@ -430,7 +429,7 @@ export const createPendingSubscriptionCheckoutAttempt = ( } } -export const persistPendingSubscriptionCheckoutAttempt = ( +const persistPendingSubscriptionCheckoutAttempt = ( attempt: PendingSubscriptionCheckoutAttempt ): PendingSubscriptionCheckoutAttempt => { const storage = getStorage() @@ -458,14 +457,6 @@ export const recordPendingSubscriptionCheckoutAttempt = ( createPendingSubscriptionCheckoutAttempt(input) ) -export const withPendingCheckoutAttemptId = ( - metadata: BeginCheckoutMetadata, - attempt: PendingSubscriptionCheckoutAttempt -): BeginCheckoutMetadata => ({ - ...metadata, - checkout_attempt_id: attempt.attempt_id -}) - const didAttemptSucceed = ( attempt: PendingSubscriptionCheckoutAttempt, status: SubscriptionStatusSnapshot diff --git a/src/platform/billing/subscription/utils/subscriptionCheckoutUtil.test.ts b/src/platform/billing/subscription/utils/subscriptionCheckoutUtil.test.ts deleted file mode 100644 index 9ef97c1b1e8..00000000000 --- a/src/platform/billing/subscription/utils/subscriptionCheckoutUtil.test.ts +++ /dev/null @@ -1,589 +0,0 @@ -import { SessionTokenError } from '@comfyorg/account-core/sessionTokenMint' - -import { useAuthStore } from '@/stores/authStore' -import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest' - -import { PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY } from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker' -import { webSessionResourceHeader } from '@comfyorg/api-client/webSessionFetch' -import { useTelemetry } from '@comfyorg/telemetry' -import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' -import { reportError } from '@comfyorg/telemetry/reportError' -import { performSubscriptionCheckout } from './subscriptionCheckoutUtil' - -const { - mockIsCloud, - mockGetCheckoutAttribution, - mockLoadCheckoutAttributionModule, - mockLocalStorage -} = vi.hoisted(() => ({ - mockIsCloud: { value: true }, - mockGetCheckoutAttribution: vi.fn(() => ({ - ga_client_id: 'ga-client-id', - ga_session_id: 'ga-session-id', - ga_session_number: 'ga-session-number', - im_ref: 'impact-click-123', - utm_source: 'impact', - utm_medium: 'affiliate', - utm_campaign: 'spring-launch', - gclid: 'gclid-123', - gbraid: 'gbraid-456', - wbraid: 'wbraid-789' - })), - mockLoadCheckoutAttributionModule: vi.fn(), - mockLocalStorage: (() => { - const store = new Map() - - return { - getItem: vi.fn((key: string) => store.get(key) ?? null), - setItem: vi.fn((key: string, value: string) => { - store.set(key, value) - }), - removeItem: vi.fn((key: string) => { - store.delete(key) - }), - clear: vi.fn(() => { - store.clear() - }), - __reset: () => { - store.clear() - } - } - })() -})) - -Object.defineProperty(window, 'localStorage', { - value: mockLocalStorage, - writable: true -}) - -Object.defineProperty(globalThis, 'localStorage', { - value: mockLocalStorage, - writable: true -}) - -vi.mock(import('@comfyorg/telemetry')) - -vi.mock(import('@/platform/distribution/types'), () => ({ - get isCloud() { - return mockIsCloud.value - }, - isDesktop: false -})) - -vi.mock(import('./checkoutAttributionLoader'), () => ({ - loadCheckoutAttributionModule: mockLoadCheckoutAttributionModule -})) - -vi.mock(import('@comfyorg/api-client/webSessionFetch'), { spy: true }) - -type Distribution = 'desktop' | 'localhost' | 'cloud' - -const setDistribution = (distribution: Distribution) => { - ;( - globalThis as typeof globalThis & { __DISTRIBUTION__: Distribution } - ).__DISTRIBUTION__ = distribution -} - -function createDeferred() { - let resolve: (value: T) => void = () => {} - const promise = new Promise((res) => { - resolve = res - }) - - return { promise, resolve } -} - -beforeEach(() => { - vi.mocked(webSessionResourceHeader).mockResolvedValue(undefined) - Object.assign(useAuthStore(), { userId: 'user-123' }) - vi.mocked(useAuthStore().getFirebaseAuthHeader).mockResolvedValue({ - Authorization: 'Bearer test-token' as const - }) - vi.mocked(useAuthStore().fetchWithCustomerRecovery).mockImplementation( - (input, init) => fetch(input, init) - ) -}) - -describe('performSubscriptionCheckout', () => { - beforeEach(() => { - mockLoadCheckoutAttributionModule.mockResolvedValue({ - getCheckoutAttribution: mockGetCheckoutAttribution - }) - setDistribution('cloud') - mockIsCloud.value = true - Object.assign(useAuthStore(), { userId: 'user-123' }) - mockLocalStorage.__reset() - }) - - afterEach(() => { - setDistribution('localhost') - mockLocalStorage.__reset() - }) - - it.for([ - { - name: 'no web session sends the Firebase header', - session: undefined, - authorization: 'Bearer test-token', - firebaseCalls: 1 - }, - { - name: 'a web session sends its own header instead', - session: { Authorization: 'Bearer session-jwt' }, - authorization: 'Bearer session-jwt', - firebaseCalls: 0 - } - ])( - 'authorizes the tier checkout: $name', - async ({ session, authorization, firebaseCalls }) => { - vi.mocked(webSessionResourceHeader).mockResolvedValue(session) - vi.spyOn(window, 'open').mockImplementation(() => window) - vi.mocked(global.fetch).mockResolvedValue( - new Response( - JSON.stringify({ checkout_url: 'https://checkout.stripe.com/x' }) - ) - ) - - await performSubscriptionCheckout('pro', 'monthly') - - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-checkout/pro'), - expect.objectContaining({ - headers: expect.objectContaining({ Authorization: authorization }) - }) - ) - expect(useAuthStore().getFirebaseAuthHeader).toHaveBeenCalledTimes( - firebaseCalls - ) - } - ) - - it('rejects with the mint failure and sends no tier checkout request', async () => { - vi.mocked(webSessionResourceHeader).mockRejectedValue( - new SessionTokenError({ - status: 'error', - code: 'SESSION_REVOKED', - retryable: false - }) - ) - - await expect( - performSubscriptionCheckout('pro', 'monthly') - ).rejects.toMatchObject({ failure: { code: 'SESSION_REVOKED' } }) - expect(global.fetch).not.toHaveBeenCalled() - }) - - it('tracks begin_checkout with user id and tier metadata', async () => { - const checkoutUrl = 'https://checkout.stripe.com/test' - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) - - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - - await performSubscriptionCheckout('pro', 'yearly') - - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith({ - user_id: 'user-123', - tier: 'pro', - cycle: 'yearly', - checkout_type: 'new', - checkout_attempt_id: expect.any(String), - ga_client_id: 'ga-client-id', - ga_session_id: 'ga-session-id', - ga_session_number: 'ga-session-number', - im_ref: 'impact-click-123', - utm_source: 'impact', - utm_medium: 'affiliate', - utm_campaign: 'spring-launch', - gclid: 'gclid-123', - gbraid: 'gbraid-456', - wbraid: 'wbraid-789' - }) - const telemetry = useTelemetry() - if (!telemetry) throw new Error('Expected telemetry mock') - const beginCheckoutMetadata = vi.mocked(telemetry.trackBeginCheckout).mock - .calls[0][0] - const [, storedAttempt] = mockLocalStorage.setItem.mock.calls[0] - expect(JSON.parse(storedAttempt)).toMatchObject({ - owner_id: 'user-123', - workspace_id: null - }) - expect(beginCheckoutMetadata.checkout_attempt_id).toBe( - JSON.parse(storedAttempt).attempt_id - ) - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining( - '/customers/cloud-subscription-checkout/pro-yearly' - ), - expect.objectContaining({ - method: 'POST', - body: JSON.stringify({ - ga_client_id: 'ga-client-id', - ga_session_id: 'ga-session-id', - ga_session_number: 'ga-session-number', - im_ref: 'impact-click-123', - utm_source: 'impact', - utm_medium: 'affiliate', - utm_campaign: 'spring-launch', - gclid: 'gclid-123', - gbraid: 'gbraid-456', - wbraid: 'wbraid-789' - }) - }) - ) - expect(openSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') - }) - - it('continues checkout when attribution collection fails', async () => { - const checkoutUrl = 'https://checkout.stripe.com/test' - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) - mockGetCheckoutAttribution.mockRejectedValueOnce( - new Error('Attribution failed') - ) - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - - await performSubscriptionCheckout('pro', 'monthly') - - expect(reportError).toHaveBeenCalledWith(expect.any(Error), { - surface: 'billing', - errorType: 'cloud_checkout_attribution_fallback', - tags: { - failure_kind: 'degraded', - feature_area: 'billing', - operation: 'load', - outcome: 'degraded', - attribution_stage: 'collect' - }, - level: 'warning' - }) - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-checkout/pro'), - expect.objectContaining({ - method: 'POST', - body: JSON.stringify({}) - }) - ) - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith({ - user_id: 'user-123', - tier: 'pro', - cycle: 'monthly', - checkout_type: 'new', - checkout_attempt_id: expect.any(String) - }) - expect(openSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') - }) - - it('reports a failed attribution chunk load as the module_load stage', async () => { - vi.spyOn(window, 'open').mockImplementation(() => window) - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: 'https://checkout.stripe.com/test' }) - } as Response) - - mockLoadCheckoutAttributionModule.mockRejectedValueOnce( - new Error('Failed to fetch dynamically imported module') - ) - await performSubscriptionCheckout('pro', 'monthly') - - expect(reportError).toHaveBeenCalledWith( - expect.any(Error), - expect.objectContaining({ - errorType: 'cloud_checkout_attribution_fallback', - tags: expect.objectContaining({ attribution_stage: 'module_load' }) - }) - ) - - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-checkout/pro'), - expect.objectContaining({ body: JSON.stringify({}) }) - ) - }) - - it('carries the payment intent source into begin_checkout and the pending attempt', async () => { - const checkoutUrl = 'https://checkout.stripe.com/test' - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) - - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - - await performSubscriptionCheckout('pro', 'monthly', { - paymentIntentSource: 'out_of_credits' - }) - - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith( - expect.objectContaining({ payment_intent_source: 'out_of_credits' }) - ) - const telemetry = useTelemetry() - if (!telemetry) throw new Error('Expected telemetry mock') - const beginCheckoutMetadata = vi.mocked(telemetry.trackBeginCheckout).mock - .calls[0][0] - const [, storedAttempt] = mockLocalStorage.setItem.mock.calls[0] - const pendingAttempt = JSON.parse(storedAttempt) - expect(pendingAttempt).toMatchObject({ - payment_intent_source: 'out_of_credits' - }) - expect(beginCheckoutMetadata.checkout_attempt_id).toBe( - pendingAttempt.attempt_id - ) - openSpy.mockRestore() - }) - - it('keeps the initiating scope when identity changes during checkout', async () => { - const checkoutUrl = 'https://checkout.stripe.com/test' - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) - const authHeader = - createDeferred< - Awaited< - ReturnType['getFirebaseAuthHeader']> - > - >() - - Object.assign(useAuthStore(), { userId: 'user-early' }) - Object.assign(useTeamWorkspaceStore(), { - activeWorkspaceId: 'workspace-early' - }) - vi.mocked(useAuthStore().getFirebaseAuthHeader).mockImplementationOnce( - () => authHeader.promise - ) - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - - const checkoutPromise = performSubscriptionCheckout('pro', 'yearly') - - Object.assign(useAuthStore(), { userId: 'user-late' }) - Object.assign(useTeamWorkspaceStore(), { - activeWorkspaceId: 'workspace-late' - }) - authHeader.resolve({ Authorization: 'Bearer test-token' as const }) - - await checkoutPromise - - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledTimes(1) - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith( - expect.objectContaining({ - user_id: 'user-early', - tier: 'pro', - cycle: 'yearly', - checkout_type: 'new', - checkout_attempt_id: expect.any(String) - }) - ) - const [, storedAttempt] = mockLocalStorage.setItem.mock.calls[0] - expect(JSON.parse(storedAttempt)).toMatchObject({ - owner_id: 'user-early', - workspace_id: 'workspace-early' - }) - expect(openSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') - }) - - it('closes a blocked checkout tab as a popup-blocked failure and keeps no attempt', async () => { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000004' - ) - const checkoutUrl = 'https://checkout.stripe.com/test' - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) - - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ checkout_url: checkoutUrl }) - } as Response) - - await expect( - performSubscriptionCheckout('pro', 'monthly', { - paymentIntentSource: 'deep_link' - }) - ).rejects.toThrow("Couldn't open the payment page") - - expect(openSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') - const storedAttempt = window.localStorage.getItem( - PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY - ) - expect(storedAttempt).toBeNull() - expect(mockLocalStorage.setItem).not.toHaveBeenCalled() - expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith( - expect.objectContaining({ - checkout_attempt_id: '00000000-0000-4000-8000-000000000004' - }) - ) - const telemetry = useTelemetry() - assert.exists(telemetry) - expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000004', - tier: 'pro', - cycle: 'monthly', - checkout_type: 'new', - payment_intent_source: 'deep_link' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'failed', - outcome: 'failure', - checkout_attempt_id: '00000000-0000-4000-8000-000000000004', - tier: 'pro', - cycle: 'monthly', - checkout_type: 'new', - payment_intent_source: 'deep_link', - failure_category: 'redirect', - error_code: 'payment_popup_blocked', - duration_ms: expect.any(Number) - } - ] - ]) - }) - - it('closes an attempt with no checkout URL with one failure and surfaces the error', async () => { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000007' - ) - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) - vi.mocked(global.fetch).mockResolvedValue(new Response(JSON.stringify({}))) - - await expect(performSubscriptionCheckout('pro', 'monthly')).rejects.toThrow( - 'Failed to initiate subscription: No checkout URL returned' - ) - - const telemetry = useTelemetry() - assert.exists(telemetry) - expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000007', - tier: 'pro', - cycle: 'monthly', - checkout_type: 'new' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'failed', - outcome: 'failure', - checkout_attempt_id: '00000000-0000-4000-8000-000000000007', - tier: 'pro', - cycle: 'monthly', - checkout_type: 'new', - failure_category: 'unknown', - error_code: 'missing_checkout_response', - duration_ms: expect.any(Number) - } - ] - ]) - expect(openSpy).not.toHaveBeenCalled() - expect( - window.localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) - ).toBeNull() - }) - - it('opens the attempt with one started event that the pending attempt shares', async () => { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000001' - ) - vi.spyOn(window, 'open').mockImplementation(() => window) - vi.mocked(global.fetch).mockResolvedValue( - new Response( - JSON.stringify({ checkout_url: 'https://checkout.stripe.com/x' }) - ) - ) - - await performSubscriptionCheckout('pro', 'yearly', { - paymentIntentSource: 'out_of_credits' - }) - - const telemetry = useTelemetry() - assert.exists(telemetry) - expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000001', - tier: 'pro', - cycle: 'yearly', - checkout_type: 'new', - payment_intent_source: 'out_of_credits' - } - ] - ]) - expect( - JSON.parse( - window.localStorage.getItem( - PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY - ) ?? 'null' - ) - ).toMatchObject({ - attempt_id: '00000000-0000-4000-8000-000000000001', - start_reported: true - }) - }) - - it('closes a rejected checkout attempt with a failure that follows its started event', async () => { - vi.spyOn(crypto, 'randomUUID').mockReturnValue( - '00000000-0000-4000-8000-000000000002' - ) - vi.mocked(global.fetch).mockResolvedValue({ - ok: false, - status: 400, - statusText: 'Bad Request', - json: async () => ({ message: 'declined for person@example.com' }), - text: async () => '' - } as Response) - - await expect( - performSubscriptionCheckout('pro', 'yearly', { - paymentIntentSource: 'deep_link' - }) - ).rejects.toThrow() - - const telemetry = useTelemetry() - assert.exists(telemetry) - expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ - [ - { - operation: 'subscription_checkout', - stage: 'started', - outcome: 'pending', - checkout_attempt_id: '00000000-0000-4000-8000-000000000002', - tier: 'pro', - cycle: 'yearly', - checkout_type: 'new', - payment_intent_source: 'deep_link' - } - ], - [ - { - operation: 'subscription_checkout', - stage: 'failed', - outcome: 'failure', - checkout_attempt_id: '00000000-0000-4000-8000-000000000002', - tier: 'pro', - cycle: 'yearly', - checkout_type: 'new', - payment_intent_source: 'deep_link', - failure_category: 'api_rejected', - duration_ms: expect.any(Number) - } - ] - ]) - }) -}) -vi.mock(import('firebase/auth')) diff --git a/src/platform/billing/subscription/utils/subscriptionCheckoutUtil.ts b/src/platform/billing/subscription/utils/subscriptionCheckoutUtil.ts deleted file mode 100644 index 71b33dbeaf9..00000000000 --- a/src/platform/billing/subscription/utils/subscriptionCheckoutUtil.ts +++ /dev/null @@ -1,292 +0,0 @@ -import { getComfyApiBaseUrl } from '@/config/comfyApi' -import { t } from '@/i18n' -import type { TierKey } from '@/platform/billing/subscription/constants/tierPricing' -import type { - PendingSubscriptionCheckoutAttempt, - PendingSubscriptionCheckoutAttemptInput -} from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker' -import { - createPendingSubscriptionCheckoutAttempt, - persistPendingSubscriptionCheckoutAttempt, - withPendingCheckoutAttemptId -} from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker' -import { webSessionResourceHeader } from '@comfyorg/api-client/webSessionFetch' -import { isCloud } from '@/platform/distribution/types' -import { useTelemetry } from '@comfyorg/telemetry' -import { reportError } from '@comfyorg/telemetry/reportError' -import type { - CheckoutAttributionMetadata, - PaymentIntentSource -} from '@comfyorg/telemetry/types' -import { parseErrorResponse } from '@/platform/remote/comfyui/errors' -import { - BillingFailureError, - PaymentPopupBlockedError, - describeBillingFailure -} from '@/platform/telemetry/utils/billingFailureCategory' -import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity' -import { AuthStoreError, useAuthStore } from '@/stores/authStore' - -import type { BillingCycle } from './subscriptionTierRank' -import { loadCheckoutAttributionModule } from './checkoutAttributionLoader' -import { openBillingUrl } from '@/platform/billing/billingTab' - -type CheckoutTier = TierKey | `${TierKey}-yearly` - -const getCheckoutTier = ( - tierKey: TierKey, - billingCycle: BillingCycle -): CheckoutTier => (billingCycle === 'yearly' ? `${tierKey}-yearly` : tierKey) - -type CheckoutAttributionStage = 'module_load' | 'collect' - -type CheckoutAttributionOutcome = - | { ok: true; attribution: CheckoutAttributionMetadata } - | { ok: false; error: unknown; stage: CheckoutAttributionStage } - -const getCheckoutAttributionForCloud = - async (): Promise => { - if (__DISTRIBUTION__ !== 'cloud') { - return { ok: true, attribution: {} } - } - - let attributionModule - try { - attributionModule = await loadCheckoutAttributionModule() - } catch (error) { - return { ok: false, error, stage: 'module_load' } - } - - const getCheckoutAttribution = attributionModule.getCheckoutAttribution - - if (typeof getCheckoutAttribution !== 'function') { - return { - ok: false, - error: new TypeError('Checkout attribution module is unavailable'), - stage: 'module_load' - } - } - - try { - return { - ok: true, - attribution: await getCheckoutAttribution() - } - } catch (error) { - return { ok: false, error, stage: 'collect' } - } - } - -async function getCheckoutAttributionPayload(): Promise { - const attribution = await getCheckoutAttributionForCloud() - if (attribution.ok) return attribution.attribution - - reportError(attribution.error, { - surface: 'billing', - errorType: 'cloud_checkout_attribution_fallback', - tags: { - failure_kind: 'degraded', - feature_area: 'billing', - operation: 'load', - outcome: 'degraded', - attribution_stage: attribution.stage - }, - level: 'warning' - }) - return {} -} - -const checkoutAuthHeader = async (authStore: ReturnType) => - (await webSessionResourceHeader()) ?? - (await authStore.getFirebaseAuthHeader()) - -interface PerformSubscriptionCheckoutOptions { - paymentIntentSource?: PaymentIntentSource -} - -/** - * Core subscription checkout logic shared between PricingTable and - * SubscriptionRedirectView. Handles: - * - Ensuring the user is authenticated - * - Calling the backend checkout endpoint - * - Normalizing error responses - * - Opening the checkout URL in a new tab when available - * - Reporting checkout-initiation failures via `trackBillingEvent` - * - * Callers are responsible for: - * - Guarding on cloud-only behavior (isCloud) - * - Managing loading state - * - Wrapping with error handling (e.g. useErrorHandling) - */ -export async function performSubscriptionCheckout( - tierKey: TierKey, - currentBillingCycle: BillingCycle, - options: PerformSubscriptionCheckoutOptions = {} -): Promise { - if (!isCloud) return - - await runReportedCheckoutAttempt( - { - tier: tierKey, - cycle: currentBillingCycle, - checkout_type: 'new', - payment_intent_source: options.paymentIntentSource, - owner_id: useAuthStore().userId ?? undefined, - workspace_id: useWorkspaceIdentity().activeWorkspaceId - }, - (pendingAttempt) => - initiateSubscriptionCheckout(pendingAttempt, options.paymentIntentSource) - ) -} - -export const missingCheckoutUrlError = () => - new BillingFailureError( - t('toastMessages.failedToInitiateSubscription', { - error: 'No checkout URL returned' - }), - { failure_category: 'unknown', error_code: 'missing_checkout_response' } - ) - -export type ReportedCheckoutAttemptInput = Omit< - PendingSubscriptionCheckoutAttemptInput, - 'start_reported' -> - -/** - * Reports `started` for one legacy checkout attempt and `failed` when `launch` - * rejects. Its success is reported later by the pending-checkout recovery, - * which closes only attempts marked `start_reported`. - */ -export async function runReportedCheckoutAttempt( - input: ReportedCheckoutAttemptInput, - launch: (attempt: PendingSubscriptionCheckoutAttempt) => Promise -): Promise { - const telemetry = useTelemetry() - const attempt = createPendingSubscriptionCheckoutAttempt({ - ...input, - start_reported: true - }) - const attemptEvent = { - operation: 'subscription_checkout', - checkout_attempt_id: attempt.attempt_id, - tier: attempt.tier, - cycle: attempt.cycle, - checkout_type: attempt.checkout_type, - payment_intent_source: attempt.payment_intent_source - } as const - telemetry?.trackBillingEvent({ - ...attemptEvent, - stage: 'started', - outcome: 'pending' - }) - - try { - await launch(attempt) - } catch (error) { - telemetry?.trackBillingEvent({ - ...attemptEvent, - stage: 'failed', - outcome: 'failure', - ...describeBillingFailure(error), - duration_ms: Date.now() - attempt.started_at_ms - }) - throw error - } -} - -async function initiateSubscriptionCheckout( - pendingAttempt: PendingSubscriptionCheckoutAttempt, - paymentIntentSource: PaymentIntentSource | undefined -): Promise { - const { tier: tierKey, cycle: currentBillingCycle } = pendingAttempt - - const authStore = useAuthStore() - const telemetry = useTelemetry() - const authHeader = await checkoutAuthHeader(authStore) - - if (!authHeader) { - throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) - } - - const checkoutTier = getCheckoutTier(tierKey, currentBillingCycle) - const checkoutAttribution = await getCheckoutAttributionPayload() - const checkoutPayload = { ...checkoutAttribution } - - const response = await authStore.fetchWithCustomerRecovery( - `${getComfyApiBaseUrl()}/customers/cloud-subscription-checkout/${checkoutTier}`, - { - method: 'POST', - headers: { ...authHeader, 'Content-Type': 'application/json' }, - body: JSON.stringify(checkoutPayload) - } - ) - - if (!response.ok) { - const { message } = await parseErrorResponse(response) - - throw new AuthStoreError( - t('toastMessages.failedToInitiateSubscription', { - error: message - }), - response.status - ) - } - - const data = await response.json() - - completeSubscriptionCheckout(data.checkout_url, { - tierKey, - currentBillingCycle, - paymentIntentSource, - pendingAttempt, - checkoutAttribution, - telemetry - }) -} - -interface CheckoutCompletionContext { - tierKey: TierKey - currentBillingCycle: BillingCycle - paymentIntentSource?: PaymentIntentSource - pendingAttempt: PendingSubscriptionCheckoutAttempt - checkoutAttribution: CheckoutAttributionMetadata - telemetry: ReturnType -} - -function trackBeginCheckout(context: CheckoutCompletionContext) { - const { pendingAttempt, paymentIntentSource } = context - const userId = pendingAttempt.owner_id - if (!userId) return - - context.telemetry?.trackBeginCheckout( - withPendingCheckoutAttemptId( - { - user_id: userId, - tier: context.tierKey, - cycle: context.currentBillingCycle, - checkout_type: 'new', - ...(paymentIntentSource - ? { payment_intent_source: paymentIntentSource } - : {}), - ...context.checkoutAttribution - }, - pendingAttempt - ) - ) -} - -function completeSubscriptionCheckout( - checkoutUrl: string | undefined, - context: CheckoutCompletionContext -) { - if (!checkoutUrl) throw missingCheckoutUrlError() - - trackBeginCheckout(context) - - if (!openBillingUrl(checkoutUrl)) { - throw new PaymentPopupBlockedError( - t('subscription.preview.paymentPopupBlocked') - ) - } - persistPendingSubscriptionCheckoutAttempt(context.pendingAttempt) -} diff --git a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts index 43e9c2c8838..75fcb825285 100644 --- a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts +++ b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts @@ -36,17 +36,6 @@ vi.mock( import('@/platform/billing/subscription/composables/useSubscriptionDialog') ) -const legacyCheckoutMocks = vi.hoisted(() => ({ - performSubscriptionCheckout: vi.fn() -})) - -vi.mock( - import('@/platform/billing/subscription/utils/subscriptionCheckoutUtil'), - () => ({ - performSubscriptionCheckout: legacyCheckoutMocks.performSubscriptionCheckout - }) -) - const TEAM_CREDIT_STOPS = { default_stop_index: 0, stops: [ @@ -157,9 +146,6 @@ describe('CloudSubscriptionRedirectView', () => { billingCycle: 'monthly' } }) - expect( - legacyCheckoutMocks.performSubscriptionCheckout - ).not.toHaveBeenCalled() // Shows loading affordances expect( @@ -174,7 +160,6 @@ describe('CloudSubscriptionRedirectView', () => { expect(mockRouterPush).not.toHaveBeenCalledWith('/') expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) - expect(useAuthActions().accessBillingPortal).not.toHaveBeenCalled() expect(useSubscriptionDialog().showPricingTable).not.toHaveBeenCalled() }) @@ -253,10 +238,6 @@ describe('CloudSubscriptionRedirectView', () => { await mountView({ tier: 'creator', cycle: 'yearly' }) expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) - expect(useAuthActions().accessBillingPortal).not.toHaveBeenCalled() - expect( - legacyCheckoutMocks.performSubscriptionCheckout - ).not.toHaveBeenCalled() expect(useSubscriptionDialog().showPricingTable).not.toHaveBeenCalled() }) @@ -277,8 +258,5 @@ describe('CloudSubscriptionRedirectView', () => { reason: 'deep_link', planMode: 'personal' }) - expect( - legacyCheckoutMocks.performSubscriptionCheckout - ).not.toHaveBeenCalled() }) }) diff --git a/src/platform/customNodes/lateLoading/cpuServerStep.test.ts b/src/platform/customNodes/lateLoading/cpuServerStep.test.ts index 7a5ffdae009..d3242b2e275 100644 --- a/src/platform/customNodes/lateLoading/cpuServerStep.test.ts +++ b/src/platform/customNodes/lateLoading/cpuServerStep.test.ts @@ -53,7 +53,8 @@ function pendingReading() { async function signIn() { provideCurrentUser(() => ({ userEmail: computed(() => null), - isApiKeyLogin: computed(() => true) + isApiKeyLogin: computed(() => true), + isLoggedIn: computed(() => true) })) await useTeamWorkspaceStore().initialize() } diff --git a/src/platform/customNodes/lateLoading/lateLoading.test.ts b/src/platform/customNodes/lateLoading/lateLoading.test.ts index 0e0259785c2..1d7d851c25f 100644 --- a/src/platform/customNodes/lateLoading/lateLoading.test.ts +++ b/src/platform/customNodes/lateLoading/lateLoading.test.ts @@ -1097,7 +1097,8 @@ describe('naming the CPU server step', () => { ) provideCurrentUser(() => ({ userEmail: computed(() => null), - isApiKeyLogin: computed(() => true) + isApiKeyLogin: computed(() => true), + isLoggedIn: computed(() => true) })) await useTeamWorkspaceStore().initialize() }) diff --git a/src/platform/workspace/ports/workspaceIdentity.test.ts b/src/platform/workspace/ports/workspaceIdentity.test.ts new file mode 100644 index 00000000000..0f4d039d69f --- /dev/null +++ b/src/platform/workspace/ports/workspaceIdentity.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { computed } from 'vue' + +import { provideCurrentUser } from '@/platform/auth/currentUserAccess' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +import { useWorkspaceIdentity } from './workspaceIdentity' + +describe('useWorkspaceIdentity initSettled', () => { + function signIn(loggedIn: boolean, userEmail: string | null = null) { + provideCurrentUser(() => ({ + userEmail: computed(() => userEmail), + isApiKeyLogin: computed(() => false), + isLoggedIn: computed(() => loggedIn) + })) + } + + it.for([ + { initState: 'ready', loggedIn: true, settled: true }, + { initState: 'error', loggedIn: true, settled: true }, + { initState: 'loading', loggedIn: false, settled: false }, + { initState: 'uninitialized', loggedIn: true, settled: false }, + { initState: 'uninitialized', loggedIn: false, settled: true } + ] as const)( + '$initState with loggedIn $loggedIn settles: $settled', + ({ initState, loggedIn, settled }) => { + signIn(loggedIn) + Object.assign(useTeamWorkspaceStore(), { initState }) + + expect(useWorkspaceIdentity().initSettled).toBe(settled) + } + ) + + it('keeps an authenticated user with no email unsettled before init starts', () => { + signIn(true, null) + Object.assign(useTeamWorkspaceStore(), { initState: 'uninitialized' }) + + expect(useWorkspaceIdentity().initSettled).toBe(false) + }) +}) diff --git a/src/platform/workspace/ports/workspaceIdentity.ts b/src/platform/workspace/ports/workspaceIdentity.ts index 42b1e5a388f..e1028a8fbd0 100644 --- a/src/platform/workspace/ports/workspaceIdentity.ts +++ b/src/platform/workspace/ports/workspaceIdentity.ts @@ -1,5 +1,6 @@ import type { WorkspaceWithRole } from '@comfyorg/ingest-types' +import { useCurrentUserAccess } from '@/platform/auth/currentUserAccess' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' export interface WorkspaceIdentityAccess { @@ -9,6 +10,7 @@ export interface WorkspaceIdentityAccess { 'id' | 'name' | 'type' | 'role' | 'subscription_tier' > | null readonly activeWorkspaceId: string | null + readonly initSettled: boolean readonly isInPersonalWorkspace: boolean readonly workspaceTransitionGeneration: number readonly identityGeneration: number @@ -26,6 +28,12 @@ export function useWorkspaceIdentity(): WorkspaceIdentityAccess { get activeWorkspaceId() { return workspace.activeWorkspaceId }, + get initSettled() { + const { initState } = workspace + if (initState === 'ready' || initState === 'error') return true + if (initState !== 'uninitialized') return false + return !useCurrentUserAccess().isLoggedIn.value + }, get isInPersonalWorkspace() { return workspace.isInPersonalWorkspace }, diff --git a/src/services/__mocks__/customerEventsService.ts b/src/services/__mocks__/customerEventsService.ts index 4c6a6c501bd..fbb53a485d6 100644 --- a/src/services/__mocks__/customerEventsService.ts +++ b/src/services/__mocks__/customerEventsService.ts @@ -1,5 +1,4 @@ -import { onTestFinished, vi } from 'vitest' -import { ref } from 'vue' +import { vi } from 'vitest' import { hasParamsBeyondDetailsColumn, @@ -32,9 +31,6 @@ const eventSeverities = new Map< ]) const customerEventsService: CustomerEventsService = { - isLoading: ref(false), - error: ref(null), - getMyEvents: vi.fn(async () => ({ events: [] })), formatEventType: vi.fn((type) => eventLabels.get(type) ?? type), getEventSeverity: vi.fn((type) => eventSeverities.get(type) ?? 'info'), formatAmount: vi.fn((amount) => { @@ -55,10 +51,4 @@ const customerEventsService: CustomerEventsService = { export const useCustomerEventsService = vi.fn< typeof real.useCustomerEventsService ->(() => { - onTestFinished(() => { - customerEventsService.isLoading.value = false - customerEventsService.error.value = null - }) - return customerEventsService -}) +>(() => customerEventsService) diff --git a/src/services/customerEventsService.test.ts b/src/services/customerEventsService.test.ts index bfbc2928787..ae5d5e6373b 100644 --- a/src/services/customerEventsService.test.ts +++ b/src/services/customerEventsService.test.ts @@ -1,39 +1,14 @@ -import { SessionTokenError } from '@comfyorg/account-core/sessionTokenMint' -import axios from 'axios' import { beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock(import('firebase/auth')) - import { EventType, useCustomerEventsService } from '@/services/customerEventsService' -import { - WebSessionTokenError, - webSessionResourceHeader -} from '@comfyorg/api-client/webSessionFetch' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' -import { useAuthStore } from '@/stores/authStore' -import type { AuthHeader } from '@comfyorg/api-client/authTypes' - -// Hoist the mocks to avoid hoisting issues -const mockAxiosInstance = vi.hoisted(() => ({ - get: vi.fn(), - interceptors: { response: { use: vi.fn() } } -})) const mockI18n = vi.hoisted(() => ({ d: vi.fn() })) -// Mock dependencies -vi.mock(import('axios'), () => ({ - default: { - create: vi.fn(() => mockAxiosInstance), - isAxiosError: vi.fn() - } -})) - vi.mock(import('@/i18n'), async () => { const { createI18n } = await import('vue-i18n') return { @@ -43,56 +18,10 @@ vi.mock(import('@/i18n'), async () => { } }) -vi.mock(import('@/utils/typeGuardUtil'), () => ({ - isAbortError: vi.fn() -})) - -vi.mock(import('@comfyorg/api-client/webSessionFetch'), { spy: true }) - describe('useCustomerEventsService', () => { let service: ReturnType - const mockAuthHeaders = { - Authorization: 'Bearer mock-token' - } satisfies AuthHeader - - const mockEventsResponse = { - events: [ - { - event_id: 'event-1', - event_type: 'credit_added', - params: { - amount: 1000, - transaction_id: 'txn-123', - payment_method: 'stripe' - }, - createdAt: '2024-01-01T10:00:00Z' - }, - { - event_id: 'event-2', - event_type: 'api_usage_completed', - params: { - api_name: 'Image Generation', - model: 'sdxl-base', - duration: 5000, - cost: 50 - }, - createdAt: '2024-01-02T10:00:00Z' - } - ], - total: 2, - page: 1, - limit: 10, - totalPages: 1 - } - beforeEach(() => { - remoteConfig.value = { comfy_api_base_url: 'https://api.example.com' } - vi.mocked(webSessionResourceHeader).mockResolvedValue(undefined) - vi.mocked(useAuthStore().getUserAuthHeader).mockResolvedValue( - mockAuthHeaders - ) - vi.mocked(useAuthStore().currentUserIdentity).mockReturnValue('api-key-a') mockI18n.d.mockImplementation((date, options) => { // Mock i18n date formatting if (options?.month === 'short') { @@ -107,253 +36,6 @@ describe('useCustomerEventsService', () => { }) service = useCustomerEventsService() - - return () => { - remoteConfig.value = {} - } - }) - - describe('initialization', () => { - it('should initialize with default state', () => { - expect(service.isLoading.value).toBe(false) - expect(service.error.value).toBeNull() - }) - }) - - describe('getMyEvents', () => { - it('should fetch events successfully', async () => { - mockAxiosInstance.get.mockResolvedValue({ data: mockEventsResponse }) - - const result = await service.getMyEvents({ - page: 1, - limit: 10 - }) - - expect(useAuthStore().getUserAuthHeader).toHaveBeenCalled() - expect(mockAxiosInstance.get).toHaveBeenCalledWith('/customers/events', { - baseURL: 'https://api.example.com', - params: { page: 1, limit: 10 }, - headers: mockAuthHeaders - }) - - expect(result).toEqual(mockEventsResponse) - expect(service.isLoading.value).toBe(false) - expect(service.error.value).toBeNull() - }) - - it('sends the request to the base URL configured after service creation', async () => { - remoteConfig.value = { comfy_api_base_url: 'https://changed.example.com' } - mockAxiosInstance.get.mockResolvedValue({ data: mockEventsResponse }) - - await service.getMyEvents() - - expect(mockAxiosInstance.get).toHaveBeenCalledWith('/customers/events', { - baseURL: 'https://changed.example.com', - params: { page: 1, limit: 10 }, - headers: mockAuthHeaders - }) - }) - - it('should use default parameters when none provided', async () => { - mockAxiosInstance.get.mockResolvedValue({ data: mockEventsResponse }) - - await service.getMyEvents() - - expect(mockAxiosInstance.get).toHaveBeenCalledWith('/customers/events', { - baseURL: 'https://api.example.com', - params: { page: 1, limit: 10 }, - headers: mockAuthHeaders - }) - }) - - it.for([ - { - name: 'no web session sends the user header', - session: undefined, - headers: mockAuthHeaders, - userHeaderCalls: 1 - }, - { - name: 'a web session sends its own header instead', - session: { Authorization: 'Bearer session-jwt' }, - headers: { Authorization: 'Bearer session-jwt' }, - userHeaderCalls: 0 - } - ])( - 'authorizes the request: $name', - async ({ session, headers, userHeaderCalls }) => { - vi.mocked(webSessionResourceHeader).mockResolvedValue(session) - mockAxiosInstance.get.mockResolvedValue({ data: mockEventsResponse }) - - await service.getMyEvents() - - expect(mockAxiosInstance.get).toHaveBeenCalledWith( - '/customers/events', - { - baseURL: 'https://api.example.com', - params: { page: 1, limit: 10 }, - headers - } - ) - expect(useAuthStore().getUserAuthHeader).toHaveBeenCalledTimes( - userHeaderCalls - ) - } - ) - - it('keeps the mint error message and hides its code', async () => { - vi.mocked(webSessionResourceHeader).mockRejectedValue( - new WebSessionTokenError( - new SessionTokenError({ - status: 'error', - code: 'SESSION_REVOKED', - retryable: false - }), - 'Your session ended. Sign in again to continue.' - ) - ) - vi.mocked(axios.isAxiosError).mockReturnValue(false) - - const result = await service.getMyEvents() - - expect(result).toBeNull() - expect(service.error.value).toContain( - 'Your session ended. Sign in again to continue.' - ) - expect(service.error.value).not.toContain('SESSION_REVOKED') - expect(service.isLoading.value).toBe(false) - expect(mockAxiosInstance.get).not.toHaveBeenCalled() - }) - - it('should return null when auth headers are missing', async () => { - vi.mocked(useAuthStore().getUserAuthHeader).mockResolvedValue(null) - - const result = await service.getMyEvents() - - expect(result).toBeNull() - expect(service.error.value).toBe('Authentication header is missing') - expect(mockAxiosInstance.get).not.toHaveBeenCalled() - }) - - it('discards events that resolve after an A->B API key switch', async () => { - let resolveEvents!: (value: unknown) => void - const eventsRequestStarted = new Promise((requestStarted) => { - mockAxiosInstance.get.mockImplementation(() => { - requestStarted() - return new Promise((resolve) => { - resolveEvents = resolve - }) - }) - }) - - const request = service.getMyEvents() - await eventsRequestStarted - vi.mocked(useAuthStore().currentUserIdentity).mockReturnValue('api-key-b') - resolveEvents({ data: mockEventsResponse }) - - await expect(request).resolves.toBeNull() - }) - - it('never exposes a stale error after an A->B API key switch', async () => { - let rejectEvents!: (reason: unknown) => void - const eventsRequestStarted = new Promise((requestStarted) => { - mockAxiosInstance.get.mockImplementation(() => { - requestStarted() - return new Promise((_resolve, reject) => { - rejectEvents = reject - }) - }) - }) - vi.mocked(axios.isAxiosError).mockReturnValue(true) - - const request = service.getMyEvents() - await eventsRequestStarted - vi.mocked(useAuthStore().currentUserIdentity).mockReturnValue('api-key-b') - rejectEvents({ - response: { status: 400, data: { message: 'account A backend error' } } - }) - - await expect(request).resolves.toBeNull() - expect(service.error.value).toBeNull() - expect(service.isLoading.value).toBe(false) - }) - - it('ignores a stale auth preflight once a newer request begins', async () => { - let resolveStaleHeader!: ( - value: Awaited< - ReturnType['getUserAuthHeader']> - > - ) => void - vi.mocked(useAuthStore().getUserAuthHeader).mockImplementationOnce( - () => - new Promise((resolve) => { - resolveStaleHeader = resolve - }) - ) - const staleRequest = service.getMyEvents() - - vi.mocked(useAuthStore().currentUserIdentity).mockReturnValue('api-key-b') - const activeRequestStarted = new Promise((requestStarted) => { - mockAxiosInstance.get.mockImplementation(() => { - requestStarted() - return new Promise(() => {}) - }) - }) - const activeRequest = service.getMyEvents() - await activeRequestStarted - - resolveStaleHeader(null) - await expect(staleRequest).resolves.toBeNull() - - expect(service.error.value).toBeNull() - expect(service.isLoading.value).toBe(true) - void activeRequest - }) - - it('should handle 400 errors', async () => { - const errorResponse = { - response: { - status: 400, - data: { message: 'Invalid input' } - } - } - mockAxiosInstance.get.mockRejectedValue(errorResponse) - vi.mocked(axios.isAxiosError).mockReturnValue(true) - - const result = await service.getMyEvents() - - expect(result).toBeNull() - expect(service.error.value).toBe('Invalid input, object invalid') - }) - - it('should handle 404 errors', async () => { - const errorResponse = { - response: { - status: 404, - data: { message: 'Not found' } - } - } - mockAxiosInstance.get.mockRejectedValue(errorResponse) - vi.mocked(axios.isAxiosError).mockReturnValue(true) - - const result = await service.getMyEvents() - - expect(result).toBeNull() - expect(service.error.value).toBe('Not found') - }) - - it('should handle network errors', async () => { - const networkError = new Error('Network Error') - mockAxiosInstance.get.mockRejectedValue(networkError) - vi.mocked(axios.isAxiosError).mockReturnValue(false) - - const result = await service.getMyEvents() - - expect(result).toBeNull() - expect(service.error.value).toBe( - 'Fetching customer events failed: Network Error' - ) - }) }) describe('formatEventType', () => { @@ -620,33 +302,6 @@ describe('useCustomerEventsService', () => { }) }) - describe('error handling edge cases', () => { - it('should handle non-Error objects', async () => { - const stringError = 'String error' - mockAxiosInstance.get.mockRejectedValue(stringError) - vi.mocked(axios.isAxiosError).mockReturnValue(false) - - const result = await service.getMyEvents() - - expect(result).toBeNull() - expect(service.error.value).toBe( - 'Fetching customer events failed: String error' - ) - }) - - it('should reset error state on new request', async () => { - // First request fails - mockAxiosInstance.get.mockRejectedValueOnce(new Error('First error')) - await service.getMyEvents() - expect(service.error.value).toBeTruthy() - - // Second request succeeds - mockAxiosInstance.get.mockResolvedValueOnce({ data: mockEventsResponse }) - await service.getMyEvents() - expect(service.error.value).toBeNull() - }) - }) - describe('EventType enum', () => { it('should have correct enum values', () => { expect(EventType.CREDIT_ADDED).toBe('credit_added') diff --git a/src/services/customerEventsService.ts b/src/services/customerEventsService.ts index da23674b4fe..06c52639cd5 100644 --- a/src/services/customerEventsService.ts +++ b/src/services/customerEventsService.ts @@ -1,10 +1,3 @@ -import type { AxiosError, AxiosResponse } from 'axios' -import axios from 'axios' -import { ref } from 'vue' - -import { webSessionResourceHeader } from '@comfyorg/api-client/webSessionFetch' -import { attachUnifiedRemintInterceptor } from '@/platform/auth/unified/remintRetry' -import { getComfyApiBaseUrl } from '@/config/comfyApi' import { formatCredits, isSubCreditCharge, @@ -16,9 +9,7 @@ import { toFiniteNumber } from '@/services/customerEventParams' import { d, i18n, t } from '@/i18n' -import { useAuthStore } from '@/stores/authStore' -import type { components, operations } from '@/types/comfyRegistryTypes' -import { isAbortError } from '@/utils/typeGuardUtil' +import type { components } from '@/types/comfyRegistryTypes' export enum EventType { CREDIT_ADDED = 'credit_added', @@ -27,72 +18,9 @@ export enum EventType { API_USAGE_COMPLETED = 'api_usage_completed' } -type CustomerEventsResponse = - operations['GetCustomerEvents']['responses']['200']['content']['application/json'] - -type CustomerEventsResponseQuery = - operations['GetCustomerEvents']['parameters']['query'] - export type AuditLog = components['schemas']['AuditLog'] -const customerApiClient = axios.create({ - headers: { - 'Content-Type': 'application/json' - } -}) - -attachUnifiedRemintInterceptor(customerApiClient) - export const useCustomerEventsService = () => { - const isLoading = ref(false) - const error = ref(null) - let latestRequestId = 0 - - const describeRequestError = ( - err: unknown, - context: string, - routeSpecificErrors?: Record - ): string | null => { - if (isAbortError(err)) return null - - if (!axios.isAxiosError(err)) { - return `${context} failed: ${err instanceof Error ? err.message : String(err)}` - } - const axiosError = err as AxiosError<{ message: string }> - const status = axiosError.response?.status - if (status && routeSpecificErrors?.[status]) { - return routeSpecificErrors[status] - } - return ( - axiosError.response?.data.message ?? - `${context} failed with status ${status}` - ) - } - - const executeRequest = async ( - requestCall: () => Promise>, - options: { - errorContext: string - routeSpecificErrors?: Record - } - ): Promise<{ data: T | null; errorMessage: string | null }> => { - const { errorContext, routeSpecificErrors } = options - - try { - const response = await requestCall() - return { data: response.data, errorMessage: null } - } catch (err) { - return { - data: null, - errorMessage: describeRequestError( - err, - errorContext, - routeSpecificErrors - ) - } - } - } - function formatEventType(eventType: string) { switch (eventType) { case 'credit_added': @@ -195,77 +123,7 @@ export const useCustomerEventsService = () => { return (amountMicros / 100).toFixed(2) } - async function getMyEvents({ - page = 1, - limit = 10 - }: CustomerEventsResponseQuery = {}): Promise { - const errorContext = 'Fetching customer events' - const routeSpecificErrors = { - 400: 'Invalid input, object invalid', - 404: 'Not found' - } - - const authStore = useAuthStore() - const requestOwner = authStore.currentUserIdentity() - const requestId = ++latestRequestId - if (!authStore.hasPersonalWorkspace) { - isLoading.value = false - error.value = t('toastMessages.noPersonalWorkspace') - return null - } - isLoading.value = true - error.value = null - - let authHeaders - try { - authHeaders = - (await webSessionResourceHeader()) ?? - (await authStore.getUserAuthHeader()) - } catch (err) { - if (requestId !== latestRequestId) return null - isLoading.value = false - error.value = describeRequestError(err, errorContext) - return null - } - if (requestId !== latestRequestId) { - return null - } - if (authStore.currentUserIdentity() !== requestOwner) { - isLoading.value = false - return null - } - if (!authHeaders) { - isLoading.value = false - error.value = 'Authentication header is missing' - return null - } - - const { data, errorMessage } = await executeRequest( - () => - customerApiClient.get('/customers/events', { - baseURL: getComfyApiBaseUrl(), - params: { page, limit }, - headers: authHeaders - }), - { errorContext, routeSpecificErrors } - ) - - if (requestId !== latestRequestId) { - return null - } - isLoading.value = false - if (authStore.currentUserIdentity() !== requestOwner) { - return null - } - error.value = errorMessage - return data - } - return { - isLoading, - error, - - getMyEvents, formatEventType, getEventSeverity, formatAmount, diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index 0f6368f24a6..7065ae92e44 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -7,15 +7,7 @@ import { FirebaseError } from 'firebase/app' import type { Auth, User, UserCredential } from 'firebase/auth' import * as firebaseAuth from 'firebase/auth' import type { Mock } from 'vitest' -import { - afterEach, - beforeEach, - describe, - expect, - it, - onTestFinished, - vi -} from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' import { useTelemetry } from '@comfyorg/telemetry' @@ -76,9 +68,6 @@ const mockAuth = fromPartial({ currentUser: null }) const CUSTOMERS_URL = /\/customers$/ const CUSTOMER_POST = { method: 'POST', url: CUSTOMERS_URL } -const BALANCE_URL = /\/customers\/balance$/ -const CREDIT_URL = /\/customers\/credit$/ -const BILLING_URL = /\/customers\/billing$/ const customerRequestBody = (): Record | undefined => { const body = fetchRequests(CUSTOMERS_URL)[0]?.body @@ -89,43 +78,6 @@ const customerRequestBody = (): Record | undefined => { const createCustomerResponse = () => Response.json({ id: 'test-customer-id' }) -const balanceResponse = () => Response.json({ balance: 0 }) - -const addCreditsResponse = () => - Response.json({ checkout_url: 'https://stripe.test/checkout' }) - -const accessBillingPortalResponse = () => - Response.json({ billing_portal_url: 'https://billing.stripe.com/test' }) - -const errorResponse = (status: number, message: string) => - Response.json({ message }, { status, statusText: 'Error' }) - -function pendingJsonResponse() { - let signalRead!: () => void - const readStarted = new Promise((resolve) => { - signalRead = resolve - }) - let resolveJson!: (value: unknown) => void - const json = new Promise((resolve) => { - resolveJson = resolve - }) - const response = new Response( - new ReadableStream( - { - async pull(controller) { - signalRead() - controller.enqueue( - new TextEncoder().encode(JSON.stringify(await json)) - ) - controller.close() - } - }, - { highWaterMark: 0 } - ) - ) - return { response, readStarted, resolveJson } -} - vi.mock(import('firebase/auth')) vi.mock(import('@comfyorg/telemetry')) @@ -178,9 +130,6 @@ describe('useAuthStore', () => { ) respondToFetch(CUSTOMERS_URL, createCustomerResponse) - respondToFetch(BALANCE_URL, balanceResponse) - respondToFetch(CREDIT_URL, addCreditsResponse) - respondToFetch(BILLING_URL, accessBillingPortalResponse) store = useAuthStore() await vi.waitFor(() => expect(store.isInitialized).toBe(true)) @@ -265,35 +214,6 @@ describe('useAuthStore', () => { await store.login('test@example.com', 'correct-password') }) - describe('fetchBalance identity isolation', () => { - it('discards a late balance response from the previous account after an A->B switch', async () => { - let signalBalanceRequested: () => void = () => {} - const balanceRequested = new Promise((resolve) => { - signalBalanceRequested = resolve - }) - const balance = pendingJsonResponse() - respondToFetch( - BALANCE_URL, - () => { - signalBalanceRequested() - return balance.response - }, - { times: 1 } - ) - - // Request starts while account A is current. - const pending = store.fetchBalance() - await balanceRequested - - // Firebase transitions directly to account B before the response lands. - authStateCallback({ ...mockUser, uid: 'account-b' }) - balance.resolveJson({ balance: 4242 }) - - expect(await pending).toBeNull() - expect(store.balance).toBeNull() - }) - }) - describe('partner-node session revoke', () => { it.for([ { name: 'sign-out', next: () => null, revokes: 1 }, @@ -314,79 +234,6 @@ describe('useAuthStore', () => { }) }) - describe('fetchBalance', () => { - it('returns null when the customer record is not found (404)', async () => { - respondToFetch( - BALANCE_URL, - () => new Response(null, { status: 404, statusText: 'Not Found' }) - ) - - const result = await store.fetchBalance() - - expect(result).toBeNull() - }) - - it('throws with the parsed error message on a non-404 failure', async () => { - respondToFetch(BALANCE_URL, () => - errorResponse(500, 'Balance service down') - ) - - await expect(store.fetchBalance()).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.failedToFetchBalance', { - error: 'Balance service down' - }) - }) - }) - - it('keeps the status and code on the thrown error', async () => { - respondToFetch(BALANCE_URL, () => - Response.json( - { error: 'SERVICE_UNAVAILABLE', message: 'try again' }, - { status: 503, headers: { 'Retry-After': '3600' } } - ) - ) - - await expect(store.fetchBalance()).rejects.toMatchObject({ - name: 'AuthStoreError', - status: 503, - code: 'SERVICE_UNAVAILABLE' - }) - }) - - it('reports an unknown code when the failure body is not JSON', async () => { - respondToFetch( - BALANCE_URL, - () => - new Response('upstream connect error', { - status: 503, - headers: { 'Retry-After': '3600' } - }) - ) - - await expect(store.fetchBalance()).rejects.toMatchObject({ - status: 503, - code: 'UNKNOWN_ERROR' - }) - }) - - it('returns the balance when a 503 clears on retry', async () => { - vi.useFakeTimers() - let calls = 0 - respondToFetch(BALANCE_URL, () => - ++calls === 1 - ? errorResponse(503, 'Balance temporarily unavailable') - : balanceResponse() - ) - - const pending = store.fetchBalance() - await vi.advanceTimersByTimeAsync(10_000) - - await expect(pending).resolves.toEqual({ balance: 0 }) - expect(calls).toBe(2) - }) - }) - describe('password update', () => { it('updates the signed-in user through the package identity', async () => { vi.spyOn(mockAuth, 'currentUser', 'get').mockReturnValue(mockUser) @@ -460,7 +307,7 @@ describe('useAuthStore', () => { }) }) - describe('user-scoped billing endpoints with API-key sessions', () => { + describe('customer provisioning with API-key sessions', () => { beforeEach(() => { authStateCallback(null) vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ @@ -469,270 +316,6 @@ describe('useAuthStore', () => { vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue('test-api-key') }) - it('fetchBalance sends the stored API key when no Firebase user exists', async () => { - const result = await store.fetchBalance() - - expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/balance'), - expect.objectContaining({ - headers: expect.objectContaining({ 'X-API-KEY': 'test-api-key' }) - }) - ) - expect(result).toEqual({ balance: 0 }) - }) - - it('fetchBalance throws userNotAuthenticated when neither credential exists', async () => { - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue(null) - - await expect(store.fetchBalance()).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - expect(fetch).not.toHaveBeenCalled() - }) - - it('drops a late balance response after the API key changes mid-flight', async () => { - let resolveBalance!: (value: Response) => void - vi.mocked(fetch).mockReturnValueOnce( - new Promise((resolve) => { - resolveBalance = resolve - }) - ) - - const request = store.fetchBalance() - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - resolveBalance(Response.json({ balance: 7 })) - - await expect(request).resolves.toBeNull() - expect(store.balance).toBeNull() - }) - - it('fetchBalance prefers the Firebase token over the API key when signed in', async () => { - authStateCallback(mockUser) - - await store.fetchBalance() - - expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/balance'), - expect.objectContaining({ - headers: expect.objectContaining({ - Authorization: 'Bearer mock-id-token' - }) - }) - ) - expect(useApiKeyAuthStore().getAuthHeader).not.toHaveBeenCalled() - }) - - it('initiateCreditPurchase sends the stored API key when no Firebase user exists', async () => { - await store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - - expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/credit'), - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ 'X-API-KEY': 'test-api-key' }) - }) - ) - }) - - it('accessBillingPortal sends the stored API key when no Firebase user exists', async () => { - respondToFetch(BILLING_URL, () => - Response.json({ billing_portal_url: 'https://stripe.test/portal' }) - ) - - await store.accessBillingPortal() - - expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/billing'), - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ 'X-API-KEY': 'test-api-key' }) - }) - ) - }) - - it('accessBillingPortal gives up on a billing request that hangs for 30 seconds', async () => { - vi.useFakeTimers() - onTestFinished(() => { - vi.useRealTimers() - }) - vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => { - const controller = new AbortController() - setTimeout( - () => - controller.abort( - new DOMException('The operation timed out.', 'TimeoutError') - ), - ms - ) - return controller.signal - }) - respondToFetch( - BILLING_URL, - (_input, init) => - new Promise((_resolve, reject) => { - init?.signal?.addEventListener('abort', () => - reject(init.signal?.reason) - ) - }) - ) - - const request = store.accessBillingPortal() - const settled = vi.fn() - request.then(settled, settled) - await vi.advanceTimersByTimeAsync(29_999) - expect(settled).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(1) - await expect(request).rejects.toMatchObject({ name: 'TimeoutError' }) - }) - - it('accessBillingPortal throws userNotAuthenticated when neither credential exists', async () => { - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue(null) - - await expect(store.accessBillingPortal()).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - expect(fetch).not.toHaveBeenCalled() - }) - it('re-provisions the customer after the API key changes', async () => { - const payload = { amount_micros: 5_000_000, currency: 'usd' } - - await store.initiateCreditPurchase(payload) - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - await store.initiateCreditPurchase(payload) - - expect(fetchRequests(CUSTOMER_POST)).toHaveLength(2) - }) - - it('does not retry with the old API key after a mid-recovery switch', async () => { - let resolveCreate!: (value: Response) => void - respondToFetch( - CUSTOMER_POST, - () => - new Promise((resolve) => { - resolveCreate = resolve - }) - ) - respondToFetch(BILLING_URL, () => - Response.json({ message: 'Failed to find customer' }, { status: 409 }) - ) - - const request = store.accessBillingPortal() - await new Promise((resolve) => setTimeout(resolve, 0)) - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - resolveCreate(createCustomerResponse()) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - expect(fetchRequests(BILLING_URL)).toHaveLength(1) - }) - - it('aborts a credit purchase when the API key changes during recovery', async () => { - let resolveCreate!: (value: Response) => void - respondToFetch( - CUSTOMER_POST, - () => - new Promise((resolve) => { - resolveCreate = resolve - }) - ) - - const request = store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - await new Promise((resolve) => setTimeout(resolve, 0)) - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - resolveCreate(createCustomerResponse()) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - expect(fetchRequests(CREDIT_URL)).toEqual([]) - }) - - it('withholds a portal URL that succeeds after an A->B API key switch', async () => { - let resolveBilling!: (value: Response) => void - const billingRequestStarted = new Promise((requestStarted) => { - respondToFetch(BILLING_URL, () => { - requestStarted() - return new Promise((resolve) => { - resolveBilling = resolve - }) - }) - }) - - const request = store.accessBillingPortal() - await billingRequestStarted - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - resolveBilling( - Response.json({ billing_portal_url: 'https://stripe.test/portal' }) - ) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - - it('withholds a checkout URL that succeeds after an A->B API key switch', async () => { - let resolveCredit!: (value: Response) => void - const creditRequestStarted = new Promise((requestStarted) => { - respondToFetch(CREDIT_URL, () => { - requestStarted() - return new Promise((resolve) => { - resolveCredit = resolve - }) - }) - }) - - const request = store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - await creditRequestStarted - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - resolveCredit( - Response.json({ checkout_url: 'https://stripe.test/checkout' }) - ) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - it('rejects a customer record created before an A->B API key switch', async () => { let resolveCreate!: (value: Response) => void const createRequestStarted = new Promise((requestStarted) => { @@ -760,47 +343,6 @@ describe('useAuthStore', () => { }) }) - it('withholds a portal URL when the API key changes while the body parses', async () => { - const portal = pendingJsonResponse() - respondToFetch(BILLING_URL, () => portal.response, { times: 1 }) - - const request = store.accessBillingPortal() - await portal.readStarted - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - portal.resolveJson({ billing_portal_url: 'https://stripe.test/portal' }) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - - it('withholds a checkout URL when the API key changes while the body parses', async () => { - const credit = pendingJsonResponse() - respondToFetch(CREDIT_URL, () => credit.response, { times: 1 }) - - const request = store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - await credit.readStarted - vi.mocked(useApiKeyAuthStore().getApiKey).mockReturnValue( - 'another-api-key' - ) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue({ - 'X-API-KEY': 'another-api-key' - }) - credit.resolveJson({ checkout_url: 'https://stripe.test/checkout' }) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - const accountAFailureResponse = () => Response.json( { message: 'account A backend error' }, @@ -816,71 +358,6 @@ describe('useAuthStore', () => { }) } - it('suppresses a balance error that rejects after an A->B API key switch', async () => { - let resolveBalance!: (value: Response) => void - const balanceRequestStarted = new Promise((requestStarted) => { - respondToFetch(BALANCE_URL, () => { - requestStarted() - return new Promise((resolve) => { - resolveBalance = resolve - }) - }) - }) - - const request = store.fetchBalance() - await balanceRequestStarted - switchToAnotherApiKey() - resolveBalance(accountAFailureResponse()) - - await expect(request).resolves.toBeNull() - expect(store.balance).toBeNull() - }) - - it('withholds a checkout error that rejects after an A->B API key switch', async () => { - let resolveCredit!: (value: Response) => void - const creditRequestStarted = new Promise((requestStarted) => { - respondToFetch(CREDIT_URL, () => { - requestStarted() - return new Promise((resolve) => { - resolveCredit = resolve - }) - }) - }) - - const request = store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - await creditRequestStarted - switchToAnotherApiKey() - resolveCredit(accountAFailureResponse()) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - - it('withholds a portal error that rejects after an A->B API key switch', async () => { - let resolveBilling!: (value: Response) => void - const billingRequestStarted = new Promise((requestStarted) => { - respondToFetch(BILLING_URL, () => { - requestStarted() - return new Promise((resolve) => { - resolveBilling = resolve - }) - }) - }) - - const request = store.accessBillingPortal() - await billingRequestStarted - switchToAnotherApiKey() - resolveBilling(accountAFailureResponse()) - - await expect(request).rejects.toMatchObject({ - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - it('withholds a customer-creation error that rejects after an A->B API key switch', async () => { let resolveCreate!: (value: Response) => void const createRequestStarted = new Promise((requestStarted) => { @@ -1775,152 +1252,6 @@ describe('useAuthStore', () => { }) }) - describe('accessBillingPortal', () => { - it('should call billing endpoint without body when no targetTier provided', async () => { - const result = await store.accessBillingPortal() - - expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/billing'), - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ - Authorization: 'Bearer mock-id-token', - 'Content-Type': 'application/json' - }) - }) - ) - - const callArgs = vi - .mocked(fetch) - .mock.calls.find(([url]) => String(url).endsWith('/customers/billing')) - expect(callArgs?.[1]).not.toHaveProperty('body') - expect(result).toEqual({ - billing_portal_url: 'https://billing.stripe.com/test' - }) - }) - - it('sends cancel_subscription only when requested, and never with a target tier', async () => { - const bodyOf = () => fetchRequests(BILLING_URL).at(-1)?.body - - await store.accessBillingPortal(undefined, { cancelSubscription: true }) - expect(JSON.parse(String(bodyOf()))).toEqual({ - cancel_subscription: true - }) - - await expect( - store.accessBillingPortal('creator', { cancelSubscription: true }) - ).rejects.toThrow(/target tier/) - - await store.accessBillingPortal(undefined, { cancelSubscription: false }) - expect(bodyOf()).toBeUndefined() - }) - - it('should include target_tier in request body when targetTier provided', async () => { - await store.accessBillingPortal('creator') - - const [billingRequest] = fetchRequests(BILLING_URL) - expect(billingRequest.body).toBeDefined() - expect(JSON.parse(String(billingRequest.body))).toEqual({ - target_tier: 'creator' - }) - }) - - it.for([ - 'standard', - 'creator', - 'pro', - 'standard-yearly', - 'creator-yearly', - 'pro-yearly' - ] as const)('sends the %s checkout tier format', async (tier) => { - await store.accessBillingPortal(tier) - - expect(JSON.parse(String(fetchRequests(BILLING_URL)[0].body))).toEqual({ - target_tier: tier - }) - }) - - it('should throw error when API returns error response', async () => { - vi.mocked(fetch).mockResolvedValueOnce( - Response.json( - { message: 'Billing portal unavailable' }, - { status: 500 } - ) - ) - - await expect(store.accessBillingPortal()).rejects.toThrow() - }) - - it('surfaces the parsed error message on a failed response', async () => { - vi.mocked(fetch).mockResolvedValueOnce( - errorResponse(503, 'Billing portal unavailable') - ) - - await expect(store.accessBillingPortal()).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.failedToAccessBillingPortal', { - error: 'Billing portal unavailable' - }) - }) - }) - - it('throws when no authentication method is available', async () => { - authStateCallback(null) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue(null) - - await expect(store.accessBillingPortal()).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - }) - - describe('addCredits / initiateCreditPurchase', () => { - it('throws when no authentication method is available', async () => { - authStateCallback(null) - vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue(null) - - await expect( - store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - ).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - }) - - it('surfaces the parsed error message on a failed response', async () => { - respondToFetch(CREDIT_URL, () => errorResponse(402, 'Card declined')) - - await expect( - store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - ).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.failedToInitiateCreditPurchase', { - error: 'Card declined' - }), - status: 402 - }) - }) - - it('skips the customer pre-flight once a customer is known to exist', async () => { - await store.createCustomer() - vi.mocked(fetch).mockClear() - - await store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - - expect(customerRequestBody()).toBeUndefined() - }) - }) - describe('getAuthHeaderOrThrow', () => { it('returns auth header when authenticated', async () => { const header = await store.getAuthHeaderOrThrow() @@ -2058,350 +1389,6 @@ describe('useAuthStore', () => { }) }) }) - - it('rejects a customer record created before an A->B Firebase identity switch', async () => { - let signalCustomerRequested: () => void = () => {} - const customerRequested = new Promise((resolve) => { - signalCustomerRequested = resolve - }) - const customer = pendingJsonResponse() - respondToFetch( - CUSTOMERS_URL, - () => { - signalCustomerRequested() - return customer.response - }, - { times: 1 } - ) - - // The auth header is resolved for account A; only the response body - // (fetched below) races the A->B switch. - const createPromise = store.createCustomer() - await customerRequested - authStateCallback({ ...mockUser, uid: 'different-user-id' }) - customer.resolveJson({ id: 'test-customer-id' }) - - await expect(createPromise).rejects.toMatchObject({ - name: 'AuthStoreError', - message: i18n.global.t('toastMessages.userNotAuthenticated') - }) - - // A subsequent credit pre-flight must still provision a customer for - // this (different) identity rather than trusting the stale flag. - vi.mocked(fetch).mockClear() - - await store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - - expect(customerRequestBody()).toEqual({ signup_source: 'cloud' }) - }) - }) - - describe('fetchWithCustomerRecovery', () => { - const BALANCE_ENDPOINT = 'https://api.test/customers/balance' - - function make409(message: string) { - return Response.json({ message }, { status: 409, statusText: 'Conflict' }) - } - function makeConflictResponse() { - return make409('Failed to find customer') - } - - function countCustomerPosts() { - return fetchRequests(CUSTOMER_POST).length - } - - it('should provision the customer and retry once when a /customers/* call returns 409', async () => { - respondToFetch(BALANCE_URL, makeConflictResponse, { times: 1 }) - - const result = await store.fetchBalance() - - expect(result).toEqual({ balance: 0 }) - expect(fetchRequests(BALANCE_URL)).toHaveLength(2) - expect(countCustomerPosts()).toBe(1) - }) - - it('should deduplicate concurrent recovery attempts into a single customer creation', async () => { - const seenUrls = new Set() - vi.mocked(fetch).mockImplementation(async (input, init) => { - const url = String(input) - if (url.endsWith('/customers') && init?.method === 'POST') { - return createCustomerResponse() - } - if (!seenUrls.has(url)) { - seenUrls.add(url) - return makeConflictResponse() - } - return Response.json({}) - }) - - const [first, second] = await Promise.all([ - store.fetchWithCustomerRecovery('https://api.test/customers/balance'), - store.fetchWithCustomerRecovery( - 'https://api.test/customers/cloud-subscription-status' - ) - ]) - - expect(first.ok).toBe(true) - expect(second.ok).toBe(true) - expect(countCustomerPosts()).toBe(1) - }) - - it('should not provision the customer again after a successful recovery', async () => { - // Endpoint keeps conflicting even after recovery succeeds - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse) - - const first = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - const second = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - - expect(first.status).toBe(409) - expect(second.status).toBe(409) - expect(countCustomerPosts()).toBe(1) - }) - - it('should return the original 409 response when customer provisioning fails', async () => { - respondToFetch( - CUSTOMER_POST, - () => - new Response(null, { - status: 500, - statusText: 'Internal Server Error' - }) - ) - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(1) - }) - - it('should pass through non-409 responses without provisioning', async () => { - vi.mocked(fetch).mockResolvedValueOnce(Response.json({})) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - - expect(response.ok).toBe(true) - expect(countCustomerPosts()).toBe(0) - }) - - it('should not provision for a 409 that is not a missing-customer conflict', async () => { - vi.mocked(fetch).mockResolvedValueOnce( - make409('Subscription already active') - ) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/cloud-subscription-checkout/standard', - { method: 'POST' } - ) - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(0) - }) - - it('should not provision for a 409 from a non-customer endpoint', async () => { - vi.mocked(fetch).mockResolvedValueOnce(makeConflictResponse()) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/workflows' - ) - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(0) - }) - - it('should not provision when /customers/ is not the root path segment', async () => { - vi.mocked(fetch).mockResolvedValueOnce(makeConflictResponse()) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/foo/customers/bar' - ) - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(0) - }) - - it('does not treat an unparsable URL as a customer endpoint', async () => { - vi.mocked(fetch).mockResolvedValueOnce(makeConflictResponse()) - - const response = await store.fetchWithCustomerRecovery('http://') - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(0) - }) - - it('passes through a 409 whose body cannot be parsed without provisioning', async () => { - vi.mocked(fetch).mockResolvedValueOnce( - new Response('invalid json', { status: 409, statusText: 'Conflict' }) - ) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(0) - }) - - it('should re-provision after the auth state changes to a different session', async () => { - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse) - - await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - expect(countCustomerPosts()).toBe(1) - - // Sign out, then a different account signs in: the memoized recovery - // from the previous account must not short-circuit the new one. - authStateCallback(null) - authStateCallback(mockUser) - - await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - expect(countCustomerPosts()).toBe(2) - }) - - it('re-provisions when the active uid changes without an auth-state reset', async () => { - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse) - - await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - expect(countCustomerPosts()).toBe(1) - - // A uid change that did not pass through onAuthStateChanged (which would - // otherwise clear the memo) must still start a fresh recovery rather than - // reuse the previous account's settled one. - store.currentUser = { - ...mockUser, - uid: 'different-uid' - } as Partial as User - - await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - expect(countCustomerPosts()).toBe(2) - }) - - it('should return the original 409 when the retry fails at the network level', async () => { - respondToFetch(BALANCE_ENDPOINT, () => - Promise.reject(new TypeError('network down')) - ) - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse, { times: 1 }) - - const response = await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - - expect(response.status).toBe(409) - expect(countCustomerPosts()).toBe(1) - }) - - it('should share one customer creation between concurrent credit pre-flights', async () => { - await Promise.all([ - store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }), - store.initiateCreditPurchase({ - amount_micros: 5_000_000, - currency: 'usd' - }) - ]) - - expect(countCustomerPosts()).toBe(1) - }) - - it('stale rejection from previous session does not null out a new in-flight recovery', async () => { - let rejectSession1Create!: (reason: unknown) => void - let resolveSession2Create!: (value: Response) => void - - const session1CreateP = new Promise((_, reject) => { - rejectSession1Create = reject - }) - const session2CreateP = new Promise((resolve) => { - resolveSession2Create = resolve - }) - - respondToFetch(CUSTOMER_POST, () => session2CreateP) - respondToFetch(CUSTOMER_POST, () => session1CreateP, { times: 1 }) - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse) - - // Session 1: trigger a recovery whose POST will hang - const session1Done = store - .fetchWithCustomerRecovery('https://api.test/customers/balance') - .then(() => 'session1') - .catch(() => 'session1-failed') - - // Drain microtasks so session1's POST is registered - await new Promise((resolve) => setTimeout(resolve, 0)) - - // Auth resets; new session starts - authStateCallback(null) - authStateCallback(mockUser) - - // Session 2 recovery — should create a new independent in-flight promise - const session2Done = store - .fetchWithCustomerRecovery('https://api.test/customers/balance') - .then(() => 'session2') - .catch(() => 'session2-failed') - - await new Promise((resolve) => setTimeout(resolve, 0)) - - // Session 1's POST fails — stale rejection fires; must NOT null out session 2's recovery - rejectSession1Create(new Error('network error')) - await session1Done - - // Session 2's POST resolves successfully - resolveSession2Create(Response.json({ id: 'id-2' })) - const session2Result = await session2Done - - // Session 2 must succeed, proving its recovery was not nulled by session 1's rejection - expect(session2Result).toBe('session2') - }) - - it('does not skip re-provisioning when createCustomer resolves after sign-out', async () => { - let resolveCreate!: (value: Response) => void - const slowCreateP = new Promise((resolve) => { - resolveCreate = resolve - }) - - respondToFetch(CUSTOMER_POST, () => slowCreateP, { times: 1 }) - respondToFetch(BALANCE_ENDPOINT, makeConflictResponse) - - // Session 1 triggers recovery with a slow POST - const session1Done = store - .fetchWithCustomerRecovery('https://api.test/customers/balance') - .catch(() => {}) - - await new Promise((resolve) => setTimeout(resolve, 0)) - - // User signs out before the POST resolves - authStateCallback(null) - authStateCallback(mockUser) - - // Stale POST resolves successfully after session reset - resolveCreate(Response.json({ id: 'stale-id' })) - await session1Done - - // A fresh recovery for the new session must POST again; - // customerCreated must not have been set by the stale resolution. - await store.fetchWithCustomerRecovery( - 'https://api.test/customers/balance' - ) - expect(countCustomerPosts()).toBe(2) - }) }) describe('realtime socket identity lifecycle', () => { @@ -2794,30 +1781,6 @@ describe('useAuthStore in local/desktop distribution', () => { }) }) - it('drops the previous account state when Desktop switches accounts', async () => { - const bridge = hostBridge({ status: 'signed_in', userId: 'host-a' }) - await startDesktopHostSession(bridge) - const resetTeams = vi.spyOn( - useTeamWorkspaceStore(), - 'resetForIdentityChange' - ) - const clearWorkspace = vi.spyOn( - useWorkspaceAuthStore(), - 'clearWorkspaceContext' - ) - store.balance = fromPartial>({ - amount_micros: 5 - }) - - bridge.push({ status: 'signed_in', userId: 'host-b' }) - await nextTick() - - expect(store.userId).toBe('host-b') - expect(resetTeams).toHaveBeenCalledOnce() - expect(clearWorkspace).toHaveBeenCalledOnce() - expect(store.balance).toBeNull() - }) - it('signs Desktop out on logout and drops an earlier stored API key', async () => { const apiKeyStore = useApiKeyAuthStore() let storedKey: string | null = 'stored-key' diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index d6da6694b39..00a1956a1b6 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -7,7 +7,6 @@ import type { PopupSignInOptions } from '@comfyorg/account-core/firebase' import { defineStore } from 'pinia' import { computed, ref, watch } from 'vue' -import { fetchWithCustomerRecovery as fetchHealingMissingCustomer } from '@comfyorg/account-core/customerRecovery' import { isSsoRequiredRefusal, ssoRequiredOrganizationId @@ -53,26 +52,13 @@ import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { provideAuthStore } from '@/platform/auth/authStoreAccess' import type { AuthHeader } from '@comfyorg/api-client/authTypes' import type { operations } from '@/types/comfyRegistryTypes' -import { parseErrorResponse } from '@/platform/remote/comfyui/errors' import { useFeatureFlags } from '@/composables/useFeatureFlags' -const BILLING_PORTAL_REQUEST_TIMEOUT_MS = 30_000 - -type CreditPurchaseResponse = - operations['InitiateCreditPurchase']['responses']['201']['content']['application/json'] -type CreditPurchasePayload = - operations['InitiateCreditPurchase']['requestBody']['content']['application/json'] type CreateCustomerResponse = operations['createCustomer']['responses']['201']['content']['application/json'] type CreateCustomerPayload = NonNullable< operations['createCustomer']['requestBody'] >['content']['application/json'] -type GetCustomerBalanceResponse = - operations['GetCustomerBalance']['responses']['200']['content']['application/json'] -type AccessBillingPortalResponse = - operations['AccessBillingPortal']['responses']['200']['content']['application/json'] -type AccessBillingPortalReqBody = - operations['AccessBillingPortal']['requestBody'] export interface SocialSignInOptions { readonly isNewUser?: boolean /** How a closed popup's late result is finished or discarded. */ @@ -81,12 +67,6 @@ export interface SocialSignInOptions { readonly resumed?: Promise } -export type BillingPortalTargetTier = NonNullable< - NonNullable< - NonNullable['content'] - >['application/json'] ->['target_tier'] - /** `AuthStoreError.code` for a `/customers/*` call skipped because the account has no personal workspace. */ export const NO_PERSONAL_WORKSPACE = 'no_personal_workspace' @@ -144,16 +124,6 @@ export const useAuthStore = defineStore('auth', () => { const loading = ref(false) const currentUser = ref(null) const isInitialized = ref(false) - const customerProvisionedIdentity = ref(null) - /** - * Memoizes the in-flight or successful customer provisioning attempt for - * the current account (see recoverMissingCustomer). Declared here so the - * auth-state listener below can reset it before its initializer would - * otherwise run. - */ - let customerRecovery: Promise | null = null - let customerRecoveryIdentity: string | null = null - const isFetchingBalance = ref(false) const mintUnifiedToken = useMemoize((uid: string) => useWorkspaceAuthStore() .mintAtLogin() @@ -163,10 +133,6 @@ export const useAuthStore = defineStore('auth', () => { }) ) - // Balance state - const balance = ref(null) - const lastBalanceUpdateTime = ref(null) - // Token refresh trigger - increments when token is refreshed const tokenRefreshTrigger = ref(0) /** @@ -260,17 +226,6 @@ export const useAuthStore = defineStore('auth', () => { if (isCloud && identityChanged) { void api.resetSocket() } - - // Reset balance when auth state changes - balance.value = null - lastBalanceUpdateTime.value = null - - // Customer provisioning state is per-account: without this reset, a - // second account in the same browser session would be short-circuited by - // the previous account's memoized recovery and stay stuck on 409s. - customerProvisionedIdentity.value = null - customerRecovery = null - customerRecoveryIdentity = null } firebaseIdentity.onUserChanged((user) => { @@ -480,17 +435,6 @@ export const useAuthStore = defineStore('auth', () => { currentUser.value?.uid ?? useApiKeyAuthStore().getApiKey()) - const currentUserCredentialIdentity = (): string | null => - currentUser.value?.uid ?? useApiKeyAuthStore().getApiKey() - - /** - * Response data from a user-scoped endpoint belongs to the identity that - * asked for it. A 200 bypasses the recovery guards in - * fetchWithCustomerRecovery, which only fence the missing-customer retry, so - * a credential swap while the request was in flight would hand the previous - * account's data to the current session — a Stripe portal or checkout URL - * minted for A opening inside B. - */ const assertIdentityUnchanged = (requestOwner: string | null): void => { if (currentUserIdentity() !== requestOwner) { throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) @@ -684,63 +628,6 @@ export const useAuthStore = defineStore('auth', () => { return token } - const fetchBalance = async (): Promise => { - if (!hasPersonalWorkspace.value) return null - isFetchingBalance.value = true - const requestOwner = currentUserIdentity() - const requestCredential = currentUserCredentialIdentity() - const requestIsCurrent = () => - currentUserIdentity() === requestOwner && - currentUserCredentialIdentity() === requestCredential - try { - const authHeader = await getCustomerAuthHeader() - if (!authHeader) { - throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) - } - - const response = await fetchWithCustomerRecovery( - buildApiUrl('/customers/balance'), - { - headers: { - ...authHeader, - 'Content-Type': 'application/json' - } - } - ) - - if (!response.ok) { - if (response.status === 404) { - // Customer not found is expected for new users - return null - } - const { message, code } = await parseErrorResponse(response) - if (!requestIsCurrent()) { - return null - } - throw new AuthStoreError( - t('toastMessages.failedToFetchBalance', { - error: message - }), - response.status, - code - ) - } - - const balanceData = await response.json() - // Session identity and request credentials can change independently; - // a late response must still match both. - if (!requestIsCurrent()) { - return null - } - // Update the last balance update time - lastBalanceUpdateTime.value = new Date() - balance.value = balanceData - return balanceData - } finally { - isFetchingBalance.value = false - } - } - const createCustomer = async ( payload?: Omit, completedCredential?: UserCredential @@ -802,59 +689,9 @@ export const useAuthStore = defineStore('auth', () => { } if (!completedUser) assertIdentityUnchanged(sessionIdentity) - if (sessionIdentity !== null) { - customerProvisionedIdentity.value = sessionIdentity - } return createCustomerResJson } - /** - * Memoizes the customer provisioning attempt so concurrent or repeated 409 - * responses from /customers/* endpoints trigger at most one successful - * POST /customers per account. A failed attempt is cleared so a later - * request can retry, e.g. after a transient network failure. - */ - const recoverMissingCustomer = (): Promise => { - const sessionIdentity = currentUserIdentity() - if ( - customerRecovery === null || - customerRecoveryIdentity !== sessionIdentity - ) { - const thisRecovery: Promise = createCustomer() - .then(() => undefined) - .catch((error: unknown) => { - if (customerRecovery === thisRecovery) { - customerRecovery = null - customerRecoveryIdentity = null - } - throw error - }) - customerRecovery = thisRecovery - customerRecoveryIdentity = sessionIdentity - } - return customerRecovery - } - - /** /customers/* fetch that self-heals a never-provisioned account (rule in @comfyorg/account-core). */ - const fetchWithCustomerRecovery = async ( - input: string, - init?: RequestInit - ): Promise => { - assertHasPersonalWorkspace() - const requestOwner = currentUserIdentity() - return fetchHealingMissingCustomer(input, { - request: () => - fetchWithUnifiedRemint( - input, - init ?? {}, - isCloud && flags.unifiedCloudAuthEnabled - ), - recoverMissingCustomer, - identityUnchanged: () => currentUserIdentity() === requestOwner, - base: window.location.href - }) - } - const executeAuthAction = async ( action: () => Promise, options: { @@ -1047,117 +884,11 @@ export const useAuthStore = defineStore('auth', () => { await firebaseIdentity.updatePassword(newPassword) } - const addCredits = async ( - requestBodyContent: CreditPurchasePayload - ): Promise => { - const requestOwner = currentUserIdentity() - const authHeader = await getCustomerAuthHeader() - if (!authHeader) { - throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) - } - - // Ensure customer was created during login/registration. Routed through - // recoverMissingCustomer so a concurrent 409-triggered recovery and this - // pre-flight share one POST /customers instead of racing. - if (customerProvisionedIdentity.value !== requestOwner) { - await recoverMissingCustomer() - if (currentUserIdentity() !== requestOwner) { - throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) - } - } - - const response = await fetchWithCustomerRecovery( - buildApiUrl('/customers/credit'), - { - method: 'POST', - headers: { - ...authHeader, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(requestBodyContent) - } - ) - - if (!response.ok) { - const { message, code } = await parseErrorResponse(response) - assertIdentityUnchanged(requestOwner) - throw new AuthStoreError( - t('toastMessages.failedToInitiateCreditPurchase', { - error: message - }), - response.status, - code - ) - } - - const creditPurchase: CreditPurchaseResponse = await response.json() - assertIdentityUnchanged(requestOwner) - return creditPurchase - } - - const initiateCreditPurchase = async ( - requestBodyContent: CreditPurchasePayload - ): Promise => - executeAuthAction(() => addCredits(requestBodyContent)) - - const accessBillingPortal = async ( - targetTier?: BillingPortalTargetTier, - options?: { cancelSubscription?: boolean } - ): Promise => { - if (targetTier && options?.cancelSubscription) { - throw new AuthStoreError( - 'cancelSubscription cannot be combined with a target tier' - ) - } - const requestOwner = currentUserIdentity() - const authHeader = await getCustomerAuthHeader() - if (!authHeader) { - throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) - } - - const response = await fetchWithCustomerRecovery( - buildApiUrl('/customers/billing'), - { - method: 'POST', - signal: AbortSignal.timeout(BILLING_PORTAL_REQUEST_TIMEOUT_MS), - headers: { - ...authHeader, - 'Content-Type': 'application/json' - }, - ...(targetTier && { - body: JSON.stringify({ target_tier: targetTier }) - }), - ...(options?.cancelSubscription === true && { - body: JSON.stringify({ cancel_subscription: true }) - }) - } - ) - - if (!response.ok) { - const { message, code } = await parseErrorResponse(response) - assertIdentityUnchanged(requestOwner) - throw new AuthStoreError( - t('toastMessages.failedToAccessBillingPortal', { - error: message - }), - response.status, - code - ) - } - - const billingPortal: AccessBillingPortalResponse = await response.json() - assertIdentityUnchanged(requestOwner) - return billingPortal - } - return { // State loading, currentUser, isInitialized, - balance, - lastBalanceUpdateTime, - isFetchingBalance, tokenRefreshTrigger, // Getters @@ -1174,13 +905,9 @@ export const useAuthStore = defineStore('auth', () => { register, logout, createCustomer, - fetchWithCustomerRecovery, getIdToken, loginWithGoogle, loginWithGithub, - initiateCreditPurchase, - fetchBalance, - accessBillingPortal, sendPasswordReset, updatePassword: _updatePassword, getAuthHeader, diff --git a/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts b/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts index 4395682c97e..4fd9106f607 100644 --- a/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts +++ b/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts @@ -11,9 +11,9 @@ import { effectScope, nextTick, computed } from 'vue' import type { Ref } from 'vue' import { storeToRefs } from 'pinia' import { fromPartial } from '@total-typescript/shoehorn' -import { useAuthStore } from '@/stores/authStore' import { useSubscription } from '@/platform/billing/subscription/composables/useSubscription' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useAuthStore } from '@/stores/authStore' import { useWorkspaceBillingStateStore } from '@/platform/billing/stores/workspaceBillingStateStore' import { useAgentDockMount } from '@/workbench/extensions/agent/composables/useAgentDockMount' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' @@ -148,9 +148,7 @@ describe('useAgentDockMount with the real billing context', () => { }) ) }) - const authStore = useAuthStore() - authStore.balance = { currency: 'usd', amount_micros: 5000000 } - vi.mocked(authStore.fetchBalance).mockResolvedValue(authStore.balance) + useAuthStore() vi.mocked(workspaceStore.updateActiveWorkspace).mockImplementation(() => {}) remoteConfig.value = {} remoteConfigState.value = 'unloaded'