Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ import SubscribeButton from '@/platform/cloud/subscription/components/SubscribeB
import SubscriptionBenefits from '@/platform/cloud/subscription/components/SubscriptionBenefits.vue'
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { isCloud } from '@/platform/distribution/types'
import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription'
import { useTelemetry } from '@/platform/telemetry'
import { useCommandStore } from '@/stores/commandStore'
import type { SubscriptionDialogReason } from '@/platform/cloud/subscription/composables/useSubscriptionDialog'
Expand All @@ -169,7 +170,8 @@ const emit = defineEmits<{
close: [subscribed: boolean]
}>()

const { fetchStatus, isActiveSubscription } = useBillingContext()
const { isActiveSubscription } = useBillingContext()
const { syncStatusAfterCheckout } = useSubscription()

const isSubscriptionEnabled = (): boolean =>
Boolean(isCloud && window.__CONFIG__?.subscription_required)
Expand All @@ -190,48 +192,20 @@ const telemetry = useTelemetry()
// Always show custom pricing table for cloud subscriptions
const showCustomPricingTable = computed(() => isSubscriptionEnabled())

const POLL_INTERVAL_MS = 3000
const MAX_POLL_ATTEMPTS = 3
let pollInterval: number | null = null
let pollAttempts = 0

const stopPolling = () => {
if (pollInterval) {
clearInterval(pollInterval)
pollInterval = null
}
}

const startPolling = () => {
stopPolling()
pollAttempts = 0

const poll = async () => {
try {
await fetchStatus()
pollAttempts++

if (pollAttempts >= MAX_POLL_ATTEMPTS) {
stopPolling()
}
} catch (error) {
console.error(
'[SubscriptionDialog] Failed to poll subscription status',
error
)
stopPolling()
}
const refreshSubscriptionStatus = async () => {
try {
await syncStatusAfterCheckout()
} catch (error) {
console.error(
'[SubscriptionDialog] Failed to refresh subscription status',
error
)
}

void poll()
pollInterval = window.setInterval(() => {
void poll()
}, POLL_INTERVAL_MS)
}

const handleWindowFocus = () => {
if (showCustomPricingTable.value) {
startPolling()
void refreshSubscriptionStatus()
}
}

Expand All @@ -242,7 +216,6 @@ watch(
window.addEventListener('focus', handleWindowFocus)
} else {
window.removeEventListener('focus', handleWindowFocus)
stopPolling()
}
},
{ immediate: true }
Expand All @@ -252,7 +225,6 @@ watch(
() => isActiveSubscription.value,
(isActive) => {
if (isActive && showCustomPricingTable.value) {
telemetry?.trackMonthlySubscriptionSucceeded()
emit('close', true)
}
}
Expand All @@ -263,7 +235,6 @@ const handleSubscribed = () => {
}

const handleChooseTeam = () => {
stopPolling()
if (onChooseTeam) {
onChooseTeam()
} else {
Expand All @@ -272,7 +243,6 @@ const handleChooseTeam = () => {
}

const handleClose = () => {
stopPolling()
onClose()
}

Expand All @@ -295,7 +265,6 @@ const handleViewEnterprise = () => {
}

onBeforeUnmount(() => {
stopPolling()
window.removeEventListener('focus', handleWindowFocus)
})
</script>
Expand Down
177 changes: 169 additions & 8 deletions src/platform/cloud/subscription/composables/useSubscription.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const {
})),
mockTelemetry: {
trackSubscription: vi.fn(),
trackMonthlySubscriptionSucceeded: vi.fn(),
trackMonthlySubscriptionCancelled: vi.fn()
},
mockUserId: { value: 'user-123' }
Expand Down Expand Up @@ -134,20 +135,40 @@ describe('useSubscription', () => {
vi.clearAllMocks()
mockIsLoggedIn.value = false
mockTelemetry.trackSubscription.mockReset()
mockTelemetry.trackMonthlySubscriptionSucceeded.mockReset()
mockTelemetry.trackMonthlySubscriptionCancelled.mockReset()
mockUserId.value = 'user-123'
mockIsCloud.value = true
window.__CONFIG__ = {
subscription_required: true
} as typeof window.__CONFIG__
vi.mocked(global.fetch).mockResolvedValue({
ok: true,
json: async () => ({
is_active: false,
subscription_id: '',
renewal_date: ''
})
} as Response)
localStorage.clear()
vi.mocked(global.fetch).mockImplementation(async (input) => {
const url = String(input)

if (url.includes('/customers/pending-subscription-success/')) {
return {
ok: true,
status: 204
} as Response
}

if (url.includes('/customers/pending-subscription-success')) {
return {
ok: true,
status: 204
} as Response
}

return {
ok: true,
json: async () => ({
is_active: false,
subscription_id: '',
renewal_date: ''
})
} as Response
})
})

describe('computed properties', () => {
Expand Down Expand Up @@ -275,6 +296,146 @@ describe('useSubscription', () => {

await expect(fetchStatus()).rejects.toThrow()
})

it('syncs and consumes pending subscription success when requested', async () => {
vi.mocked(global.fetch).mockImplementation(async (input) => {
const url = String(input)

if (url.includes('/customers/cloud-subscription-status')) {
return {
ok: true,
json: async () => ({
is_active: true,
subscription_id: 'sub_123',
renewal_date: '2025-11-16'
})
} as Response
}

if (url.endsWith('/customers/pending-subscription-success')) {
return {
ok: true,
status: 200,
json: async () => ({
id: 'event-123',
transaction_id: 'stripe-event-123',
value: 35,
currency: 'USD',
tier: 'creator',
cycle: 'monthly',
checkout_type: 'change',
previous_tier: 'standard'
})
} as Response
}

if (
url.endsWith(
'/customers/pending-subscription-success/event-123/consume'
)
) {
return {
ok: true,
status: 204
} as Response
}

throw new Error(`Unexpected fetch URL: ${url}`)
})

const { syncStatusAfterCheckout } = useSubscriptionWithScope()

await syncStatusAfterCheckout()

expect(
mockTelemetry.trackMonthlySubscriptionSucceeded
).toHaveBeenCalledWith(
expect.objectContaining({
transaction_id: 'stripe-event-123',
value: 35,
currency: 'USD',
tier: 'creator',
cycle: 'monthly',
checkout_type: 'change',
previous_tier: 'standard'
})
)
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining(
'/customers/pending-subscription-success/event-123/consume'
),
expect.objectContaining({
method: 'POST'
})
)
})

it('does not retrack a subscription success already delivered in this browser', async () => {
localStorage.setItem(
'comfy.subscription_success.delivered_transactions',
JSON.stringify(['stripe-event-123'])
)

vi.mocked(global.fetch).mockImplementation(async (input) => {
const url = String(input)

if (url.includes('/customers/cloud-subscription-status')) {
return {
ok: true,
json: async () => ({
is_active: true,
subscription_id: 'sub_123',
renewal_date: '2025-11-16'
})
} as Response
}

if (url.endsWith('/customers/pending-subscription-success')) {
return {
ok: true,
status: 200,
json: async () => ({
id: 'event-123',
transaction_id: 'stripe-event-123',
value: 20,
currency: 'USD',
tier: 'standard',
cycle: 'monthly',
checkout_type: 'new'
})
} as Response
}

if (
url.endsWith(
'/customers/pending-subscription-success/event-123/consume'
)
) {
return {
ok: true,
status: 204
} as Response
}

throw new Error(`Unexpected fetch URL: ${url}`)
})

const { syncStatusAfterCheckout } = useSubscriptionWithScope()

await syncStatusAfterCheckout()

expect(
mockTelemetry.trackMonthlySubscriptionSucceeded
).not.toHaveBeenCalled()
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining(
'/customers/pending-subscription-success/event-123/consume'
),
expect.objectContaining({
method: 'POST'
})
)
})
})

describe('subscribe', () => {
Expand Down
Loading
Loading