-
Notifications
You must be signed in to change notification settings - Fork 511
Expand file tree
/
Copy pathsubscriptionPurchaseTracker.ts
More file actions
69 lines (60 loc) · 1.88 KB
/
subscriptionPurchaseTracker.ts
File metadata and controls
69 lines (60 loc) · 1.88 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
import type { TierKey } from '@/platform/cloud/subscription/constants/tierPricing'
import type { BillingCycle } from './subscriptionTierRank'
type PendingSubscriptionPurchase = {
tierKey: TierKey
billingCycle: BillingCycle
timestamp: number
}
const STORAGE_KEY = 'pending_subscription_purchase'
const MAX_AGE_MS = 24 * 60 * 60 * 1000 // 24 hours
const VALID_TIERS: TierKey[] = ['standard', 'creator', 'pro', 'founder']
const VALID_CYCLES: BillingCycle[] = ['monthly', 'yearly']
export function startSubscriptionPurchaseTracking(
tierKey: TierKey,
billingCycle: BillingCycle
): void {
if (typeof window === 'undefined') return
try {
const payload: PendingSubscriptionPurchase = {
tierKey,
billingCycle,
timestamp: Date.now()
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(payload))
} catch {
// Ignore storage errors (e.g. private browsing mode)
}
}
export function getPendingSubscriptionPurchase(): PendingSubscriptionPurchase | null {
if (typeof window === 'undefined') return null
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return null
try {
const parsed = JSON.parse(raw) as PendingSubscriptionPurchase
if (!parsed || typeof parsed !== 'object') {
localStorage.removeItem(STORAGE_KEY)
return null
}
const { tierKey, billingCycle, timestamp } = parsed
if (
!VALID_TIERS.includes(tierKey) ||
!VALID_CYCLES.includes(billingCycle) ||
typeof timestamp !== 'number'
) {
localStorage.removeItem(STORAGE_KEY)
return null
}
if (Date.now() - timestamp > MAX_AGE_MS) {
localStorage.removeItem(STORAGE_KEY)
return null
}
return parsed
} catch {
localStorage.removeItem(STORAGE_KEY)
return null
}
}
export function clearPendingSubscriptionPurchase(): void {
if (typeof window === 'undefined') return
localStorage.removeItem(STORAGE_KEY)
}