Line data Source code
1 : import type { AuditLog } from '@/platform/billing/api/customerEventsService'
2 :
3 2356 : const STORAGE_KEY = 'pending_topup_timestamp'
4 2356 : const MAX_AGE_MS = 24 * 60 * 60 * 1000 // 24 hours
5 :
6 : interface CompletedTopup {
7 : /** Set when the checkout tab opened, one purchase request after `started`. */
8 : startedAtMs: number
9 : }
10 :
11 0 : function getPendingTopupTimestamp(): number | null {
12 0 : const timestampStr = localStorage.getItem(STORAGE_KEY)
13 0 : if (timestampStr === null) return null
14 :
15 0 : const timestamp = Number(timestampStr)
16 0 : const age = Date.now() - timestamp
17 0 : if (Number.isSafeInteger(timestamp) && age >= 0 && age <= MAX_AGE_MS) {
18 0 : return timestamp
19 : }
20 :
21 0 : localStorage.removeItem(STORAGE_KEY)
22 0 : return null
23 : }
24 :
25 : /**
26 : * Pending credit top-up marker (localStorage) so the balance can refresh on
27 : * return from Stripe checkout. Pure billing state, no telemetry dependency, so
28 : * it works regardless of telemetry consent.
29 : */
30 1 : export function usePendingTopup() {
31 : // Mark a top-up as pending before opening the Stripe checkout window.
32 1 : function startPendingTopup(): void {
33 1 : localStorage.setItem(STORAGE_KEY, Date.now().toString())
34 : }
35 :
36 : // The top-up a later credit_added completed, if any; clears the marker on hit.
37 0 : function consumeCompletedTopup(
38 : events: AuditLog[] | undefined | null
39 : ): CompletedTopup | null {
40 0 : const timestamp = getPendingTopupTimestamp()
41 0 : if (timestamp === null) return null
42 0 : if (!events || events.length === 0) return null
43 :
44 : const completedTopup = events.find(
45 : (e) =>
46 : (e.event_type === 'credit_added' ||
47 : e.event_type === 'topup_completed') &&
48 : e.createdAt &&
49 : new Date(e.createdAt).getTime() > timestamp
50 : )
51 :
52 0 : if (!completedTopup) return null
53 0 : localStorage.removeItem(STORAGE_KEY)
54 0 : return { startedAtMs: timestamp }
55 : }
56 :
57 : // Non-consuming: true if a pending top-up is awaiting a balance refresh.
58 0 : function pendingTopupNeedsRefresh(): boolean {
59 0 : return getPendingTopupTimestamp() !== null
60 : }
61 :
62 : // Clear any pending top-up marker.
63 0 : function clearPendingTopup(): void {
64 0 : localStorage.removeItem(STORAGE_KEY)
65 : }
66 :
67 1 : return {
68 : startPendingTopup,
69 : consumeCompletedTopup,
70 : pendingTopupNeedsRefresh,
71 : clearPendingTopup
72 : }
73 : }
|