@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,75 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useCrossSell = useCrossSell;
7
+ var _react = require("react");
8
+ var _ahooks = require("ahooks");
9
+ var _checkoutAugmented = require("../../types/checkout-augmented");
10
+ var _SessionContext = require("../context/SessionContext");
11
+ var _PaymentMethodContext = require("../context/PaymentMethodContext");
12
+ var _lineItems = require("../core/lineItems");
13
+ var _crossSell = require("../core/crossSell");
14
+ function useCrossSell() {
15
+ const {
16
+ items,
17
+ session,
18
+ effectiveSessionId,
19
+ refresh
20
+ } = (0, _SessionContext.useSessionContext)();
21
+ const {
22
+ currency
23
+ } = (0, _PaymentMethodContext.usePaymentMethodContext)();
24
+ const currencyId = currency?.id || null;
25
+ const embeddedItem = (0, _react.useMemo)(() => (0, _lineItems.getCrossSellItem)(items), [items]);
26
+ const [fetchedItem, setFetchedItem] = (0, _react.useState)(null);
27
+ const itemPriceIds = (0, _react.useMemo)(() => items.map(i => i.price_id).join(","), [items]);
28
+ const hasCrossSellInItems = (0, _react.useMemo)(() => items.some(i => i.cross_sell), [items]);
29
+ (0, _react.useEffect)(() => {
30
+ if (!effectiveSessionId || !session) return void 0;
31
+ if (session.status === "complete") return void 0;
32
+ if (embeddedItem) {
33
+ setFetchedItem(null);
34
+ return void 0;
35
+ }
36
+ if (hasCrossSellInItems) {
37
+ return void 0;
38
+ }
39
+ let cancelled = false;
40
+ (0, _crossSell.fetchCrossSellItem)(effectiveSessionId).then(item2 => {
41
+ if (!cancelled) {
42
+ setFetchedItem(item2);
43
+ }
44
+ });
45
+ return () => {
46
+ cancelled = true;
47
+ };
48
+ }, [effectiveSessionId, session?.id, embeddedItem, itemPriceIds, hasCrossSellInItems]);
49
+ const item = embeddedItem || fetchedItem;
50
+ const required = (0, _react.useMemo)(() => items.some(i => i.cross_sell_required), [items]);
51
+ const add = (0, _ahooks.useMemoizedFn)(async () => {
52
+ if (session?.status === "complete") return;
53
+ const crossSellItemPrice = (0, _lineItems.getCrossSellItem)(items);
54
+ if (!crossSellItemPrice) return;
55
+ try {
56
+ await (0, _crossSell.addCrossSellItem)(effectiveSessionId, crossSellItemPrice.id, session, currencyId, refresh);
57
+ } catch (err) {
58
+ console.error("Failed to add cross-sell:", (0, _checkoutAugmented.getErrorMessage)(err));
59
+ }
60
+ });
61
+ const remove = (0, _ahooks.useMemoizedFn)(async () => {
62
+ if (session?.status === "complete") return;
63
+ try {
64
+ await (0, _crossSell.removeCrossSellItem)(effectiveSessionId, session, currencyId, refresh);
65
+ } catch (err) {
66
+ console.error("Failed to remove cross-sell:", (0, _checkoutAugmented.getErrorMessage)(err));
67
+ }
68
+ });
69
+ return {
70
+ item,
71
+ required,
72
+ add,
73
+ remove
74
+ };
75
+ }
@@ -0,0 +1,14 @@
1
+ import type { FieldConfig, CheckoutFormData } from '../types';
2
+ import type { SessionData } from './useCheckoutSession';
3
+ export interface UseCustomerFormReturn {
4
+ fields: FieldConfig[];
5
+ values: CheckoutFormData;
6
+ onChange: (field: string, value: string | boolean | Record<string, string>) => void;
7
+ errors: Partial<Record<string, string>>;
8
+ touched: Record<string, boolean>;
9
+ validate: () => Promise<boolean>;
10
+ validateField: (field: string) => Promise<void>;
11
+ /** Re-fetch customer info from backend and update form values (e.g. after login) */
12
+ refetchCustomer: () => Promise<void>;
13
+ }
14
+ export declare function useCustomerForm(sessionData: SessionData | null, currencyId: string | null, methodId: string | null): UseCustomerFormReturn;
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useCustomerForm = useCustomerForm;
7
+ var _react = require("react");
8
+ var _ahooks = require("ahooks");
9
+ var _api = _interopRequireWildcard(require("../../shared/api"));
10
+ var _validation = require("../../shared/validation");
11
+ var _customerForm = require("../core/customerForm");
12
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
13
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
14
+ function useCustomerForm(sessionData, currencyId, methodId) {
15
+ const session = sessionData?.checkoutSession;
16
+ const customer = sessionData?.customer;
17
+ const fields = (0, _react.useMemo)(() => (0, _customerForm.buildFields)(session), [session?.id]);
18
+ const [values, setValues] = (0, _react.useState)(() => (0, _customerForm.createInitialValues)(session, customer));
19
+ const [errors, setErrors] = (0, _react.useState)({});
20
+ const [touched, setTouched] = (0, _react.useState)({});
21
+ const [prefetched, setPrefetched] = (0, _react.useState)(false);
22
+ (0, _react.useEffect)(() => {
23
+ if (session && !prefetched) {
24
+ setValues((0, _customerForm.createInitialValues)(session, customer));
25
+ }
26
+ }, [session?.id]);
27
+ (0, _react.useEffect)(() => {
28
+ if (currencyId || methodId) {
29
+ setValues(prev => ({
30
+ ...prev,
31
+ ...(currencyId && {
32
+ payment_currency: currencyId
33
+ }),
34
+ ...(methodId && {
35
+ payment_method: methodId
36
+ })
37
+ }));
38
+ }
39
+ }, [currencyId, methodId]);
40
+ (0, _react.useEffect)(() => {
41
+ if (!session || prefetched || session.status === "complete") return;
42
+ const fetchCustomer = async () => {
43
+ try {
44
+ const {
45
+ data
46
+ } = await _api.default.get(`${_api.API.CUSTOMER_ME}?fallback=1&skipSummary=1`);
47
+ if (data) {
48
+ setPrefetched(true);
49
+ setValues(prev => ({
50
+ ...prev,
51
+ customer_name: prev.customer_name || data.name || "",
52
+ customer_email: prev.customer_email || data.email || "",
53
+ customer_phone: prev.customer_phone || data.phone || "",
54
+ billing_address: {
55
+ ...prev.billing_address,
56
+ country: prev.billing_address?.country || data.address?.country || "",
57
+ state: prev.billing_address?.state || data.address?.state || "",
58
+ city: prev.billing_address?.city || data.address?.city || "",
59
+ line1: prev.billing_address?.line1 || data.address?.line1 || "",
60
+ line2: prev.billing_address?.line2 || data.address?.line2 || "",
61
+ postal_code: prev.billing_address?.postal_code || data.address?.postal_code || ""
62
+ }
63
+ }));
64
+ }
65
+ } catch {}
66
+ };
67
+ fetchCustomer();
68
+ }, [session?.id]);
69
+ const onChange = (0, _ahooks.useMemoizedFn)((field, value) => {
70
+ setValues(prev => (0, _customerForm.setNestedValue)(prev, field, value));
71
+ setTouched(prev => ({
72
+ ...prev,
73
+ [field]: true
74
+ }));
75
+ });
76
+ const getValidateOptions = (0, _ahooks.useMemoizedFn)(() => ({
77
+ phoneEnabled: !!session?.phone_number_collection?.enabled,
78
+ addressMode: session?.billing_address_collection,
79
+ fieldValidation: session?.metadata?.page_info?.field_validation
80
+ }));
81
+ const validate = (0, _ahooks.useMemoizedFn)(async () => {
82
+ const result = await (0, _validation.validateForm)(values, getValidateOptions());
83
+ setErrors(result.errors);
84
+ return result.valid;
85
+ });
86
+ const validateField = (0, _ahooks.useMemoizedFn)(async field => {
87
+ const result = await (0, _validation.validateForm)(values, getValidateOptions());
88
+ setErrors(prev => {
89
+ const next = {
90
+ ...prev
91
+ };
92
+ if (result.errors[field]) {
93
+ next[field] = result.errors[field];
94
+ } else {
95
+ delete next[field];
96
+ }
97
+ return next;
98
+ });
99
+ });
100
+ const refetchCustomer = (0, _ahooks.useMemoizedFn)(async () => {
101
+ try {
102
+ const {
103
+ data
104
+ } = await _api.default.get(`${_api.API.CUSTOMER_ME}?fallback=1&skipSummary=1`);
105
+ if (data) {
106
+ setPrefetched(true);
107
+ setValues(prev => ({
108
+ ...prev,
109
+ customer_name: data.name || prev.customer_name || "",
110
+ customer_email: data.email || prev.customer_email || "",
111
+ customer_phone: data.phone || prev.customer_phone || "",
112
+ billing_address: {
113
+ ...prev.billing_address,
114
+ country: data.address?.country || prev.billing_address?.country || "",
115
+ state: data.address?.state || prev.billing_address?.state || "",
116
+ city: data.address?.city || prev.billing_address?.city || "",
117
+ line1: data.address?.line1 || prev.billing_address?.line1 || "",
118
+ line2: data.address?.line2 || prev.billing_address?.line2 || "",
119
+ postal_code: data.address?.postal_code || prev.billing_address?.postal_code || ""
120
+ }
121
+ }));
122
+ }
123
+ } catch {}
124
+ });
125
+ return {
126
+ fields,
127
+ values,
128
+ onChange,
129
+ errors,
130
+ touched,
131
+ validate,
132
+ validateField,
133
+ refetchCustomer
134
+ };
135
+ }
@@ -0,0 +1,2 @@
1
+ import type { UseCustomerFormReturn } from './useCustomerForm';
2
+ export declare function useCustomerFormFeature(): UseCustomerFormReturn;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useCustomerFormFeature = useCustomerFormFeature;
7
+ var _CustomerFormContext = require("../context/CustomerFormContext");
8
+ function useCustomerFormFeature() {
9
+ return (0, _CustomerFormContext.useCustomerFormContext)();
10
+ }
@@ -0,0 +1,11 @@
1
+ export interface UseExchangeRateReturn {
2
+ value: string | null;
3
+ display: string | null;
4
+ provider: string | null;
5
+ providerDisplay: string | null;
6
+ fetchedAt: number | null;
7
+ status: 'loading' | 'available' | 'unavailable';
8
+ hasDynamicPricing: boolean;
9
+ refresh: () => Promise<void>;
10
+ }
11
+ export declare function useExchangeRate(): UseExchangeRateReturn;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useExchangeRate = useExchangeRate;
7
+ var _ExchangeRateContext = require("../context/ExchangeRateContext");
8
+ var _format = require("../../shared/format");
9
+ function useExchangeRate() {
10
+ const {
11
+ rate,
12
+ provider,
13
+ providerDisplay,
14
+ fetchedAt,
15
+ status,
16
+ hasDynamicPricing,
17
+ refresh
18
+ } = (0, _ExchangeRateContext.useExchangeRateContext)();
19
+ return {
20
+ value: (0, _format.formatExchangeRate)(rate),
21
+ display: rate ? (0, _format.formatExchangeRateDisplay)(rate) : null,
22
+ provider,
23
+ providerDisplay,
24
+ fetchedAt,
25
+ status,
26
+ hasDynamicPricing,
27
+ refresh
28
+ };
29
+ }
@@ -0,0 +1,22 @@
1
+ import type { TLineItemExpanded, TPrice } from '@blocklet/payment-types';
2
+ export interface UseLineItemsReturn {
3
+ items: Array<TLineItemExpanded & {
4
+ adjustable_quantity?: {
5
+ enabled: boolean;
6
+ minimum?: number;
7
+ maximum?: number;
8
+ };
9
+ }>;
10
+ /** true if all items pass inventory check (quantity_available, quantity_limit_per_checkout) */
11
+ inventoryOk: boolean;
12
+ updateQuantity: (itemId: string, qty: number) => Promise<void>;
13
+ upsell: (fromId: string, toId: string) => Promise<void>;
14
+ downsell: (priceId: string) => Promise<void>;
15
+ crossSellItem: TPrice | null;
16
+ crossSellRequired: boolean;
17
+ addCrossSell: () => Promise<void>;
18
+ removeCrossSell: () => Promise<void>;
19
+ isDonation: boolean;
20
+ setDonationAmount: (priceId: string, amount: string) => Promise<void>;
21
+ }
22
+ export declare function useLineItems(): UseLineItemsReturn;
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useLineItems = useLineItems;
7
+ var _react = require("react");
8
+ var _ahooks = require("ahooks");
9
+ var _checkoutAugmented = require("../../types/checkout-augmented");
10
+ var _SessionContext = require("../context/SessionContext");
11
+ var _PaymentMethodContext = require("../context/PaymentMethodContext");
12
+ var _lineItems = require("../core/lineItems");
13
+ var _crossSell = require("../core/crossSell");
14
+ function useLineItems() {
15
+ const {
16
+ items,
17
+ session,
18
+ effectiveSessionId,
19
+ isDonation,
20
+ refresh
21
+ } = (0, _SessionContext.useSessionContext)();
22
+ const {
23
+ currency
24
+ } = (0, _PaymentMethodContext.usePaymentMethodContext)();
25
+ const currencyId = currency?.id || null;
26
+ const defaultQtyApplied = (0, _react.useRef)(false);
27
+ (0, _react.useEffect)(() => {
28
+ if (defaultQtyApplied.current || !effectiveSessionId || !items.length || !currencyId || session?.status === "complete") return;
29
+ try {
30
+ const params = new URLSearchParams(window.location.search);
31
+ for (const item of items) {
32
+ const qtyStr = params.get(`qty_${item.price_id}`) || params.get(`qty_${item.price?.id}`) || params.get("qty");
33
+ if (qtyStr) {
34
+ const qty = Math.max(1, parseInt(qtyStr, 10));
35
+ if (Number.isFinite(qty) && qty !== item.quantity) {
36
+ defaultQtyApplied.current = true;
37
+ (0, _lineItems.adjustQuantity)(effectiveSessionId, item.price_id, qty, currencyId, session, refresh);
38
+ break;
39
+ }
40
+ }
41
+ }
42
+ } catch {}
43
+ }, [effectiveSessionId, items, currencyId]);
44
+ const updateQuantity = (0, _ahooks.useMemoizedFn)(async (itemId, qty) => {
45
+ if (session?.status === "complete") return;
46
+ try {
47
+ await (0, _lineItems.adjustQuantity)(effectiveSessionId, itemId, qty, currencyId, session, refresh);
48
+ } catch (err) {
49
+ console.error("Failed to update quantity:", (0, _checkoutAugmented.getErrorMessage)(err));
50
+ }
51
+ });
52
+ const upsell = (0, _ahooks.useMemoizedFn)(async (fromId, toId) => {
53
+ if (session?.status === "complete") return;
54
+ await (0, _lineItems.performUpsell)(effectiveSessionId, fromId, toId, session, currencyId, refresh);
55
+ });
56
+ const downsell = (0, _ahooks.useMemoizedFn)(async priceId => {
57
+ if (session?.status === "complete") return;
58
+ await (0, _lineItems.performDownsell)(effectiveSessionId, priceId, session, currencyId, refresh);
59
+ });
60
+ const embeddedCrossSellItem = (0, _react.useMemo)(() => (0, _lineItems.getCrossSellItem)(items), [items]);
61
+ const [fetchedCrossSellItem, setFetchedCrossSellItem] = (0, _react.useState)(null);
62
+ const itemPriceIds = (0, _react.useMemo)(() => items.map(i => i.price_id).join(","), [items]);
63
+ const hasCrossSellInItems = (0, _react.useMemo)(() => items.some(i => i.cross_sell), [items]);
64
+ (0, _react.useEffect)(() => {
65
+ if (!effectiveSessionId || !session) return void 0;
66
+ if (session.status === "complete") return void 0;
67
+ if (embeddedCrossSellItem) {
68
+ setFetchedCrossSellItem(null);
69
+ return void 0;
70
+ }
71
+ if (hasCrossSellInItems) {
72
+ return void 0;
73
+ }
74
+ let cancelled = false;
75
+ (0, _crossSell.fetchCrossSellItem)(effectiveSessionId).then(item => {
76
+ if (!cancelled) {
77
+ setFetchedCrossSellItem(item);
78
+ }
79
+ });
80
+ return () => {
81
+ cancelled = true;
82
+ };
83
+ }, [effectiveSessionId, session?.id, embeddedCrossSellItem, itemPriceIds, hasCrossSellInItems]);
84
+ const crossSellItem = embeddedCrossSellItem || fetchedCrossSellItem;
85
+ const crossSellRequired = (0, _react.useMemo)(() => items.some(item => item.cross_sell_required), [items]);
86
+ const addCrossSell = (0, _ahooks.useMemoizedFn)(async () => {
87
+ if (session?.status === "complete") return;
88
+ if (!crossSellItem) return;
89
+ try {
90
+ await (0, _crossSell.addCrossSellItem)(effectiveSessionId, crossSellItem.id, session, currencyId, refresh);
91
+ } catch (err) {
92
+ console.error("Failed to add cross-sell:", (0, _checkoutAugmented.getErrorMessage)(err));
93
+ }
94
+ });
95
+ const removeCrossSell = (0, _ahooks.useMemoizedFn)(async () => {
96
+ if (session?.status === "complete") return;
97
+ try {
98
+ await (0, _crossSell.removeCrossSellItem)(effectiveSessionId, session, currencyId, refresh);
99
+ } catch (err) {
100
+ console.error("Failed to remove cross-sell:", (0, _checkoutAugmented.getErrorMessage)(err));
101
+ }
102
+ });
103
+ const setDonationAmount = (0, _ahooks.useMemoizedFn)(async (priceId, amount) => {
104
+ if (session?.status === "complete") return;
105
+ if (!isDonation) return;
106
+ try {
107
+ await (0, _lineItems.changeDonationAmount)(effectiveSessionId, priceId, amount, session, currencyId, refresh);
108
+ } catch (err) {
109
+ console.error("Failed to change amount:", (0, _checkoutAugmented.getErrorMessage)(err));
110
+ }
111
+ });
112
+ const mappedItems = (0, _react.useMemo)(() => items.map(item => ({
113
+ ...item,
114
+ adjustable_quantity: item.adjustable_quantity
115
+ })), [items]);
116
+ const inventoryOk = (0, _react.useMemo)(() => items.every(item => {
117
+ const {
118
+ price
119
+ } = item;
120
+ if (!price) return true;
121
+ const q = Number(item.quantity) || 0;
122
+ const available = price.quantity_available || 0;
123
+ const sold = price.quantity_sold || 0;
124
+ const limitPerCheckout = price.quantity_limit_per_checkout || 0;
125
+ if (available > 0 && sold + q > available) return false;
126
+ if (limitPerCheckout > 0 && limitPerCheckout < q) return false;
127
+ return true;
128
+ }), [items]);
129
+ return {
130
+ items: mappedItems,
131
+ inventoryOk,
132
+ updateQuantity,
133
+ upsell,
134
+ downsell,
135
+ crossSellItem,
136
+ crossSellRequired,
137
+ addCrossSell,
138
+ removeCrossSell,
139
+ isDonation,
140
+ setDonationAmount
141
+ };
142
+ }
@@ -0,0 +1,26 @@
1
+ import type { TPaymentMethodExpanded, TPaymentCurrency } from '@blocklet/payment-types';
2
+ import type { SessionData } from './useCheckoutSession';
3
+ export interface UsePaymentMethodReturn {
4
+ current: TPaymentMethodExpanded;
5
+ currency: TPaymentCurrency;
6
+ available: TPaymentMethodExpanded[];
7
+ currencies: TPaymentCurrency[];
8
+ isStripe: boolean;
9
+ isCrypto: boolean;
10
+ isCredit: boolean;
11
+ switching: boolean;
12
+ setType: (type: 'stripe' | 'crypto') => Promise<void>;
13
+ types: Array<{
14
+ type: 'stripe' | 'crypto';
15
+ label: string;
16
+ currencies: TPaymentCurrency[];
17
+ active: boolean;
18
+ }>;
19
+ setCurrency: (currencyId: string) => Promise<void>;
20
+ stripe: {
21
+ publishableKey: string | null;
22
+ clientSecret: string | null;
23
+ status: 'idle' | 'ready' | 'processing' | 'succeeded' | 'failed';
24
+ } | null;
25
+ }
26
+ export declare function usePaymentMethod(sessionData: SessionData | null, sessionId: string, refreshSession: (force?: boolean) => Promise<void>): UsePaymentMethodReturn;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.usePaymentMethod = usePaymentMethod;
7
+ var _react = require("react");
8
+ var _ahooks = require("ahooks");
9
+ var _checkoutAugmented = require("../../types/checkout-augmented");
10
+ var _api = _interopRequireWildcard(require("../../shared/api"));
11
+ var _paymentMethod = require("../core/paymentMethod");
12
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
13
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
14
+ function usePaymentMethod(sessionData, sessionId, refreshSession) {
15
+ const methods = sessionData?.paymentMethods || [];
16
+ const session = sessionData?.checkoutSession;
17
+ const [currencyId, setCurrencyId] = (0, _react.useState)(() => (0, _paymentMethod.getInitialCurrencyId)(session, methods));
18
+ const [switching, setSwitching] = (0, _react.useState)(false);
19
+ const initialSyncedRef = (0, _react.useRef)(null);
20
+ (0, _react.useEffect)(() => {
21
+ if (session && !currencyId) {
22
+ setCurrencyId((0, _paymentMethod.getInitialCurrencyId)(session, methods));
23
+ }
24
+ }, [session?.id]);
25
+ const {
26
+ method: currentMethod,
27
+ currency: currentCurrency
28
+ } = (0, _react.useMemo)(() => (0, _paymentMethod.findMethodAndCurrency)(methods, currencyId), [methods, currencyId]);
29
+ const allCurrencies = (0, _react.useMemo)(() => (0, _paymentMethod.flattenCurrencies)(methods), [methods]);
30
+ const isStripe = currentMethod?.type === "stripe";
31
+ const isCrypto = currentMethod?.type !== "stripe" && currentMethod?.type !== void 0;
32
+ const isCredit = currentCurrency?.type === "credit";
33
+ const types = (0, _react.useMemo)(() => (0, _paymentMethod.buildPaymentTypes)(methods, currentMethod), [methods, currentMethod]);
34
+ const setType = (0, _ahooks.useMemoizedFn)(async type => {
35
+ const targetMethod = methods.find(m => type === "stripe" ? m.type === "stripe" : m.type !== "stripe");
36
+ if (!targetMethod) return;
37
+ const firstCurrency = targetMethod.payment_currencies?.[0];
38
+ if (firstCurrency) {
39
+ await switchCurrency(firstCurrency.id);
40
+ }
41
+ });
42
+ const switchCurrency = (0, _ahooks.useMemoizedFn)(async newCurrencyId => {
43
+ if (session?.status === "complete") return;
44
+ const {
45
+ method
46
+ } = (0, _paymentMethod.findMethodAndCurrency)(methods, newCurrencyId);
47
+ if (!method || !sessionId) return;
48
+ setSwitching(true);
49
+ try {
50
+ await _api.default.put(_api.API.SWITCH_CURRENCY(sessionId), {
51
+ currency_id: newCurrencyId,
52
+ payment_method_id: method.id
53
+ });
54
+ setCurrencyId(newCurrencyId);
55
+ try {
56
+ localStorage.setItem((0, _paymentMethod.getCurrencyStorageKey)(session?.user?.did), newCurrencyId);
57
+ } catch {}
58
+ await refreshSession(true);
59
+ } catch (err) {
60
+ console.error("Failed to switch currency:", (0, _checkoutAugmented.getErrorMessage)(err));
61
+ if (session?.currency_id) {
62
+ setCurrencyId(session.currency_id);
63
+ }
64
+ } finally {
65
+ setSwitching(false);
66
+ }
67
+ });
68
+ (0, _react.useEffect)(() => {
69
+ if (!session?.id || !currencyId || !methods.length) return;
70
+ if (initialSyncedRef.current === session.id) return;
71
+ initialSyncedRef.current = session.id;
72
+ const sessionCurrencyId = session.currency_id;
73
+ if (session.status === "complete") return;
74
+ if (sessionCurrencyId && sessionCurrencyId !== currencyId) {
75
+ switchCurrency(currencyId);
76
+ }
77
+ }, [session?.id, currencyId, methods.length]);
78
+ const stripe = (0, _react.useMemo)(() => {
79
+ if (!currentMethod || currentMethod.type !== "stripe") return null;
80
+ const stripeSettings = currentMethod.settings?.stripe;
81
+ return {
82
+ publishableKey: stripeSettings?.publishable_key || null,
83
+ clientSecret: sessionData?.paymentIntent?.client_secret || null,
84
+ status: "idle"
85
+ };
86
+ }, [currentMethod, sessionData?.paymentIntent]);
87
+ return {
88
+ current: currentMethod,
89
+ currency: currentCurrency,
90
+ available: methods,
91
+ currencies: allCurrencies,
92
+ isStripe,
93
+ isCrypto,
94
+ isCredit,
95
+ switching,
96
+ setType,
97
+ types,
98
+ setCurrency: switchCurrency,
99
+ stripe
100
+ };
101
+ }
@@ -0,0 +1,2 @@
1
+ import type { UsePaymentMethodReturn } from './usePaymentMethod';
2
+ export declare function usePaymentMethodFeature(): UsePaymentMethodReturn;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.usePaymentMethodFeature = usePaymentMethodFeature;
7
+ var _PaymentMethodContext = require("../context/PaymentMethodContext");
8
+ function usePaymentMethodFeature() {
9
+ return (0, _PaymentMethodContext.usePaymentMethodContext)();
10
+ }
@@ -0,0 +1,57 @@
1
+ import type { TPaymentCurrency } from '@blocklet/payment-types';
2
+ import type { SessionData } from './useCheckoutSession';
3
+ export interface UsePricingReturn {
4
+ subtotal: string;
5
+ paymentAmount: string;
6
+ discount: string | null;
7
+ tax: {
8
+ amount: string;
9
+ rate: number;
10
+ inclusive: boolean;
11
+ } | null;
12
+ staking: string | null;
13
+ total: string;
14
+ usdEquivalent: string | null;
15
+ hasDynamicPricing: boolean;
16
+ rate: {
17
+ value: string | null;
18
+ display: string | null;
19
+ provider: string | null;
20
+ providerDisplay: string | null;
21
+ fetchedAt: number | null;
22
+ status: 'loading' | 'available' | 'unavailable';
23
+ refresh: () => Promise<void>;
24
+ };
25
+ quote: {
26
+ locked: boolean;
27
+ lockedAt: number | null;
28
+ expiresAt: number | null;
29
+ expired: boolean;
30
+ baseCurrency: string | null;
31
+ };
32
+ slippage: {
33
+ percent: number;
34
+ set: (config: {
35
+ mode: string;
36
+ percent: number;
37
+ }) => Promise<void>;
38
+ };
39
+ promotion: {
40
+ applied: boolean;
41
+ code: string | null;
42
+ active: boolean;
43
+ inactiveReason: string | null;
44
+ apply: (code: string) => Promise<{
45
+ success: boolean;
46
+ error?: string;
47
+ }>;
48
+ remove: () => Promise<void>;
49
+ };
50
+ trial: {
51
+ active: boolean;
52
+ days: number;
53
+ afterTrialPrice: string | null;
54
+ afterTrialInterval: string | null;
55
+ };
56
+ }
57
+ export declare function usePricing(sessionData: SessionData | null, sessionId: string, currency: TPaymentCurrency | null, isStripe: boolean, refreshSession: (force?: boolean) => Promise<void>, paymentMethodType?: string | null): UsePricingReturn;