@blocklet/payment-react-headless 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/.eslintrc.js +18 -0
  2. package/build.config.ts +30 -0
  3. package/es/checkout/context/CheckoutProvider.d.ts +6 -0
  4. package/es/checkout/context/CheckoutProvider.js +209 -0
  5. package/es/checkout/context/CustomerFormContext.d.ts +4 -0
  6. package/es/checkout/context/CustomerFormContext.js +9 -0
  7. package/es/checkout/context/ExchangeRateContext.d.ts +11 -0
  8. package/es/checkout/context/ExchangeRateContext.js +9 -0
  9. package/es/checkout/context/PaymentMethodContext.d.ts +26 -0
  10. package/es/checkout/context/PaymentMethodContext.js +9 -0
  11. package/es/checkout/context/SessionContext.d.ts +45 -0
  12. package/es/checkout/context/SessionContext.js +9 -0
  13. package/es/checkout/context/SubmitContext.d.ts +4 -0
  14. package/es/checkout/context/SubmitContext.js +9 -0
  15. package/es/checkout/context/index.d.ts +6 -0
  16. package/es/checkout/context/index.js +6 -0
  17. package/es/checkout/core/billingInterval.d.ts +15 -0
  18. package/es/checkout/core/billingInterval.js +36 -0
  19. package/es/checkout/core/crossSell.d.ts +4 -0
  20. package/es/checkout/core/crossSell.js +30 -0
  21. package/es/checkout/core/customerForm.d.ts +5 -0
  22. package/es/checkout/core/customerForm.js +105 -0
  23. package/es/checkout/core/exchangeRate.d.ts +11 -0
  24. package/es/checkout/core/exchangeRate.js +25 -0
  25. package/es/checkout/core/index.d.ts +10 -0
  26. package/es/checkout/core/index.js +55 -0
  27. package/es/checkout/core/lineItems.d.ts +7 -0
  28. package/es/checkout/core/lineItems.js +59 -0
  29. package/es/checkout/core/paymentMethod.d.ts +23 -0
  30. package/es/checkout/core/paymentMethod.js +85 -0
  31. package/es/checkout/core/pricing.d.ts +32 -0
  32. package/es/checkout/core/pricing.js +221 -0
  33. package/es/checkout/core/promotion.d.ts +10 -0
  34. package/es/checkout/core/promotion.js +39 -0
  35. package/es/checkout/core/session.d.ts +26 -0
  36. package/es/checkout/core/session.js +50 -0
  37. package/es/checkout/core/submit.d.ts +40 -0
  38. package/es/checkout/core/submit.js +66 -0
  39. package/es/checkout/hooks/index.d.ts +34 -0
  40. package/es/checkout/hooks/index.js +19 -0
  41. package/es/checkout/hooks/useBillingInterval.d.ts +14 -0
  42. package/es/checkout/hooks/useBillingInterval.js +50 -0
  43. package/es/checkout/hooks/useCheckout.d.ts +2 -0
  44. package/es/checkout/hooks/useCheckout.js +212 -0
  45. package/es/checkout/hooks/useCheckoutSession.d.ts +58 -0
  46. package/es/checkout/hooks/useCheckoutSession.js +107 -0
  47. package/es/checkout/hooks/useCheckoutStatus.d.ts +10 -0
  48. package/es/checkout/hooks/useCheckoutStatus.js +16 -0
  49. package/es/checkout/hooks/useCrossSell.d.ts +8 -0
  50. package/es/checkout/hooks/useCrossSell.js +57 -0
  51. package/es/checkout/hooks/useCustomerForm.d.ts +14 -0
  52. package/es/checkout/hooks/useCustomerForm.js +116 -0
  53. package/es/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
  54. package/es/checkout/hooks/useCustomerFormFeature.js +4 -0
  55. package/es/checkout/hooks/useExchangeRate.d.ts +11 -0
  56. package/es/checkout/hooks/useExchangeRate.js +15 -0
  57. package/es/checkout/hooks/useLineItems.d.ts +22 -0
  58. package/es/checkout/hooks/useLineItems.js +139 -0
  59. package/es/checkout/hooks/usePaymentMethod.d.ts +26 -0
  60. package/es/checkout/hooks/usePaymentMethod.js +101 -0
  61. package/es/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
  62. package/es/checkout/hooks/usePaymentMethodFeature.js +4 -0
  63. package/es/checkout/hooks/usePricing.d.ts +57 -0
  64. package/es/checkout/hooks/usePricing.js +174 -0
  65. package/es/checkout/hooks/usePricingFeature.d.ts +28 -0
  66. package/es/checkout/hooks/usePricingFeature.js +36 -0
  67. package/es/checkout/hooks/useProduct.d.ts +32 -0
  68. package/es/checkout/hooks/useProduct.js +5 -0
  69. package/es/checkout/hooks/usePromotion.d.ts +12 -0
  70. package/es/checkout/hooks/usePromotion.js +48 -0
  71. package/es/checkout/hooks/useSlippage.d.ts +8 -0
  72. package/es/checkout/hooks/useSlippage.js +29 -0
  73. package/es/checkout/hooks/useSubmit.d.ts +38 -0
  74. package/es/checkout/hooks/useSubmit.js +493 -0
  75. package/es/checkout/hooks/useSubmitFeature.d.ts +2 -0
  76. package/es/checkout/hooks/useSubmitFeature.js +4 -0
  77. package/es/checkout/hooks/useUpsell.d.ts +5 -0
  78. package/es/checkout/hooks/useUpsell.js +25 -0
  79. package/es/checkout/index.d.ts +37 -0
  80. package/es/checkout/index.js +28 -0
  81. package/es/checkout/types.d.ts +262 -0
  82. package/es/checkout/types.js +0 -0
  83. package/es/index.d.ts +1 -0
  84. package/es/index.js +28 -0
  85. package/es/shared/api.d.ts +41 -0
  86. package/es/shared/api.js +81 -0
  87. package/es/shared/format.d.ts +38 -0
  88. package/es/shared/format.js +229 -0
  89. package/es/shared/polling.d.ts +15 -0
  90. package/es/shared/polling.js +20 -0
  91. package/es/shared/types.d.ts +10 -0
  92. package/es/shared/types.js +0 -0
  93. package/es/shared/validation.d.ts +38 -0
  94. package/es/shared/validation.js +190 -0
  95. package/es/types/checkout-augmented.d.ts +42 -0
  96. package/es/types/checkout-augmented.js +17 -0
  97. package/es/types/external.d.ts +18 -0
  98. package/examples/01-basic-checkout.tsx +159 -0
  99. package/examples/01-credit-recharge.tsx +19 -0
  100. package/examples/02-subscription.tsx +40 -0
  101. package/examples/03-upsell.tsx +60 -0
  102. package/examples/04-cross-sell.tsx +54 -0
  103. package/examples/05-full-checkout.tsx +126 -0
  104. package/jest.config.js +15 -0
  105. package/lib/checkout/context/CheckoutProvider.d.ts +6 -0
  106. package/lib/checkout/context/CheckoutProvider.js +181 -0
  107. package/lib/checkout/context/CustomerFormContext.d.ts +4 -0
  108. package/lib/checkout/context/CustomerFormContext.js +16 -0
  109. package/lib/checkout/context/ExchangeRateContext.d.ts +11 -0
  110. package/lib/checkout/context/ExchangeRateContext.js +16 -0
  111. package/lib/checkout/context/PaymentMethodContext.d.ts +26 -0
  112. package/lib/checkout/context/PaymentMethodContext.js +16 -0
  113. package/lib/checkout/context/SessionContext.d.ts +45 -0
  114. package/lib/checkout/context/SessionContext.js +16 -0
  115. package/lib/checkout/context/SubmitContext.d.ts +4 -0
  116. package/lib/checkout/context/SubmitContext.js +16 -0
  117. package/lib/checkout/context/index.d.ts +6 -0
  118. package/lib/checkout/context/index.js +77 -0
  119. package/lib/checkout/core/billingInterval.d.ts +15 -0
  120. package/lib/checkout/core/billingInterval.js +42 -0
  121. package/lib/checkout/core/crossSell.d.ts +4 -0
  122. package/lib/checkout/core/crossSell.js +43 -0
  123. package/lib/checkout/core/customerForm.d.ts +5 -0
  124. package/lib/checkout/core/customerForm.js +106 -0
  125. package/lib/checkout/core/exchangeRate.d.ts +11 -0
  126. package/lib/checkout/core/exchangeRate.js +45 -0
  127. package/lib/checkout/core/index.d.ts +10 -0
  128. package/lib/checkout/core/index.js +297 -0
  129. package/lib/checkout/core/lineItems.d.ts +7 -0
  130. package/lib/checkout/core/lineItems.js +76 -0
  131. package/lib/checkout/core/paymentMethod.d.ts +23 -0
  132. package/lib/checkout/core/paymentMethod.js +114 -0
  133. package/lib/checkout/core/pricing.d.ts +32 -0
  134. package/lib/checkout/core/pricing.js +216 -0
  135. package/lib/checkout/core/promotion.d.ts +10 -0
  136. package/lib/checkout/core/promotion.js +62 -0
  137. package/lib/checkout/core/session.d.ts +26 -0
  138. package/lib/checkout/core/session.js +58 -0
  139. package/lib/checkout/core/submit.d.ts +40 -0
  140. package/lib/checkout/core/submit.js +84 -0
  141. package/lib/checkout/hooks/index.d.ts +34 -0
  142. package/lib/checkout/hooks/index.js +138 -0
  143. package/lib/checkout/hooks/useBillingInterval.d.ts +14 -0
  144. package/lib/checkout/hooks/useBillingInterval.js +63 -0
  145. package/lib/checkout/hooks/useCheckout.d.ts +2 -0
  146. package/lib/checkout/hooks/useCheckout.js +190 -0
  147. package/lib/checkout/hooks/useCheckoutSession.d.ts +58 -0
  148. package/lib/checkout/hooks/useCheckoutSession.js +119 -0
  149. package/lib/checkout/hooks/useCheckoutStatus.d.ts +10 -0
  150. package/lib/checkout/hooks/useCheckoutStatus.js +28 -0
  151. package/lib/checkout/hooks/useCrossSell.d.ts +8 -0
  152. package/lib/checkout/hooks/useCrossSell.js +75 -0
  153. package/lib/checkout/hooks/useCustomerForm.d.ts +14 -0
  154. package/lib/checkout/hooks/useCustomerForm.js +135 -0
  155. package/lib/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
  156. package/lib/checkout/hooks/useCustomerFormFeature.js +10 -0
  157. package/lib/checkout/hooks/useExchangeRate.d.ts +11 -0
  158. package/lib/checkout/hooks/useExchangeRate.js +29 -0
  159. package/lib/checkout/hooks/useLineItems.d.ts +22 -0
  160. package/lib/checkout/hooks/useLineItems.js +142 -0
  161. package/lib/checkout/hooks/usePaymentMethod.d.ts +26 -0
  162. package/lib/checkout/hooks/usePaymentMethod.js +101 -0
  163. package/lib/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
  164. package/lib/checkout/hooks/usePaymentMethodFeature.js +10 -0
  165. package/lib/checkout/hooks/usePricing.d.ts +57 -0
  166. package/lib/checkout/hooks/usePricing.js +168 -0
  167. package/lib/checkout/hooks/usePricingFeature.d.ts +28 -0
  168. package/lib/checkout/hooks/usePricingFeature.js +48 -0
  169. package/lib/checkout/hooks/useProduct.d.ts +32 -0
  170. package/lib/checkout/hooks/useProduct.js +21 -0
  171. package/lib/checkout/hooks/usePromotion.d.ts +12 -0
  172. package/lib/checkout/hooks/usePromotion.js +57 -0
  173. package/lib/checkout/hooks/useSlippage.d.ts +8 -0
  174. package/lib/checkout/hooks/useSlippage.js +39 -0
  175. package/lib/checkout/hooks/useSubmit.d.ts +38 -0
  176. package/lib/checkout/hooks/useSubmit.js +504 -0
  177. package/lib/checkout/hooks/useSubmitFeature.d.ts +2 -0
  178. package/lib/checkout/hooks/useSubmitFeature.js +10 -0
  179. package/lib/checkout/hooks/useUpsell.d.ts +5 -0
  180. package/lib/checkout/hooks/useUpsell.js +40 -0
  181. package/lib/checkout/index.d.ts +37 -0
  182. package/lib/checkout/index.js +182 -0
  183. package/lib/checkout/types.d.ts +262 -0
  184. package/lib/checkout/types.js +1 -0
  185. package/lib/index.d.ts +1 -0
  186. package/lib/index.js +162 -0
  187. package/lib/shared/api.d.ts +41 -0
  188. package/lib/shared/api.js +88 -0
  189. package/lib/shared/format.d.ts +38 -0
  190. package/lib/shared/format.js +262 -0
  191. package/lib/shared/polling.d.ts +15 -0
  192. package/lib/shared/polling.js +32 -0
  193. package/lib/shared/types.d.ts +10 -0
  194. package/lib/shared/types.js +1 -0
  195. package/lib/shared/validation.d.ts +38 -0
  196. package/lib/shared/validation.js +212 -0
  197. package/lib/types/checkout-augmented.d.ts +42 -0
  198. package/lib/types/checkout-augmented.js +24 -0
  199. package/lib/types/external.d.ts +18 -0
  200. package/package.json +64 -0
  201. package/src/checkout/context/CheckoutProvider.tsx +269 -0
  202. package/src/checkout/context/CustomerFormContext.ts +14 -0
  203. package/src/checkout/context/ExchangeRateContext.ts +21 -0
  204. package/src/checkout/context/PaymentMethodContext.ts +36 -0
  205. package/src/checkout/context/SessionContext.ts +49 -0
  206. package/src/checkout/context/SubmitContext.ts +14 -0
  207. package/src/checkout/context/index.ts +6 -0
  208. package/src/checkout/core/billingInterval.ts +62 -0
  209. package/src/checkout/core/crossSell.ts +52 -0
  210. package/src/checkout/core/customerForm.ts +122 -0
  211. package/src/checkout/core/exchangeRate.ts +38 -0
  212. package/src/checkout/core/index.ts +60 -0
  213. package/src/checkout/core/lineItems.ts +106 -0
  214. package/src/checkout/core/paymentMethod.ts +113 -0
  215. package/src/checkout/core/pricing.ts +347 -0
  216. package/src/checkout/core/promotion.ts +59 -0
  217. package/src/checkout/core/session.ts +62 -0
  218. package/src/checkout/core/submit.ts +109 -0
  219. package/src/checkout/hooks/index.ts +41 -0
  220. package/src/checkout/hooks/useBillingInterval.ts +71 -0
  221. package/src/checkout/hooks/useCheckout.ts +267 -0
  222. package/src/checkout/hooks/useCheckoutSession.ts +217 -0
  223. package/src/checkout/hooks/useCheckoutStatus.ts +31 -0
  224. package/src/checkout/hooks/useCrossSell.ts +80 -0
  225. package/src/checkout/hooks/useCustomerForm.ts +156 -0
  226. package/src/checkout/hooks/useCustomerFormFeature.ts +7 -0
  227. package/src/checkout/hooks/useExchangeRate.ts +28 -0
  228. package/src/checkout/hooks/useLineItems.ts +191 -0
  229. package/src/checkout/hooks/usePaymentMethod.ts +165 -0
  230. package/src/checkout/hooks/usePaymentMethodFeature.ts +8 -0
  231. package/src/checkout/hooks/usePricing.ts +274 -0
  232. package/src/checkout/hooks/usePricingFeature.ts +73 -0
  233. package/src/checkout/hooks/useProduct.ts +32 -0
  234. package/src/checkout/hooks/usePromotion.ts +67 -0
  235. package/src/checkout/hooks/useSlippage.ts +39 -0
  236. package/src/checkout/hooks/useSubmit.ts +684 -0
  237. package/src/checkout/hooks/useSubmitFeature.ts +7 -0
  238. package/src/checkout/hooks/useUpsell.ts +35 -0
  239. package/src/checkout/index.ts +65 -0
  240. package/src/checkout/types.ts +292 -0
  241. package/src/index.ts +64 -0
  242. package/src/shared/api.ts +118 -0
  243. package/src/shared/format.ts +318 -0
  244. package/src/shared/polling.ts +49 -0
  245. package/src/shared/types.ts +13 -0
  246. package/src/shared/validation.ts +254 -0
  247. package/src/types/checkout-augmented.ts +77 -0
  248. package/src/types/external.d.ts +18 -0
  249. package/tools/jest.js +1 -0
  250. package/tsconfig.json +18 -0
@@ -0,0 +1,274 @@
1
+ import { useState, useMemo, useEffect, useRef } from 'react';
2
+ import { useMemoizedFn } from 'ahooks';
3
+ import type { TPaymentCurrency, TLineItemExpanded } from '@blocklet/payment-types';
4
+
5
+ import { getErrorMessage } from '../../types/checkout-augmented';
6
+
7
+ import { formatExchangeRate, formatExchangeRateDisplay } from '../../shared/format';
8
+ import { checkHasDynamicPricing, fetchExchangeRate, getBackoffInterval } from '../core/exchangeRate';
9
+ import { calculateAmounts, calculateQuoteMeta, calculateTrial } from '../core/pricing';
10
+ import {
11
+ extractPromotionCodeFromSession,
12
+ applyPromotionCode,
13
+ removePromotionCode,
14
+ isPromotionActive,
15
+ } from '../core/promotion';
16
+ import { updateSlippage } from '../core/submit';
17
+ import type { SessionData } from './useCheckoutSession';
18
+
19
+ export interface UsePricingReturn {
20
+ subtotal: string;
21
+ paymentAmount: string;
22
+ discount: string | null;
23
+ tax: {
24
+ amount: string;
25
+ rate: number;
26
+ inclusive: boolean;
27
+ } | null;
28
+ staking: string | null;
29
+ total: string;
30
+ usdEquivalent: string | null;
31
+ hasDynamicPricing: boolean;
32
+ rate: {
33
+ value: string | null;
34
+ display: string | null;
35
+ provider: string | null;
36
+ providerDisplay: string | null;
37
+ fetchedAt: number | null;
38
+ status: 'loading' | 'available' | 'unavailable';
39
+ refresh: () => Promise<void>;
40
+ };
41
+ quote: {
42
+ locked: boolean;
43
+ lockedAt: number | null;
44
+ expiresAt: number | null;
45
+ expired: boolean;
46
+ baseCurrency: string | null;
47
+ };
48
+ slippage: {
49
+ percent: number;
50
+ set: (config: { mode: string; percent: number }) => Promise<void>;
51
+ };
52
+ promotion: {
53
+ applied: boolean;
54
+ code: string | null;
55
+ active: boolean;
56
+ inactiveReason: string | null;
57
+ apply: (code: string) => Promise<{ success: boolean; error?: string }>;
58
+ remove: () => Promise<void>;
59
+ };
60
+ trial: {
61
+ active: boolean;
62
+ days: number;
63
+ afterTrialPrice: string | null;
64
+ afterTrialInterval: string | null;
65
+ };
66
+ }
67
+
68
+ export function usePricing(
69
+ sessionData: SessionData | null,
70
+ sessionId: string,
71
+ currency: TPaymentCurrency | null,
72
+ isStripe: boolean,
73
+ refreshSession: (force?: boolean) => Promise<void>,
74
+ paymentMethodType?: string | null
75
+ ): UsePricingReturn {
76
+ const session = sessionData?.checkoutSession;
77
+ const items: TLineItemExpanded[] = (session?.line_items || []) as TLineItemExpanded[];
78
+
79
+ const [exchangeRate, setExchangeRate] = useState<string | null>(null);
80
+ const [rateProvider, setRateProvider] = useState<string | null>(null);
81
+ const [rateProviderDisplay, setRateProviderDisplay] = useState<string | null>(null);
82
+ const [rateFetchedAt, setRateFetchedAt] = useState<number | null>(null);
83
+ const [rateStatus, setRateStatus] = useState<'loading' | 'available' | 'unavailable'>('loading');
84
+ const [promotionCode, setPromotionCode] = useState<string | null>(null);
85
+
86
+ // Initialize promotionCode from session's existing discounts
87
+ useEffect(() => {
88
+ if (!session || promotionCode) return;
89
+ const code = extractPromotionCodeFromSession(session);
90
+ if (code) setPromotionCode(code);
91
+ }, [session?.id]); // eslint-disable-line react-hooks/exhaustive-deps
92
+
93
+ const pollingRef = useRef<ReturnType<typeof setTimeout> | null>(null);
94
+ const failCountRef = useRef(0);
95
+ const mountedRef = useRef(true);
96
+
97
+ const hasDynamicPricing = useMemo(() => checkHasDynamicPricing(items), [items]);
98
+
99
+ // Fetch exchange rate
100
+ const fetchRate = useMemoizedFn(async () => {
101
+ if (!sessionId || !hasDynamicPricing || isStripe) {
102
+ setRateStatus(hasDynamicPricing ? 'unavailable' : 'available');
103
+ if (isStripe) {
104
+ setExchangeRate(null);
105
+ setRateProvider(null);
106
+ setRateProviderDisplay(null);
107
+ setRateFetchedAt(null);
108
+ }
109
+ return;
110
+ }
111
+
112
+ try {
113
+ setRateStatus('loading');
114
+ const result = await fetchExchangeRate(sessionId, currency?.id);
115
+
116
+ if (!mountedRef.current) return;
117
+
118
+ if (result.rate) {
119
+ setExchangeRate(result.rate);
120
+ setRateProvider(result.provider);
121
+ setRateProviderDisplay(result.providerDisplay);
122
+ setRateFetchedAt(result.fetchedAt);
123
+ setRateStatus('available');
124
+ failCountRef.current = 0;
125
+ } else {
126
+ setRateStatus('unavailable');
127
+ }
128
+ } catch {
129
+ if (!mountedRef.current) return;
130
+ failCountRef.current += 1;
131
+ setRateStatus('unavailable');
132
+ }
133
+ });
134
+
135
+ // Rate polling with exponential backoff
136
+ useEffect(() => {
137
+ mountedRef.current = true;
138
+
139
+ if (!hasDynamicPricing || isStripe || !sessionId || session?.status === 'complete') {
140
+ // Clear stale rate when switching to Stripe
141
+ if (isStripe) {
142
+ setExchangeRate(null);
143
+ setRateProvider(null);
144
+ setRateProviderDisplay(null);
145
+ setRateFetchedAt(null);
146
+ setRateStatus('unavailable');
147
+ } else if (session?.status === 'complete') {
148
+ // Completed session: rate is irrelevant, suppress unavailable warnings
149
+ setRateStatus('available');
150
+ }
151
+ return undefined;
152
+ }
153
+
154
+ fetchRate();
155
+
156
+ const scheduleNext = () => {
157
+ const backoff = getBackoffInterval(failCountRef.current);
158
+ pollingRef.current = setTimeout(() => {
159
+ fetchRate().then(scheduleNext);
160
+ }, backoff);
161
+ };
162
+
163
+ scheduleNext();
164
+
165
+ // Visibility-aware polling
166
+ const handleVisibility = () => {
167
+ if (document.hidden) {
168
+ if (pollingRef.current) clearTimeout(pollingRef.current);
169
+ } else if (session?.status !== 'complete') {
170
+ fetchRate().then(scheduleNext);
171
+ }
172
+ };
173
+
174
+ document.addEventListener('visibilitychange', handleVisibility);
175
+
176
+ return () => {
177
+ mountedRef.current = false;
178
+ if (pollingRef.current) clearTimeout(pollingRef.current);
179
+ document.removeEventListener('visibilitychange', handleVisibility);
180
+ };
181
+ }, [hasDynamicPricing, isStripe, sessionId, currency?.id, session?.status]); // eslint-disable-line react-hooks/exhaustive-deps
182
+
183
+ // Calculate amounts
184
+ const amounts = useMemo(
185
+ () => calculateAmounts(items, currency, session, exchangeRate, hasDynamicPricing, paymentMethodType),
186
+ [items, currency, exchangeRate, hasDynamicPricing, session, paymentMethodType]
187
+ );
188
+
189
+ // Quote metadata
190
+ const quoteMeta = useMemo(
191
+ () => calculateQuoteMeta(items, hasDynamicPricing, sessionData),
192
+ [items, hasDynamicPricing, sessionData]
193
+ );
194
+
195
+ // Slippage
196
+ const setSlippage = useMemoizedFn(async (config: { mode: string; percent: number }) => {
197
+ try {
198
+ const data = await updateSlippage(sessionId, config);
199
+ if (data?.checkoutSession || data?.quotes) {
200
+ await refreshSession(true);
201
+ }
202
+ } catch (err: unknown) {
203
+ console.error('Failed to update slippage:', getErrorMessage(err));
204
+ }
205
+ });
206
+
207
+ const currentSlippagePercent = quoteMeta.slippagePercent ?? 0.5;
208
+
209
+ // Auto-refresh on quote expiry (skip if session already completed)
210
+ useEffect(() => {
211
+ if (!quoteMeta.expired || !quoteMeta.expiresAt || session?.status === 'complete') return;
212
+ refreshSession(true);
213
+ }, [quoteMeta.expired]); // eslint-disable-line react-hooks/exhaustive-deps
214
+
215
+ // Promotion
216
+ const applyPromotion = useMemoizedFn(async (code: string) => {
217
+ const result = await applyPromotionCode(sessionId, code, currency?.id);
218
+ if (result.success) {
219
+ setPromotionCode(code);
220
+ await refreshSession(true);
221
+ }
222
+ return result;
223
+ });
224
+
225
+ const removePromotion = useMemoizedFn(async () => {
226
+ try {
227
+ await removePromotionCode(sessionId);
228
+ setPromotionCode(null);
229
+ await refreshSession(true);
230
+ } catch {
231
+ // Ignore
232
+ }
233
+ });
234
+
235
+ const promotionApplied = (session?.discounts || []).length > 0;
236
+ const promotionActive = isPromotionActive(session);
237
+
238
+ // Trial
239
+ const trial = calculateTrial(session, currency?.id, items, currency, hasDynamicPricing, exchangeRate);
240
+
241
+ return {
242
+ ...amounts,
243
+ hasDynamicPricing,
244
+ rate: {
245
+ value: formatExchangeRate(exchangeRate),
246
+ display: exchangeRate ? formatExchangeRateDisplay(exchangeRate) : null,
247
+ provider: rateProvider,
248
+ providerDisplay: rateProviderDisplay,
249
+ fetchedAt: rateFetchedAt,
250
+ status: rateStatus,
251
+ refresh: fetchRate,
252
+ },
253
+ quote: {
254
+ locked: quoteMeta.locked,
255
+ lockedAt: quoteMeta.lockedAt,
256
+ expiresAt: quoteMeta.expiresAt,
257
+ expired: quoteMeta.expired,
258
+ baseCurrency: quoteMeta.baseCurrency,
259
+ },
260
+ slippage: {
261
+ percent: currentSlippagePercent,
262
+ set: setSlippage,
263
+ },
264
+ promotion: {
265
+ applied: promotionApplied,
266
+ code: promotionCode,
267
+ active: promotionActive,
268
+ inactiveReason: !promotionActive ? 'Promotions not allowed' : null,
269
+ apply: applyPromotion,
270
+ remove: removePromotion,
271
+ },
272
+ trial,
273
+ };
274
+ }
@@ -0,0 +1,73 @@
1
+ import { useMemo, useEffect } from 'react';
2
+
3
+ import { useSessionContext } from '../context/SessionContext';
4
+ import { usePaymentMethodContext } from '../context/PaymentMethodContext';
5
+ import { useExchangeRateContext } from '../context/ExchangeRateContext';
6
+ import { calculateAmounts, calculateQuoteMeta, calculateTrial } from '../core/pricing';
7
+
8
+ export interface UsePricingFeatureReturn {
9
+ subtotal: string;
10
+ paymentAmount: string;
11
+ discount: string | null;
12
+ tax: {
13
+ amount: string;
14
+ rate: number;
15
+ inclusive: boolean;
16
+ } | null;
17
+ staking: string | null;
18
+ total: string;
19
+ usdEquivalent: string | null;
20
+ hasDynamicPricing: boolean;
21
+ quote: {
22
+ locked: boolean;
23
+ lockedAt: number | null;
24
+ expiresAt: number | null;
25
+ expired: boolean;
26
+ baseCurrency: string | null;
27
+ };
28
+ trial: {
29
+ active: boolean;
30
+ days: number;
31
+ afterTrialPrice: string | null;
32
+ afterTrialInterval: string | null;
33
+ };
34
+ }
35
+
36
+ export function usePricingFeature(): UsePricingFeatureReturn {
37
+ const { items, session, sessionData, refresh } = useSessionContext();
38
+ const { currency } = usePaymentMethodContext();
39
+ const { rate: exchangeRate, hasDynamicPricing } = useExchangeRateContext();
40
+
41
+ const { current: currentMethod } = usePaymentMethodContext();
42
+
43
+ const amounts = useMemo(
44
+ () => calculateAmounts(items, currency, session, exchangeRate, hasDynamicPricing, currentMethod?.type || null),
45
+ [items, currency, exchangeRate, hasDynamicPricing, session, currentMethod?.type]
46
+ );
47
+
48
+ const quoteMeta = useMemo(
49
+ () => calculateQuoteMeta(items, hasDynamicPricing, sessionData),
50
+ [items, hasDynamicPricing, sessionData]
51
+ );
52
+
53
+ // Auto-refresh on quote expiry (skip if session already completed)
54
+ useEffect(() => {
55
+ if (!quoteMeta.expired || !quoteMeta.expiresAt || session?.status === 'complete') return;
56
+ refresh(true);
57
+ }, [quoteMeta.expired]); // eslint-disable-line react-hooks/exhaustive-deps
58
+
59
+ const trial = calculateTrial(session, currency?.id, items, currency, hasDynamicPricing, exchangeRate);
60
+
61
+ return {
62
+ ...amounts,
63
+ hasDynamicPricing,
64
+ quote: {
65
+ locked: quoteMeta.locked,
66
+ lockedAt: quoteMeta.lockedAt,
67
+ expiresAt: quoteMeta.expiresAt,
68
+ expired: quoteMeta.expired,
69
+ baseCurrency: quoteMeta.baseCurrency,
70
+ },
71
+ trial,
72
+ };
73
+ }
@@ -0,0 +1,32 @@
1
+ import { useSessionContext } from '../context/SessionContext';
2
+
3
+ export interface UseProductReturn {
4
+ product: {
5
+ name: string;
6
+ description: string;
7
+ images: string[];
8
+ features: Array<{ name: string; icon?: string }>;
9
+ billing: {
10
+ mode: 'payment' | 'subscription';
11
+ interval: 'month' | 'year' | 'week' | 'day' | null;
12
+ intervalCount: number;
13
+ displayInterval: string;
14
+ };
15
+ metadata: Record<string, string>;
16
+ } | null;
17
+ subscription: {
18
+ mode: 'payment' | 'subscription' | 'setup';
19
+ showStake: boolean;
20
+ confirmMessage: string;
21
+ } | null;
22
+ pageInfo: {
23
+ formPurposeDescription?: { en: string; zh: string };
24
+ showProductFeatures: boolean;
25
+ } | null;
26
+ vendorCount: number;
27
+ }
28
+
29
+ export function useProduct(): UseProductReturn {
30
+ const { product, subscription, pageInfo, vendorCount } = useSessionContext();
31
+ return { product, subscription, pageInfo, vendorCount };
32
+ }
@@ -0,0 +1,67 @@
1
+ import { useState, useEffect } from 'react';
2
+ import { useMemoizedFn } from 'ahooks';
3
+
4
+ import { useSessionContext } from '../context/SessionContext';
5
+ import { usePaymentMethodContext } from '../context/PaymentMethodContext';
6
+ import {
7
+ extractPromotionCodeFromSession,
8
+ applyPromotionCode,
9
+ removePromotionCode,
10
+ isPromotionActive,
11
+ } from '../core/promotion';
12
+
13
+ export interface UsePromotionReturn {
14
+ applied: boolean;
15
+ code: string | null;
16
+ active: boolean;
17
+ inactiveReason: string | null;
18
+ apply: (code: string) => Promise<{ success: boolean; error?: string }>;
19
+ remove: () => Promise<void>;
20
+ }
21
+
22
+ export function usePromotion(): UsePromotionReturn {
23
+ const { session, effectiveSessionId, refresh } = useSessionContext();
24
+ const { currency } = usePaymentMethodContext();
25
+
26
+ const [promotionCode, setPromotionCode] = useState<string | null>(null);
27
+
28
+ // Initialize from session's existing discounts
29
+ useEffect(() => {
30
+ if (!session || promotionCode) return;
31
+ const code = extractPromotionCodeFromSession(session);
32
+ if (code) setPromotionCode(code);
33
+ }, [session?.id]); // eslint-disable-line react-hooks/exhaustive-deps
34
+
35
+ const apply = useMemoizedFn(async (code: string) => {
36
+ if (session?.status === 'complete') return { success: false, error: 'Session already completed' };
37
+ const result = await applyPromotionCode(effectiveSessionId, code, currency?.id);
38
+ if (result.success) {
39
+ setPromotionCode(code);
40
+ await refresh(true);
41
+ }
42
+ return result;
43
+ });
44
+
45
+ const remove = useMemoizedFn(async () => {
46
+ if (session?.status === 'complete') return;
47
+ try {
48
+ await removePromotionCode(effectiveSessionId);
49
+ setPromotionCode(null);
50
+ await refresh(true);
51
+ } catch {
52
+ // Ignore
53
+ }
54
+ });
55
+
56
+ const promotionApplied = (session?.discounts || []).length > 0;
57
+ const promotionActive = isPromotionActive(session);
58
+
59
+ return {
60
+ applied: promotionApplied,
61
+ code: promotionCode,
62
+ active: promotionActive,
63
+ inactiveReason: !promotionActive ? 'Promotions not allowed' : null,
64
+ apply,
65
+ remove,
66
+ };
67
+ }
@@ -0,0 +1,39 @@
1
+ import { useMemo } from 'react';
2
+ import { useMemoizedFn } from 'ahooks';
3
+
4
+ import { getErrorMessage } from '../../types/checkout-augmented';
5
+ import { useSessionContext } from '../context/SessionContext';
6
+ import { useExchangeRateContext } from '../context/ExchangeRateContext';
7
+ import { calculateQuoteMeta } from '../core/pricing';
8
+ import { updateSlippage } from '../core/submit';
9
+
10
+ export interface UseSlippageReturn {
11
+ percent: number;
12
+ set: (config: { mode: string; percent: number }) => Promise<void>;
13
+ }
14
+
15
+ export function useSlippage(): UseSlippageReturn {
16
+ const { items, sessionData, effectiveSessionId, refresh } = useSessionContext();
17
+ const { hasDynamicPricing } = useExchangeRateContext();
18
+
19
+ const quoteMeta = useMemo(
20
+ () => calculateQuoteMeta(items, hasDynamicPricing, sessionData),
21
+ [items, hasDynamicPricing, sessionData]
22
+ );
23
+
24
+ const set = useMemoizedFn(async (config: { mode: string; percent: number }) => {
25
+ try {
26
+ const data = await updateSlippage(effectiveSessionId, config);
27
+ if (data?.checkoutSession || data?.quotes) {
28
+ await refresh(true);
29
+ }
30
+ } catch (err: unknown) {
31
+ console.error('Failed to update slippage:', getErrorMessage(err));
32
+ }
33
+ });
34
+
35
+ return {
36
+ percent: quoteMeta.slippagePercent ?? 0.5,
37
+ set,
38
+ };
39
+ }