-
Notifications
You must be signed in to change notification settings - Fork 673
Expand file tree
/
Copy pathuseWorkspaceBilling.ts
More file actions
444 lines (408 loc) · 13.5 KB
/
Copy pathuseWorkspaceBilling.ts
File metadata and controls
444 lines (408 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import { computed, ref, shallowRef } from 'vue'
import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans'
import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog'
import type { SubscriptionDialogOptions } from '@/platform/cloud/subscription/composables/useSubscriptionDialog'
import type {
BillingBalanceResponse,
BillingStatusResponse,
CreateTopupResponse,
PreviewSubscribeOptions,
PreviewSubscribeResponse,
SubscribeOptions,
SubscribeResponse
} from '@/platform/workspace/api/workspaceApi'
import {
WorkspaceApiError,
workspaceApi
} from '@/platform/workspace/api/workspaceApi'
import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore'
import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
import type {
BalanceInfo,
BillingActions,
BillingState,
SubscriptionInfo
} from '../../../composables/billing/types'
/**
* Whether a rejection means the subscription already holds the state the caller
* asked for. The request did nothing, but the user's intent is satisfied, so
* surfacing it as a failure would report a problem that does not exist — most
* visibly when a request succeeds and its response is lost, and the retry is
* then refused.
*
* The 4xx check keeps a server fault that happens to echo one of these codes
* from being swallowed as success.
*/
function isAlreadyInRequestedState(err: unknown, code: string): boolean {
return (
err instanceof WorkspaceApiError &&
err.code === code &&
err.status !== undefined &&
err.status >= 400 &&
err.status < 500
)
}
/**
* Refreshes local state after a no-op, without letting the refresh overturn the
* outcome. The desired state already holds on the server, so a failed read must
* not turn it back into a reported failure — which is exactly what would happen
* on the flaky network that caused the no-op in the first place.
*/
async function resyncQuietly(refresh: () => Promise<unknown>): Promise<void> {
try {
await refresh()
} catch {
// Intentionally ignored: the next read corrects the view.
}
}
/**
* Adapter for workspace-scoped billing via /billing/* endpoints.
* Used for team workspaces.
* @internal - Use useBillingContext() instead of importing directly.
*/
export function useWorkspaceBilling(): BillingState & BillingActions {
const billingPlans = useBillingPlans()
const billingOperationStore = useBillingOperationStore()
const workspaceStore = useTeamWorkspaceStore()
const isInitialized = ref(false)
const isLoading = ref(false)
const error = ref<string | null>(null)
const statusData = shallowRef<BillingStatusResponse | null>(null)
const balanceData = shallowRef<BillingBalanceResponse | null>(null)
// Prevent older status and balance responses from overwriting newer state.
const latestBillingReadIds = { status: 0, balance: 0 }
const canAccessSubscriptionFeatures = computed(
() => statusData.value?.is_active ?? false
)
const isFreeTier = computed(
() => statusData.value?.subscription_tier === 'FREE'
)
const subscription = computed<SubscriptionInfo | null>(() => {
const status = statusData.value
if (!status) return null
return {
isActive: status.is_active,
tier: status.subscription_tier ?? null,
duration: status.subscription_duration ?? null,
planSlug: status.plan_slug ?? null,
scheduledPlanSlug: status.scheduled_plan_slug ?? null,
changeAt: status.change_at ?? null,
renewalDate: status.renewal_date ?? null,
endDate: status.cancel_at ?? null,
isCancelled: status.subscription_status === 'canceled',
hasFunds: status.has_funds
}
})
const balance = computed<BalanceInfo | null>(() => {
const data = balanceData.value
if (!data) return null
return {
amountMicros: data.amount_micros,
currency: data.currency,
effectiveBalanceMicros:
data.effective_balance_micros ?? data.amount_micros,
prepaidBalanceMicros: data.prepaid_balance_micros ?? 0,
cloudCreditBalanceMicros: data.cloud_credit_balance_micros ?? 0
}
})
const billingStatus = computed(() => statusData.value?.billing_status ?? null)
const subscriptionStatus = computed(
() => statusData.value?.subscription_status ?? null
)
const tier = computed(() => statusData.value?.subscription_tier ?? null)
const renewalDate = computed(() => statusData.value?.renewal_date ?? null)
const plans = computed(() => billingPlans.plans.value)
const currentPlanSlug = computed(
() => statusData.value?.plan_slug ?? billingPlans.currentPlanSlug.value
)
const teamCreditStops = computed(() => billingPlans.teamCreditStops.value)
const currentTeamCreditStop = computed(
() => statusData.value?.team_credit_stop ?? null
)
async function initialize(): Promise<void> {
if (isInitialized.value) return
isLoading.value = true
error.value = null
try {
await Promise.all([fetchStatus(), fetchBalance(), fetchPlans()])
// Re-fetch balance if free tier credits were just lazily granted
if (isFreeTier.value && balance.value?.amountMicros === 0) {
await fetchBalance()
}
isInitialized.value = true
} catch (err) {
error.value =
err instanceof Error ? err.message : 'Failed to initialize billing'
throw err
} finally {
isLoading.value = false
}
}
async function fetchStatus(): Promise<void> {
const requestId = ++latestBillingReadIds.status
const workspaceId = workspaceStore.activeWorkspace?.id
isLoading.value = true
error.value = null
try {
const status = await workspaceApi.getBillingStatus()
if (
requestId !== latestBillingReadIds.status ||
workspaceId !== workspaceStore.activeWorkspace?.id
) {
return
}
statusData.value = status
if (workspaceId && status.billing_rail) {
workspaceStore.setWorkspaceBillingRail(workspaceId, status.billing_rail)
}
if (
status.pending_billing_op_id &&
!billingOperationStore.getOperation(status.pending_billing_op_id)
) {
void billingOperationStore.startOperation(
status.pending_billing_op_id,
status.pending_billing_op_type === 'topup' ? 'topup' : 'subscription',
undefined,
status.action_url
)
}
} catch (err) {
if (requestId === latestBillingReadIds.status) {
error.value =
err instanceof Error ? err.message : 'Failed to fetch billing status'
}
throw err
} finally {
if (requestId === latestBillingReadIds.status) isLoading.value = false
}
}
async function fetchBalance(): Promise<void> {
const requestId = ++latestBillingReadIds.balance
isLoading.value = true
error.value = null
try {
const balance = await workspaceApi.getBillingBalance()
if (requestId === latestBillingReadIds.balance) {
balanceData.value = balance
}
} catch (err) {
if (requestId === latestBillingReadIds.balance) {
error.value =
err instanceof Error ? err.message : 'Failed to fetch balance'
}
throw err
} finally {
if (requestId === latestBillingReadIds.balance) isLoading.value = false
}
}
async function retryBillingRead(
fetchBillingResource: () => Promise<void>,
billingResource: keyof typeof latestBillingReadIds
): Promise<{ failed: boolean; requestId: number }> {
const firstAttempt = fetchBillingResource()
const firstRequestId = latestBillingReadIds[billingResource]
try {
await firstAttempt
return { failed: false, requestId: firstRequestId }
} catch {
if (firstRequestId !== latestBillingReadIds[billingResource]) {
return { failed: false, requestId: firstRequestId }
}
}
const retry = fetchBillingResource()
const retryRequestId = latestBillingReadIds[billingResource]
try {
await retry
return { failed: false, requestId: retryRequestId }
} catch {
return {
failed: retryRequestId === latestBillingReadIds[billingResource],
requestId: retryRequestId
}
}
}
async function reconcileBillingStateAfterSubscribe(): Promise<void> {
const [statusResult, balanceResult] = await Promise.all([
retryBillingRead(fetchStatus, 'status'),
retryBillingRead(fetchBalance, 'balance')
])
const statusFailed =
statusResult.failed &&
statusResult.requestId === latestBillingReadIds.status
const balanceFailed =
balanceResult.failed &&
balanceResult.requestId === latestBillingReadIds.balance
if (statusFailed || balanceFailed) {
error.value = 'Subscription succeeded, but billing state refresh failed'
}
}
async function subscribe(
planSlug: string,
options?: SubscribeOptions
): Promise<SubscribeResponse> {
isLoading.value = true
error.value = null
try {
const response = await workspaceApi.subscribe(planSlug, options)
isLoading.value = false
void reconcileBillingStateAfterSubscribe()
return response
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to subscribe'
isLoading.value = false
throw err
}
}
async function previewSubscribe(
planSlug: string,
options?: PreviewSubscribeOptions
): Promise<PreviewSubscribeResponse | null> {
isLoading.value = true
error.value = null
try {
return await workspaceApi.previewSubscribe(planSlug, options)
} catch (err) {
error.value =
err instanceof Error ? err.message : 'Failed to preview subscription'
throw err
} finally {
isLoading.value = false
}
}
async function manageSubscription(): Promise<void> {
isLoading.value = true
error.value = null
try {
const returnUrl = window.location.href
const response = await workspaceApi.getPaymentPortalUrl(returnUrl)
if (response.url) {
window.open(response.url, '_blank')
}
} catch (err) {
error.value =
err instanceof Error ? err.message : 'Failed to open billing portal'
throw err
} finally {
isLoading.value = false
}
}
async function cancelSubscription(): Promise<void> {
isLoading.value = true
error.value = null
try {
const response = await workspaceApi.cancelSubscription()
const operation = await billingOperationStore.startOperation(
response.billing_op_id,
'cancel'
)
if (operation.status !== 'succeeded') {
throw new Error(
operation.errorMessage ?? 'Failed to cancel subscription'
)
}
} catch (err) {
if (isAlreadyInRequestedState(err, 'ALREADY_CANCELED')) {
await resyncQuietly(fetchStatus)
// fetchStatus records its own read failure; the cancellation still
// holds, so the operation is not in error.
error.value = null
return
}
error.value =
err instanceof Error ? err.message : 'Failed to cancel subscription'
throw err
} finally {
isLoading.value = false
}
}
async function resubscribe(): Promise<void> {
isLoading.value = true
error.value = null
try {
await workspaceApi.resubscribe()
await Promise.allSettled([fetchStatus(), fetchBalance()])
} catch (err) {
if (isAlreadyInRequestedState(err, 'NOT_SCHEDULED_FOR_CANCELLATION')) {
// Mirrors the success path, which refreshes balance too. allSettled,
// not all: a rejection from one read must not release this branch while
// the other is still in flight, or that one writes its failure into
// error after the clear below.
await resyncQuietly(() =>
Promise.allSettled([fetchStatus(), fetchBalance()])
)
error.value = null
return
}
error.value = err instanceof Error ? err.message : 'Failed to resubscribe'
throw err
} finally {
isLoading.value = false
}
}
async function topup(amountCents: number): Promise<CreateTopupResponse> {
isLoading.value = true
error.value = null
try {
return await workspaceApi.createTopup(amountCents)
} catch (err) {
error.value =
err instanceof Error ? err.message : 'Failed to top up credits'
throw err
} finally {
isLoading.value = false
}
}
async function fetchPlans(): Promise<void> {
isLoading.value = true
error.value = null
try {
await billingPlans.fetchPlans()
if (billingPlans.error.value) {
error.value = billingPlans.error.value
}
} finally {
isLoading.value = false
}
}
const subscriptionDialog = useSubscriptionDialog()
async function requireActiveSubscription(): Promise<void> {
await fetchStatus()
if (!canAccessSubscriptionFeatures.value) {
subscriptionDialog.show({ reason: 'subscription_required' })
}
}
function showSubscriptionDialog(options?: SubscriptionDialogOptions): void {
subscriptionDialog.show(options)
}
return {
// State
isInitialized,
subscription,
balance,
plans,
currentPlanSlug,
teamCreditStops,
currentTeamCreditStop,
isLoading,
error,
canAccessSubscriptionFeatures,
isFreeTier,
billingStatus,
subscriptionStatus,
tier,
renewalDate,
// Actions
initialize,
fetchStatus,
fetchBalance,
subscribe,
previewSubscribe,
manageSubscription,
cancelSubscription,
resubscribe,
topup,
fetchPlans,
requireActiveSubscription,
showSubscriptionDialog
}
}