-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbilling.subscriptions.component.vue
More file actions
794 lines (740 loc) · 29.1 KB
/
Copy pathbilling.subscriptions.component.vue
File metadata and controls
794 lines (740 loc) · 29.1 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
<!--
BillingSubscriptionsComponent
=============================
Self-contained subscriptions panel rendered inside the user account "Subscriptions" tab.
Always renders the current plan card + Stripe portal button; meter / extras sections are
gated by `serverConfig.billing.meterMode === true`.
USAGE:
<BillingSubscriptionsComponent />
PROPS:
- none (component uses billingStore + authStore directly)
EVENTS:
- none
-->
<template>
<v-container class="billing-subscriptions py-6 px-6" style="max-width: none; width: 100%;">
<!-- ── Status banners ────────────────────────────────────────────────── -->
<v-alert
v-if="checkoutProcessing"
type="info"
variant="tonal"
class="mb-4"
aria-live="polite"
>
<div class="d-flex align-center ga-3">
<v-progress-circular indeterminate size="18" width="2" color="info" />
<span>Processing your payment...</span>
</div>
</v-alert>
<v-alert
v-else-if="checkoutTimeout"
type="warning"
variant="tonal"
class="mb-4"
aria-live="polite"
>
Payment received, your subscription is being synced. Please refresh in a few seconds.
<template #append>
<v-btn variant="text" size="small" @click="retryFetchSubscription">
Refresh
</v-btn>
</template>
</v-alert>
<v-alert
v-else-if="paymentSuccessMessage"
type="success"
variant="tonal"
closable
class="mb-4"
@click:close="dismissPaymentSuccess"
>
{{ paymentSuccessMessage }}
</v-alert>
<!-- ── Loading ──────────────────────────────────────────────────────── -->
<v-row v-if="fetchLoading" justify="center" class="py-10">
<AppSpinner color="primary" />
</v-row>
<!-- ── P1-1: Subscription fetch error ─────────────────────────────── -->
<v-card
v-else-if="subscriptionError && !subscription && !checkoutProcessing && !checkoutTimeout"
role="alert"
aria-live="assertive"
:class="config.vuetify.theme.rounded"
class="billing-subscriptions__error-card pa-6 mb-4"
elevation="0"
>
<div class="d-flex align-center mb-3">
<v-icon icon="fa-solid fa-triangle-exclamation" color="error" size="small" class="mr-3" aria-hidden="true" />
<span class="text-title-large font-weight-medium">Subscription unavailable</span>
</div>
<p class="text-body-medium text-medium-emphasis mb-4">
Unable to load your subscription details. Please try again.
</p>
<v-btn
color="primary"
variant="flat"
:class="config.vuetify.theme.rounded"
class="text-none text-body-medium"
:loading="fetchLoading"
@click="retryFetchSubscription"
>
Retry
</v-btn>
</v-card>
<!-- ── Main content ─────────────────────────────────────────────────── -->
<template v-else>
<v-row>
<!-- ── LEFT COLUMN: Plan summary + meter ──────────────────────── -->
<v-col cols="12" :md="meterMode ? 5 : 12">
<!-- ── Plan summary card (free) ──────────────────────────────── -->
<v-card
v-if="!subscription || currentPlan === 'free'"
:class="config.vuetify.theme.rounded"
class="billing-subscriptions__plan-card billing-subscriptions__plan-card--free pa-6 mb-4"
elevation="0"
>
<div class="d-flex align-center justify-space-between flex-wrap ga-3 mb-4">
<div class="d-flex align-center ga-3">
<span class="text-title-large font-weight-medium">Current Plan</span>
<BillingPlanBadgeComponent plan="free" />
</div>
</div>
<p class="text-body-medium text-medium-emphasis mb-6">
{{ freePlanBlurb }}
</p>
<v-btn
color="primary"
variant="flat"
:class="config.vuetify.theme.rounded"
class="text-none text-body-medium"
to="/pricing"
>
Upgrade
</v-btn>
</v-card>
<!-- ── Plan summary card (paid) ───────────────────────────────── -->
<v-card
v-else
:class="config.vuetify.theme.rounded"
class="billing-subscriptions__plan-card billing-subscriptions__plan-card--paid pa-6 mb-4"
elevation="0"
>
<!-- Header row: plan name + badge left, status chip + action right -->
<div class="d-flex align-center justify-space-between flex-wrap ga-3 mb-4">
<div class="d-flex align-center ga-3">
<span class="text-title-large font-weight-medium">Current Plan</span>
<BillingPlanBadgeComponent :plan="currentPlan" />
</div>
<div class="d-flex align-center ga-2">
<v-icon
:icon="subscriptionStatusIcon"
size="x-small"
:color="subscriptionStatusMeta.color"
aria-hidden="true"
/>
<v-chip
:color="subscriptionStatusMeta.color"
variant="tonal"
size="small"
class="text-capitalize"
>
{{ subscriptionStatusMeta.label }}
</v-chip>
<v-btn
v-if="subscriptionStatusAction"
:color="subscriptionStatusAction.color"
variant="tonal"
size="small"
:class="config.vuetify.theme.rounded"
class="text-none text-body-medium"
:loading="portalLoading"
@click="manageSubscription"
>
{{ subscriptionStatusAction.label }}
</v-btn>
</div>
</div>
<!-- Next billing date -->
<div v-if="nextBillingDate" class="d-flex align-center ga-2 mb-6 text-body-medium text-medium-emphasis">
<v-icon icon="fa-solid fa-calendar" size="x-small" aria-hidden="true" />
<span>{{ `Next billing date: ${nextBillingDate}` }}</span>
</div>
<!-- CTAs (portal error surfaced via centralized snackbar — see lib/services/axios.js) -->
<div class="d-flex ga-3 flex-wrap" :class="{ 'mt-6': !nextBillingDate }">
<v-btn
color="primary"
variant="flat"
:class="config.vuetify.theme.rounded"
class="text-none text-body-medium"
:loading="portalLoading"
@click="manageSubscription"
>
Manage Subscription
</v-btn>
<v-btn
v-if="canUpgrade"
variant="outlined"
:class="config.vuetify.theme.rounded"
class="text-none text-body-medium"
to="/pricing"
>
Change Plan
</v-btn>
</div>
</v-card>
<!-- ── Meter section (single bar — no duplicate) ──────────────── -->
<template v-if="meterMode">
<!-- Meter polling error surfaced via centralized snackbar (lib/services/axios.js) -->
<!-- ── Usage meter card (T4 % bar — single source, no BillingUsageBarComponent) -->
<v-card
:class="config.vuetify.theme.rounded"
class="billing-subscriptions__meter-card px-6 py-3 mb-0"
elevation="0"
>
<p class="text-title-medium font-weight-medium mb-2">Weekly meter</p>
<BillingMeterProgressComponent
:used="meterUsed"
:quota="combinedPool"
:extras="0"
:overage="0"
:net-remaining-raw="combinedPool - meterUsed"
label=""
/>
</v-card>
<!-- ── Breakdown card ─────────────────────────────────────────── -->
<v-card
:class="config.vuetify.theme.rounded"
class="billing-subscriptions__meter-card--breakdown px-6 py-3 mb-0"
elevation="0"
>
<p class="text-title-medium font-weight-medium mb-2">Breakdown</p>
<BillingMeterBreakdownChartComponent :breakdown="meterBreakdown" />
</v-card>
</template>
</v-col>
<!-- ── RIGHT COLUMN: Extras + ledger (meterMode only) ─────────── -->
<v-col v-if="meterMode" cols="12" md="7">
<!-- ── Extras card ──────────────────────────────────────────────── -->
<v-card
:class="config.vuetify.theme.rounded"
class="billing-subscriptions__extras-card pa-6 mb-4"
elevation="0"
>
<!-- Header row: title + balance chip inline -->
<div class="d-flex align-center justify-space-between flex-wrap ga-3 mb-4">
<p class="text-title-medium font-weight-medium mb-0">Extra units</p>
<v-chip
variant="tonal"
color="primary"
size="small"
>
{{ meterExtras === 0 ? 'no units remaining' : meterExtras === 1 ? `${meterExtras} unit remaining` : `${meterExtras} units remaining` }}
</v-chip>
</div>
<!-- CTA: /pricing#units — single source of truth for pack pricing (feedback #7) -->
<v-btn
color="primary"
variant="flat"
:class="config.vuetify.theme.rounded"
class="text-none text-body-medium mb-6"
to="/pricing#units"
>
Buy compute extras
</v-btn>
<!-- Ledger: last 20 entries -->
<v-divider class="mb-4" />
<p class="text-body-medium font-weight-medium mb-3">Transaction history</p>
<BillingExtrasLedgerComponent
:entries="extrasLedger.entries"
:total="extrasLedger.total"
:page="extrasLedger.page"
:limit="extrasLedger.limit"
@update:page="onLedgerPageChange"
/>
</v-card>
</v-col>
</v-row>
</template>
<BillingExtrasCheckoutModalComponent
v-model="extrasCheckoutDialog"
:packs="extrasPacks"
/>
</v-container>
</template>
<script>
/**
* Module dependencies.
*/
import { computed, watch } from 'vue';
import { useBillingStore } from '../stores/billing.store';
import { useAuthStore } from '../../auth/stores/auth.store';
import { useMeter } from '../composables/billing.useMeter';
import { useCheckoutPolling } from '../composables/billing.useCheckoutPolling';
import { resolveStaticContent } from '../lib/billing.resolveStaticContent.js';
import BillingPlanBadgeComponent from './billing.planBadge.component.vue';
import BillingMeterProgressComponent from './billing.meterProgress.component.vue';
import BillingMeterBreakdownChartComponent from './billing.meterBreakdownChart.component.vue';
import BillingExtrasLedgerComponent from './billing.extrasLedger.component.vue';
import BillingExtrasCheckoutModalComponent from './billing.extrasCheckoutModal.component.vue';
import AppSpinner from '../../core/components/core.appSpinner.component.vue';
const { plans: plansConfig, packs: packsConfig } = resolveStaticContent();
/**
* Component definition.
*/
export default {
name: 'BillingSubscriptionsComponent',
components: {
BillingPlanBadgeComponent,
BillingMeterProgressComponent,
BillingMeterBreakdownChartComponent,
BillingExtrasLedgerComponent,
BillingExtrasCheckoutModalComponent,
AppSpinner,
},
/**
* @desc Wires billingStore + authStore + reactive meterMode + useMeter derived refs.
* Checkout polling state is owned by useCheckoutPolling composable (issue #4219 refactor).
* Polling refs are returned here so Options API methods can access them via `this.X` and
* tests can read them via `wrapper.vm.X` — Vue 3 auto-unwraps setup() refs on the instance.
* @returns {Object}
*/
setup() {
const billingStore = useBillingStore();
const authStore = useAuthStore();
const meter = useMeter({ pollIntervalMs: 0 });
const {
used: meterUsed,
quota: meterQuota,
extras: meterExtras,
breakdown: meterBreakdown,
overage: meterOverage,
netRemainingRaw: meterNetRemainingRaw,
} = meter;
const meterMode = computed(() => authStore.serverConfig?.billing?.meterMode === true);
watch(
meterMode,
(active) => {
if (active) {
void billingStore.fetchExtrasLedger({ page: 1, limit: 20 }).catch((error) => {
console.error('Failed to load extras ledger:', error);
});
}
},
{ immediate: true },
);
// Checkout polling composable — owns all polling reactive state.
// Refs are returned to the instance so Options API methods + tests access them via `this.X`.
const polling = useCheckoutPolling();
return {
billingStore,
authStore,
meterMode,
meterUsed,
meterQuota,
meterExtras,
meterBreakdown,
meterOverage,
meterNetRemainingRaw,
// Polling state (refs — auto-unwrapped on the instance)
checkoutProcessing: polling.checkoutProcessing,
checkoutTimeout: polling.checkoutTimeout,
paymentSuccessMessage: polling.paymentSuccessMessage,
checkoutPollCount: polling.checkoutPollCount,
pollAborted: polling.pollAborted,
checkoutPollSnapshotId: polling.checkoutPollSnapshotId,
checkoutPollSnapshotStatus: polling.checkoutPollSnapshotStatus,
checkoutPollSnapshotPlan: polling.checkoutPollSnapshotPlan,
checkoutPollTimer: polling.checkoutPollTimer,
// Polling composable handle — used by Options API methods to delegate calls.
// Named without $ / _ prefix to avoid Vue 3 reserved-prefix dev warning.
pollingComposable: polling,
};
},
data() {
return {
portalLoading: false,
extrasCheckoutDialog: false,
paymentSuccessTimer: null,
successCleanupTimer: null,
// V5 P2: visibility-change subscription refresh debounce (timestamp of last fetch)
subscriptionLastFetchedAt: 0,
};
},
computed: {
/**
* @desc Combined compute pool = subscription quota + extras + already-used.
* Used as denominator for "Weekly compute" % so Free plan (quota=0) doesn't
* false-alarm 100% red. Matches the sidenav gauge formula.
* @returns {number}
*/
combinedPool() {
return this.meterQuota + this.meterExtras + this.meterUsed;
},
fetchLoading() {
return this.billingStore.loading;
},
/**
* @desc Free-plan upgrade blurb, config-overridable. Devkit default: exact current
* copy (full paragraph, not just the second sentence) so a downstream missing a
* feature (e.g. no team members) can rewrite the whole thing.
* @returns {string}
*/
freePlanBlurb() {
return (
this.config?.billing?.freePlanBlurb ??
"You're on the free plan. Upgrade to unlock more projects, team members, and advanced features."
);
},
subscription() {
return this.billingStore.subscription;
},
/**
* @desc Error message from the last fetchSubscription failure (P1-1).
* @returns {string|null}
*/
subscriptionError() {
return this.billingStore.subscriptionError;
},
/**
* @desc Extras credit ledger data for the paginated history table.
* @returns {{ entries: Array, total: number, page: number, limit: number }}
*/
extrasLedger() {
return this.billingStore.extrasLedger ?? { entries: [], total: 0, page: 1, limit: 20 };
},
/**
* @desc Derive current plan from subscription or default to free.
* @returns {string}
*/
currentPlan() {
return this.subscription?.plan || 'free';
},
/**
* @desc Ordered plan IDs from static content, used to decide if a paid plan can move up.
* @returns {Array<string>}
*/
availablePlanIds() {
const staticIds = plansConfig.map((plan) => plan.id).filter(Boolean);
if (staticIds.length > 0) return staticIds;
return this.billingStore.plans
.map((plan) => plan.planId || plan.name?.toLowerCase())
.filter(Boolean);
},
/**
* @desc Whether the current paid plan has a higher plan available.
* @returns {boolean}
*/
canUpgrade() {
const currentIndex = this.availablePlanIds.indexOf(this.currentPlan);
return currentIndex >= 0 && currentIndex < this.availablePlanIds.length - 1;
},
/**
* @desc Available extras packs for the inline checkout modal.
* BillingExtrasCheckoutModalComponent needs the legacy flat shape
* `{ packId, label, priceUsd, meterUnits }` — Stripe-backed `packsAvailable`
* already comes in that shape from the backend. `packsConfig` (static-content
* fallback) is V4-unified (`{ id, title, price:{amount,period}, meta:{packId,
* priceUsd, meterUnits}, ... }` — same shape BillingCardComponent renders via
* BillingPacksComponent), so it's adapted here at the consumer boundary rather
* than at the source: both this modal and the pricing-page card get their
* required shape from the SAME `packsConfig` static content.
* @returns {Array<{packId: string, label: string, priceUsd: number, meterUnits: number}>}
*/
extrasPacks() {
const fromStore =
this.billingStore.usageMeter?.packsAvailable ??
this.billingStore.extrasBalance?.packsAvailable ??
null;
if (fromStore && fromStore.length > 0) return fromStore;
return packsConfig.map((pack) => ({
packId: pack.meta?.packId ?? pack.id,
label: pack.title,
priceUsd: pack.meta?.priceUsd ?? null,
meterUnits: pack.meta?.meterUnits ?? null,
}));
},
/**
* @desc Current subscription status normalized to a displayable string.
* @returns {string}
*/
subscriptionStatus() {
return this.subscription?.status || 'unknown';
},
/**
* @desc Vuetify chip metadata for the current subscription status.
* @returns {{ color: string, label: string }}
*/
subscriptionStatusMeta() {
const status = this.subscriptionStatus;
const colors = {
active: 'success',
trialing: 'success',
past_due: 'warning',
paused: 'warning',
canceled: 'error',
incomplete: 'error',
incomplete_expired: 'error',
unpaid: 'error',
};
const labels = {
paused: 'Paused',
unpaid: 'Unpaid',
};
return {
color: colors[status] || 'default',
label: labels[status] || status.replace(/_/g, ' '),
};
},
/**
* @desc Font Awesome icon for the current subscription status.
* @returns {string}
*/
subscriptionStatusIcon() {
if (['active', 'trialing'].includes(this.subscriptionStatus)) return 'fa-solid fa-circle-check';
if (this.subscriptionStatus === 'past_due') return 'fa-solid fa-triangle-exclamation';
if (this.subscriptionStatus === 'paused') return 'fa-solid fa-circle-pause';
if (this.subscriptionStatus === 'unpaid') return 'fa-solid fa-triangle-exclamation';
if (['canceled', 'incomplete', 'incomplete_expired'].includes(this.subscriptionStatus)) return 'fa-solid fa-circle-exclamation';
return 'fa-solid fa-circle-info';
},
/**
* @desc Portal action shown for subscription statuses requiring attention.
* @returns {{ color: string, label: string }|null}
*/
subscriptionStatusAction() {
if (this.subscriptionStatus === 'past_due') {
return { color: 'warning', label: 'Update payment method' };
}
if (this.subscriptionStatus === 'canceled') {
return { color: 'error', label: 'Reactivate' };
}
if (this.subscriptionStatus === 'paused') {
return { color: 'warning', label: 'Reactivate' };
}
if (this.subscriptionStatus === 'unpaid') {
return { color: 'error', label: 'Update payment method' };
}
if (['incomplete', 'incomplete_expired'].includes(this.subscriptionStatus)) {
return { color: 'error', label: 'Complete payment' };
}
return null;
},
/**
* @desc Format the next billing date for display (en-US).
* @returns {string|null}
*/
nextBillingDate() {
const date = this.subscription?.currentPeriodEnd;
if (!date) return null;
return new Date(date).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
},
},
/**
* @desc Fetch subscription data on mount and handle Stripe redirect query params.
* The legacy /billing page is retired; this component is now the landing point for
* Stripe redirects (success, cancel, packPurchased).
*
* F5 recovery (V5 P1): if sessionStorage contains a stale in-progress polling entry
* from a previous render and it's still within the polling window, polling is resumed
* for the remaining time without requiring the ?success query param to still be present.
* @returns {Promise<void>}
*/
async mounted() {
const orgsEnabled = this.authStore.serverConfig?.organizations?.enabled;
const hasOrg = !!this.authStore.user?.currentOrganization;
if (!this.authStore.isLoggedIn || (orgsEnabled && !hasOrg)) return;
const isCheckoutSuccess = this.handleCheckoutSuccessQuery();
if (!isCheckoutSuccess) {
// Check for interrupted polling session (F5 during checkout processing)
const resumed = this.resumeCheckoutPollingFromSession();
if (!resumed) {
// Normal load: fetch once and surface errors
try {
await this.billingStore.fetchSubscription();
this.subscriptionLastFetchedAt = Date.now();
} catch {
// subscriptionError is already set in the store; component shows error card
}
}
}
// Note: fetchExtrasLedger is handled by the immediate watcher in setup(),
// no duplicate call needed here.
// V5 P2: refresh subscription when tab regains visibility (multi-tab stale state)
document.addEventListener('visibilitychange', this.handleSubscriptionVisibilityChange);
},
/**
* @desc Clear pending timers and remove event listeners on component teardown.
* @returns {void}
*/
beforeUnmount() {
if (this.successCleanupTimer) {
clearTimeout(this.successCleanupTimer);
}
if (this.paymentSuccessTimer) {
clearTimeout(this.paymentSuccessTimer);
}
if (this.checkoutPollTimer) {
clearTimeout(this.checkoutPollTimer);
}
this.pollAborted = true;
document.removeEventListener('visibilitychange', this.handleSubscriptionVisibilityChange);
},
methods: {
/**
* @desc Handle tab visibility change — refresh subscription when tab becomes visible.
* Debounced 500ms to prevent a redundant fetch immediately after mount or a recent poll.
* Skipped while checkout polling is active to avoid concurrent fetch interference.
* @returns {void}
*/
// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Options API method, not a Qwik component
handleSubscriptionVisibilityChange() {
if (document.visibilityState !== 'visible') return;
const DEBOUNCE_MS = 500;
if (Date.now() - this.subscriptionLastFetchedAt < DEBOUNCE_MS) return;
if (this.checkoutProcessing) return; // Don't interrupt active polling
this.subscriptionLastFetchedAt = Date.now();
this.billingStore.fetchSubscription().catch(() => {});
},
/**
* @desc Manually dismiss the payment success banner and clear its auto-dismiss timer.
* @returns {void}
*/
dismissPaymentSuccess() {
if (this.paymentSuccessTimer) {
clearTimeout(this.paymentSuccessTimer);
this.paymentSuccessTimer = null;
}
this.paymentSuccessMessage = null;
},
/**
* @desc Re-fetch subscription on demand (Retry button / Refresh button).
* When called after a checkout timeout, clears the timeout banner if the
* subscription is now active/trialing.
* @returns {Promise<void>}
*/
async retryFetchSubscription() {
try {
const sub = await this.billingStore.fetchSubscription();
if (this.checkoutTimeout && ['active', 'trialing'].includes(sub?.status)) {
this.checkoutTimeout = false;
this.checkoutProcessing = false;
this.paymentSuccessMessage = 'Subscription activated successfully. Thank you!';
}
} catch {
// subscriptionError updated in store
}
},
/**
* @desc Detect ?success=true or ?checkout=success from Stripe redirect and start polling.
* Delegates to useCheckoutPolling composable.
* @returns {boolean} True when polling was started
*/
handleCheckoutSuccessQuery() {
return this.pollingComposable.handleCheckoutSuccessQuery(this.$route, () => this.scheduleQueryCleanup());
},
/**
* @desc Attempt to resume an interrupted checkout polling session after F5 reload.
* Delegates to useCheckoutPolling composable.
* @returns {boolean} True when polling was successfully resumed
*/
resumeCheckoutPollingFromSession() {
return this.pollingComposable.resumeCheckoutPollingFromSession();
},
/**
* @desc Persist checkout polling session to sessionStorage for F5 recovery.
* Delegates to useCheckoutPolling composable.
* @param {{ startedAt: number }} payload - Session data to persist
* @returns {void}
*/
persistCheckoutPollingSession(payload) {
this.pollingComposable.persistCheckoutPollingSession(payload);
},
/**
* @desc Clear the checkout polling session from sessionStorage.
* Delegates to useCheckoutPolling composable.
* @returns {void}
*/
clearCheckoutPollingSession() {
this.pollingComposable.clearCheckoutPollingSession();
},
/**
* @desc Poll fetchSubscription until the subscription changes or max attempts reached.
* Delegates to useCheckoutPolling composable.
* @returns {void}
*/
pollSubscription() {
this.pollingComposable.pollSubscription();
},
/**
* @desc Schedule URL query cleanup after success detection.
* @returns {void}
*/
scheduleQueryCleanup() {
this.successCleanupTimer = setTimeout(() => {
this.$router.replace({
query: { ...this.$route.query, success: undefined, type: undefined, packPurchased: undefined, tab: 'subscriptions' },
});
}, 100);
},
/**
* @desc Open the Stripe customer portal in a new tab.
* @returns {Promise<void>}
*/
async manageSubscription() {
this.portalLoading = true;
try {
const url = await this.billingStore.openPortal();
if (url) window.open(url, '_blank', 'noopener,noreferrer');
} catch (err) {
// Centralized snackbar (lib/services/axios.js) surfaces backend error.
console.error('Failed to open billing portal:', err);
} finally {
this.portalLoading = false;
}
},
/**
* @desc Handle ledger page change from BillingExtrasLedgerComponent.
* @param {number} page
* @returns {Promise<void>}
*/
async onLedgerPageChange(page) {
try {
await this.billingStore.fetchExtrasLedger({ page, limit: this.extrasLedger.limit });
} catch (error) {
console.error('Failed to load ledger page:', error);
}
},
},
};
</script>
<style scoped>
/* Plan card: accent left-border on paid plans */
.billing-subscriptions__plan-card--paid {
border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
border-left: 3px solid rgb(var(--v-theme-primary));
}
/* Free plan card: standard border, no accent */
.billing-subscriptions__plan-card--free {
border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
}
/* Error card: error-tinted border */
.billing-subscriptions__error-card {
border: 1px solid rgba(var(--v-theme-error), 0.2);
}
/* Meter section cards: consistent surface border */
.billing-subscriptions__meter-card {
border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
}
/* Breakdown card: same surface border as meter card */
.billing-subscriptions__meter-card--breakdown {
border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
}
/* Extras card (right column): consistent surface border */
.billing-subscriptions__extras-card {
border: 1px solid rgba(var(--v-theme-on-surface), 0.08);
}
</style>