@commercelayer/react-components 4.27.0-beta.0 → 4.28.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 (200) hide show
  1. package/lib/cjs/components/MetadataInput.js +1 -1
  2. package/lib/cjs/components/SubmitButton.js +1 -1
  3. package/lib/cjs/components/addresses/Address.js +1 -1
  4. package/lib/cjs/components/addresses/AddressCountrySelector.js +1 -1
  5. package/lib/cjs/components/addresses/AddressField.js +1 -1
  6. package/lib/cjs/components/addresses/AddressInput.d.ts +4 -4
  7. package/lib/cjs/components/addresses/AddressInput.js +1 -1
  8. package/lib/cjs/components/addresses/AddressInputSelect.js +1 -1
  9. package/lib/cjs/components/addresses/AddressStateSelector.js +1 -1
  10. package/lib/cjs/components/addresses/AddressesContainer.js +1 -1
  11. package/lib/cjs/components/addresses/AddressesEmpty.js +1 -1
  12. package/lib/cjs/components/addresses/BillingAddressContainer.js +1 -1
  13. package/lib/cjs/components/addresses/BillingAddressForm.d.ts +4 -4
  14. package/lib/cjs/components/addresses/BillingAddressForm.js +1 -1
  15. package/lib/cjs/components/addresses/SaveAddressesButton.js +1 -1
  16. package/lib/cjs/components/addresses/ShippingAddressContainer.js +1 -1
  17. package/lib/cjs/components/addresses/ShippingAddressForm.d.ts +4 -4
  18. package/lib/cjs/components/addresses/ShippingAddressForm.js +1 -1
  19. package/lib/cjs/components/auth/CommerceLayer.js +1 -1
  20. package/lib/cjs/components/customers/CustomerAddressForm.js +1 -1
  21. package/lib/cjs/components/customers/CustomerContainer.js +1 -1
  22. package/lib/cjs/components/customers/CustomerField.js +1 -1
  23. package/lib/cjs/components/customers/CustomerInput.js +1 -1
  24. package/lib/cjs/components/customers/CustomerPaymentSource.js +1 -1
  25. package/lib/cjs/components/customers/CustomerPaymentSourceEmpty.js +1 -1
  26. package/lib/cjs/components/customers/MyAccountLink.js +1 -1
  27. package/lib/cjs/components/customers/MyIdentityLink.js +1 -1
  28. package/lib/cjs/components/customers/SaveCustomerButton.js +1 -1
  29. package/lib/cjs/components/errors/Errors.js +1 -1
  30. package/lib/cjs/components/gift_cards/GiftCardContainer.js +1 -1
  31. package/lib/cjs/components/gift_cards/GiftCardCurrencySelector.js +1 -1
  32. package/lib/cjs/components/gift_cards/GiftCardInput.js +1 -1
  33. package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.js +1 -1
  34. package/lib/cjs/components/gift_cards/GiftCardOrCouponForm.js +1 -1
  35. package/lib/cjs/components/gift_cards/GiftCardOrCouponInput.js +1 -1
  36. package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
  37. package/lib/cjs/components/gift_cards/GiftCardOrCouponSubmit.js +1 -1
  38. package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionButton.js +1 -1
  39. package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionsContainer.js +1 -1
  40. package/lib/cjs/components/line_items/LineItem.js +1 -1
  41. package/lib/cjs/components/line_items/LineItemAmount.js +1 -1
  42. package/lib/cjs/components/line_items/LineItemCode.js +1 -1
  43. package/lib/cjs/components/line_items/LineItemField.js +1 -1
  44. package/lib/cjs/components/line_items/LineItemImage.js +1 -1
  45. package/lib/cjs/components/line_items/LineItemName.js +1 -1
  46. package/lib/cjs/components/line_items/LineItemOption.js +1 -1
  47. package/lib/cjs/components/line_items/LineItemOptions.js +1 -1
  48. package/lib/cjs/components/line_items/LineItemQuantity.js +1 -1
  49. package/lib/cjs/components/line_items/LineItemRemoveLink.js +1 -1
  50. package/lib/cjs/components/line_items/LineItemsContainer.js +1 -1
  51. package/lib/cjs/components/line_items/LineItemsCount.js +1 -1
  52. package/lib/cjs/components/line_items/LineItemsEmpty.js +1 -1
  53. package/lib/cjs/components/orders/AddToCartButton.js +1 -1
  54. package/lib/cjs/components/orders/AdjustmentAmount.js +1 -1
  55. package/lib/cjs/components/orders/CartLink.js +1 -1
  56. package/lib/cjs/components/orders/CheckoutLink.js +1 -1
  57. package/lib/cjs/components/orders/DiscountAmount.js +1 -1
  58. package/lib/cjs/components/orders/GiftCardAmount.js +1 -1
  59. package/lib/cjs/components/orders/HostedCart.js +1 -1
  60. package/lib/cjs/components/orders/OrderContainer.d.ts +1 -1
  61. package/lib/cjs/components/orders/OrderContainer.js +1 -1
  62. package/lib/cjs/components/orders/OrderList.js +1 -1
  63. package/lib/cjs/components/orders/OrderListEmpty.js +1 -1
  64. package/lib/cjs/components/orders/OrderListPaginationButtons.js +1 -1
  65. package/lib/cjs/components/orders/OrderListPaginationInfo.js +1 -1
  66. package/lib/cjs/components/orders/OrderListRow.js +1 -1
  67. package/lib/cjs/components/orders/OrderNumber.js +1 -1
  68. package/lib/cjs/components/orders/OrderStorage.js +1 -1
  69. package/lib/cjs/components/orders/PaymentMethodAmount.js +1 -1
  70. package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
  71. package/lib/cjs/components/orders/PlaceOrderContainer.js +1 -1
  72. package/lib/cjs/components/orders/PrivacyAndTermsCheckbox.js +1 -1
  73. package/lib/cjs/components/orders/ShippingAmount.js +1 -1
  74. package/lib/cjs/components/orders/SubTotalAmount.js +1 -1
  75. package/lib/cjs/components/orders/TaxesAmount.js +1 -1
  76. package/lib/cjs/components/orders/TotalAmount.js +1 -1
  77. package/lib/cjs/components/parcels/ParcelField.js +1 -1
  78. package/lib/cjs/components/parcels/ParcelLineItem.js +1 -1
  79. package/lib/cjs/components/parcels/ParcelLineItemField.js +1 -1
  80. package/lib/cjs/components/parcels/ParcelLineItemsCount.js +1 -1
  81. package/lib/cjs/components/parcels/Parcels.js +1 -1
  82. package/lib/cjs/components/parcels/ParcelsCount.js +1 -1
  83. package/lib/cjs/components/payment_gateways/AdyenGateway.js +1 -1
  84. package/lib/cjs/components/payment_gateways/BraintreeGateway.js +1 -1
  85. package/lib/cjs/components/payment_gateways/CheckoutComGateway.js +1 -1
  86. package/lib/cjs/components/payment_gateways/ExternalGateway.js +1 -1
  87. package/lib/cjs/components/payment_gateways/KlarnaGateway.js +1 -1
  88. package/lib/cjs/components/payment_gateways/PaymentGateway.js +1 -1
  89. package/lib/cjs/components/payment_gateways/PaypalGateway.js +1 -1
  90. package/lib/cjs/components/payment_gateways/StripeGateway.js +1 -1
  91. package/lib/cjs/components/payment_gateways/WireTransferGateway.js +1 -1
  92. package/lib/cjs/components/payment_methods/PaymentMethod.js +1 -1
  93. package/lib/cjs/components/payment_methods/PaymentMethodName.js +1 -1
  94. package/lib/cjs/components/payment_methods/PaymentMethodPrice.js +1 -1
  95. package/lib/cjs/components/payment_methods/PaymentMethodRadioButton.js +1 -1
  96. package/lib/cjs/components/payment_methods/PaymentMethodsContainer.js +1 -1
  97. package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
  98. package/lib/cjs/components/payment_source/BraintreePayment.js +1 -1
  99. package/lib/cjs/components/payment_source/CheckoutComPayment.js +1 -1
  100. package/lib/cjs/components/payment_source/ExternalPayment.js +1 -1
  101. package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
  102. package/lib/cjs/components/payment_source/PaymentSource.js +1 -1
  103. package/lib/cjs/components/payment_source/PaymentSourceBrandIcon.js +1 -1
  104. package/lib/cjs/components/payment_source/PaymentSourceBrandName.js +1 -1
  105. package/lib/cjs/components/payment_source/PaymentSourceDetail.js +1 -1
  106. package/lib/cjs/components/payment_source/PaymentSourceEditButton.js +1 -1
  107. package/lib/cjs/components/payment_source/PaypalPayment.js +1 -1
  108. package/lib/cjs/components/payment_source/StripeExpressPayment.js +1 -1
  109. package/lib/cjs/components/payment_source/StripePayment.js +1 -1
  110. package/lib/cjs/components/payment_source/WireTransferPayment.js +1 -1
  111. package/lib/cjs/components/prices/Price.js +1 -1
  112. package/lib/cjs/components/prices/PricesContainer.js +1 -1
  113. package/lib/cjs/components/shipments/Shipment.js +1 -1
  114. package/lib/cjs/components/shipments/ShipmentField.js +1 -1
  115. package/lib/cjs/components/shipments/ShipmentsContainer.js +1 -1
  116. package/lib/cjs/components/shipments/ShipmentsCount.js +1 -1
  117. package/lib/cjs/components/shipping_methods/ShippingMethod.js +1 -1
  118. package/lib/cjs/components/shipping_methods/ShippingMethodName.js +1 -1
  119. package/lib/cjs/components/shipping_methods/ShippingMethodPrice.js +1 -1
  120. package/lib/cjs/components/shipping_methods/ShippingMethodRadioButton.js +1 -1
  121. package/lib/cjs/components/skus/AvailabilityContainer.js +1 -1
  122. package/lib/cjs/components/skus/AvailabilityTemplate.js +1 -1
  123. package/lib/cjs/components/skus/DeliveryLeadTime.js +1 -1
  124. package/lib/cjs/components/skus/SkuField.js +1 -1
  125. package/lib/cjs/components/skus/SkusContainer.js +1 -1
  126. package/lib/cjs/components/stock_transfers/StockTransferField.js +1 -1
  127. package/lib/cjs/components/utils/AddressCardsTemplate.js +1 -1
  128. package/lib/cjs/components/utils/BaseField.js +1 -1
  129. package/lib/cjs/components/utils/BaseInput.d.ts +3 -3
  130. package/lib/cjs/components/utils/BaseInput.js +1 -1
  131. package/lib/cjs/components/utils/BaseOrderPrice.js +1 -1
  132. package/lib/cjs/components/utils/BaseSelect.js +1 -1
  133. package/lib/cjs/components/utils/ErrorBoundary.js +1 -1
  134. package/lib/cjs/components/utils/GenericFieldComponent.js +1 -1
  135. package/lib/cjs/components/utils/Parent.js +1 -1
  136. package/lib/cjs/components/utils/PaymentCardsTemplate.js +1 -1
  137. package/lib/cjs/components/utils/PriceTemplate.js +1 -1
  138. package/lib/cjs/components/utils/getAllErrors.js +1 -1
  139. package/lib/cjs/context/BillingAddressFormContext.d.ts +2 -2
  140. package/lib/cjs/context/ExternalFunctionContext.js +1 -1
  141. package/lib/cjs/context/OrderContext.js +1 -1
  142. package/lib/cjs/hooks/useOrderContainer.js +1 -1
  143. package/lib/cjs/reducers/AddressReducer.js +1 -1
  144. package/lib/cjs/reducers/AvailabilityReducer.js +1 -1
  145. package/lib/cjs/reducers/BillingAddressReducer.js +1 -1
  146. package/lib/cjs/reducers/CustomerReducer.d.ts +5 -6
  147. package/lib/cjs/reducers/CustomerReducer.js +1 -1
  148. package/lib/cjs/reducers/GiftCardReducer.js +1 -1
  149. package/lib/cjs/reducers/InStockSubscriptionReducer.js +1 -1
  150. package/lib/cjs/reducers/LineItemReducer.js +1 -1
  151. package/lib/cjs/reducers/OrderReducer.js +1 -1
  152. package/lib/cjs/reducers/PaymentMethodReducer.js +1 -1
  153. package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
  154. package/lib/cjs/reducers/PriceReducer.js +1 -1
  155. package/lib/cjs/reducers/ShipmentReducer.js +1 -1
  156. package/lib/cjs/reducers/ShippingAddressReducer.js +1 -1
  157. package/lib/cjs/reducers/SkuListsReducer.js +1 -1
  158. package/lib/cjs/reducers/SkuReducer.js +1 -1
  159. package/lib/cjs/typings/index.js +1 -1
  160. package/lib/cjs/utils/addressesManager.js +1 -1
  161. package/lib/cjs/utils/adyen/manageGiftCard.js +1 -1
  162. package/lib/cjs/utils/baseReducer.js +1 -1
  163. package/lib/cjs/utils/countryStateCity.js +1 -1
  164. package/lib/cjs/utils/customMessages.js +1 -1
  165. package/lib/cjs/utils/expressPaymentHelper.js +1 -1
  166. package/lib/cjs/utils/getApplicationLink.js +1 -1
  167. package/lib/cjs/utils/getCardDetails.js +1 -1
  168. package/lib/cjs/utils/getCustomerIdByToken.js +1 -1
  169. package/lib/cjs/utils/getErrors.js +1 -1
  170. package/lib/cjs/utils/getPrices.js +1 -1
  171. package/lib/cjs/utils/getPublicIp.js +1 -1
  172. package/lib/cjs/utils/getSdk.js +1 -1
  173. package/lib/cjs/utils/hasSubscriptions.js +1 -1
  174. package/lib/cjs/utils/organization.js +1 -1
  175. package/lib/cjs/utils/promisify.js +1 -1
  176. package/lib/cjs/utils/shipments.js +1 -1
  177. package/lib/cjs/utils/snakeToCamelCase.js +1 -1
  178. package/lib/cjs/utils/stripe/retrievePaymentIntent.js +1 -1
  179. package/lib/cjs/utils/triggerAttributeHelper.js +1 -1
  180. package/lib/cjs/utils/updateOrderSubscriptionCustomerPaymentSource.js +1 -1
  181. package/lib/cjs/utils/validateFormFields.js +1 -1
  182. package/lib/esm/components/addresses/AddressInput.d.ts +4 -4
  183. package/lib/esm/components/addresses/AddressInput.js +1 -1
  184. package/lib/esm/components/addresses/BillingAddressForm.d.ts +4 -4
  185. package/lib/esm/components/addresses/BillingAddressForm.js +1 -1
  186. package/lib/esm/components/addresses/ShippingAddressForm.d.ts +4 -4
  187. package/lib/esm/components/addresses/ShippingAddressForm.js +1 -1
  188. package/lib/esm/components/customers/CustomerContainer.js +1 -1
  189. package/lib/esm/components/orders/OrderContainer.d.ts +1 -1
  190. package/lib/esm/components/orders/OrderContainer.js +1 -1
  191. package/lib/esm/components/orders/OrderList.js +1 -1
  192. package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
  193. package/lib/esm/components/payment_source/CheckoutComPayment.js +1 -1
  194. package/lib/esm/components/payment_source/StripePayment.js +1 -1
  195. package/lib/esm/components/utils/BaseInput.d.ts +3 -3
  196. package/lib/esm/context/BillingAddressFormContext.d.ts +2 -2
  197. package/lib/esm/reducers/AddressReducer.js +1 -1
  198. package/lib/esm/reducers/CustomerReducer.d.ts +5 -6
  199. package/lib/esm/reducers/CustomerReducer.js +1 -1
  200. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getErrors,exports.setErrors=setErrors;const tslib_1=require("tslib"),differenceBy_1=tslib_1.__importDefault(require("lodash/differenceBy"));function getErrors({error,resource,field,attributes}){var _a;return(_a=error?.errors)===null||_a===void 0?void 0:_a.map(e=>Object.assign(Object.assign(Object.assign(Object.assign({},e),{resource}),field!=null&&field!==""&&{field}),attributes!=null&&attributes))}function setErrors({currentErrors=[],newErrors=[],dispatch,filterBy="code"}){const errorsDifference=(0,differenceBy_1.default)(currentErrors,newErrors,filterBy),mergeErrors=currentErrors?.length===0?newErrors:errorsDifference,errors=[...currentErrors||[],...mergeErrors];return dispatch?.({type:"setErrors",payload:{errors}}),errors}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getErrors,exports.setErrors=setErrors;const tslib_1=require("tslib"),differenceBy_1=tslib_1.__importDefault(require("lodash/differenceBy"));function getErrors({error,resource,field,attributes}){return error?.errors?.map(e=>({...e,resource,...field!=null&&field!==""&&{field},...attributes!=null&&attributes}))}function setErrors({currentErrors=[],newErrors=[],dispatch,filterBy="code"}){const errorsDifference=(0,differenceBy_1.default)(currentErrors,newErrors,filterBy),mergeErrors=currentErrors?.length===0?newErrors:errorsDifference,errors=[...currentErrors||[],...mergeErrors];return dispatch?.({type:"setErrors",payload:{errors}}),errors}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPriceByCode=getPriceByCode,exports.getPricesComponent=getPricesComponent,exports.default=getPrices;const tslib_1=require("tslib"),react_1=require("react"),jsx_runtime_1=require("react/jsx-runtime"),lodash_1=require("lodash"),PriceTemplate_1=tslib_1.__importDefault(require("../components/utils/PriceTemplate"));function getPriceByCode(skuPrices,code=""){return code?(0,lodash_1.first)(skuPrices.filter(p=>p.currency_code===code)):(0,lodash_1.first)(skuPrices)}function getPricesComponent(skuPrices,props){return(0,lodash_1.isEmpty)(skuPrices)?(0,jsx_runtime_1.jsx)(PriceTemplate_1.default,Object.assign({},props)):skuPrices.map((p,k)=>{const showCompare=typeof props.showCompare>"u"&&p?.compare_at_amount_cents!=null&&p?.compare_at_amount_cents>p?.amount_cents||props.showCompare;return(0,react_1.createElement)(PriceTemplate_1.default,Object.assign({},props,{key:k,showCompare,formattedAmount:p.formatted_amount,formattedCompare:p.formatted_compare_at_amount,skuCode:p.sku_code}))})}function getPrices(prices){const obj={};return(0,lodash_1.isArray)(prices)&&prices.forEach(p=>{var _a;const sku=(_a=p?.sku_code)!==null&&_a!==void 0?_a:"";(0,lodash_1.has)(obj,sku)?obj[sku].push(p):obj[sku]=[p]}),obj}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPriceByCode=getPriceByCode,exports.getPricesComponent=getPricesComponent,exports.default=getPrices;const tslib_1=require("tslib"),react_1=require("react"),jsx_runtime_1=require("react/jsx-runtime"),lodash_1=require("lodash"),PriceTemplate_1=tslib_1.__importDefault(require("../components/utils/PriceTemplate"));function getPriceByCode(skuPrices,code=""){return code?(0,lodash_1.first)(skuPrices.filter(p=>p.currency_code===code)):(0,lodash_1.first)(skuPrices)}function getPricesComponent(skuPrices,props){return(0,lodash_1.isEmpty)(skuPrices)?(0,jsx_runtime_1.jsx)(PriceTemplate_1.default,{...props}):skuPrices.map((p,k)=>{const showCompare=typeof props.showCompare>"u"&&p?.compare_at_amount_cents!=null&&p?.compare_at_amount_cents>p?.amount_cents||props.showCompare;return(0,react_1.createElement)(PriceTemplate_1.default,{...props,key:k,showCompare,formattedAmount:p.formatted_amount,formattedCompare:p.formatted_compare_at_amount,skuCode:p.sku_code})})}function getPrices(prices){const obj={};return(0,lodash_1.isArray)(prices)&&prices.forEach(p=>{const sku=p?.sku_code??"";(0,lodash_1.has)(obj,sku)?obj[sku].push(p):obj[sku]=[p]}),obj}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPublicIP=getPublicIP;const tslib_1=require("tslib");function getPublicIP(){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{const response=yield fetch("https://api.ipify.org?format=json");if(!response.ok)throw new Error("Network response was not ok");return(yield response.json()).ip}catch(error){return console.error("Error fetching public IP address:",error),""}})}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPublicIP=getPublicIP;async function getPublicIP(){try{const response=await fetch("https://api.ipify.org?format=json");if(!response.ok)throw new Error("Network response was not ok");return(await response.json()).ip}catch(error){return console.error("Error fetching public IP address:",error),""}}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getSdk;const tslib_1=require("tslib"),organization_1=require("./organization"),sdk_1=tslib_1.__importDefault(require("@commercelayer/sdk"));function getSdk({endpoint,accessToken}){if(accessToken==null||endpoint==null)throw new Error("accessToken and endpoint are required parameters");const org=(0,organization_1.getOrganizationSlug)(endpoint);return(0,sdk_1.default)(Object.assign({accessToken},org))}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getSdk;const tslib_1=require("tslib"),organization_1=require("./organization"),sdk_1=tslib_1.__importDefault(require("@commercelayer/sdk"));function getSdk({endpoint,accessToken}){if(accessToken==null||endpoint==null)throw new Error("accessToken and endpoint are required parameters");const org=(0,organization_1.getOrganizationSlug)(endpoint);return(0,sdk_1.default)({accessToken,...org})}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.hasSubscriptions=hasSubscriptions;function hasSubscriptions(order){var _a;return((_a=order.line_items)===null||_a===void 0?void 0:_a.some(item=>{var _a2;return item.frequency&&((_a2=item.frequency)===null||_a2===void 0?void 0:_a2.length)>0}))||order?.subscription_created_at!=null||!1}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.hasSubscriptions=hasSubscriptions;function hasSubscriptions(order){return order.line_items?.some(item=>item.frequency&&item.frequency?.length>0)||order?.subscription_created_at!=null||!1}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOrganizationSlug=getOrganizationSlug,exports.getOrganizationConfig=getOrganizationConfig,exports.useOrganizationConfig=useOrganizationConfig;const tslib_1=require("tslib"),react_1=require("react"),getDomain_1=require("./getDomain"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),organization_config_1=require("@commercelayer/organization-config"),jwt_1=require("./jwt");function getOrganizationSlug(endpoint){const org={organization:"",domain:"commercelayer.io"},{domain,slug}=(0,getDomain_1.getDomain)(endpoint);return{organization:slug,domain:domain||org.domain}}function getOrganizationConfig(config){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a;const{market}=(0,jwt_1.jwt)(config.accessToken),organization=yield(0,getSdk_1.default)(config).organization.retrieve({fields:{organizations:["id","config"]}});return(0,organization_config_1.getMfeConfig)({jsonConfig:(_a=organization.config)!==null&&_a!==void 0?_a:{},market:`market:id:${market.id.join(",")}`,params:config.params})})}function useOrganizationConfig({accessToken,endpoint,params}){const[organizationConfig,setOrganizationConfig]=(0,react_1.useState)(null);return(0,react_1.useEffect)(()=>{accessToken==null||endpoint==null||getOrganizationConfig({accessToken,endpoint,params}).then(config=>{setOrganizationConfig(config)})},[accessToken,endpoint]),organizationConfig}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOrganizationSlug=getOrganizationSlug,exports.getOrganizationConfig=getOrganizationConfig,exports.useOrganizationConfig=useOrganizationConfig;const tslib_1=require("tslib"),react_1=require("react"),getDomain_1=require("./getDomain"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),organization_config_1=require("@commercelayer/organization-config"),jwt_1=require("./jwt");function getOrganizationSlug(endpoint){const org={organization:"",domain:"commercelayer.io"},{domain,slug}=(0,getDomain_1.getDomain)(endpoint);return{organization:slug,domain:domain||org.domain}}async function getOrganizationConfig(config){const{market}=(0,jwt_1.jwt)(config.accessToken),organization=await(0,getSdk_1.default)(config).organization.retrieve({fields:{organizations:["id","config"]}});return(0,organization_config_1.getMfeConfig)({jsonConfig:organization.config??{},market:`market:id:${market.id.join(",")}`,params:config.params})}function useOrganizationConfig({accessToken,endpoint,params}){const[organizationConfig,setOrganizationConfig]=(0,react_1.useState)(null);return(0,react_1.useEffect)(()=>{accessToken==null||endpoint==null||getOrganizationConfig({accessToken,endpoint,params}).then(config=>{setOrganizationConfig(config)})},[accessToken,endpoint]),organizationConfig}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=promisify;const tslib_1=require("tslib"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction"));function promisify(cb,params){return tslib_1.__awaiter(this,void 0,void 0,function*(){return yield new Promise((resolve,reject)=>{params?cb(params,(err,res)=>{err&&reject(err),resolve(res)}):(0,isFunction_1.default)(cb?.tokenize)?cb?.tokenize((err,payload)=>{err&&reject(err),resolve(payload)}):cb((err,res)=>{err&&reject(err),resolve(res)})})})}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=promisify;const tslib_1=require("tslib"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction"));async function promisify(cb,params){return await new Promise((resolve,reject)=>{params?cb(params,(err,res)=>{err&&reject(err),resolve(res)}):(0,isFunction_1.default)(cb?.tokenize)?cb?.tokenize((err,payload)=>{err&&reject(err),resolve(payload)}):cb((err,res)=>{err&&reject(err),resolve(res)})})}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shipmentsFilled=shipmentsFilled,exports.isDoNotShip=isDoNotShip;const tslib_1=require("tslib"),compact_1=tslib_1.__importDefault(require("lodash/compact")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty"));function shipmentsFilled(shipments){const filled=(0,compact_1.default)(shipments.filter(shipment=>!(0,isEmpty_1.default)(shipment.shipping_method)));return!(0,isEmpty_1.default)(filled)}function isDoNotShip(lineItems){const itemDoNotShip=[],items=lineItems?lineItems.filter(({item_type})=>item_type==="skus").map(lineItem=>{var _a;return!((_a=lineItem.item)===null||_a===void 0)&&_a.do_not_ship&&itemDoNotShip.push(!0),lineItem}):[];return itemDoNotShip.length>0&&itemDoNotShip.length===items.length}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shipmentsFilled=shipmentsFilled,exports.isDoNotShip=isDoNotShip;const tslib_1=require("tslib"),compact_1=tslib_1.__importDefault(require("lodash/compact")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty"));function shipmentsFilled(shipments){const filled=(0,compact_1.default)(shipments.filter(shipment=>!(0,isEmpty_1.default)(shipment.shipping_method)));return!(0,isEmpty_1.default)(filled)}function isDoNotShip(lineItems){const itemDoNotShip=[],items=lineItems?lineItems.filter(({item_type})=>item_type==="skus").map(lineItem=>(lineItem.item?.do_not_ship&&itemDoNotShip.push(!0),lineItem)):[];return itemDoNotShip.length>0&&itemDoNotShip.length===items.length}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.snakeToCamelCase=snakeToCamelCase;function snakeToCamelCase(value){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l;const words=value.toLowerCase().split("_"),first=(_a=words[0])!==null&&_a!==void 0?_a:"",secondLetter=(_d=(_c=(_b=words[1])===null||_b===void 0?void 0:_b[0])===null||_c===void 0?void 0:_c.toUpperCase())!==null&&_d!==void 0?_d:"",second=(_f=(_e=words[1])===null||_e===void 0?void 0:_e.substring(1))!==null&&_f!==void 0?_f:"",thirdLetter=(_j=(_h=(_g=words[2])===null||_g===void 0?void 0:_g[0])===null||_h===void 0?void 0:_h.toUpperCase())!==null&&_j!==void 0?_j:"",third=(_l=(_k=words[2])===null||_k===void 0?void 0:_k.substring(1))!==null&&_l!==void 0?_l:"";return`${first}${secondLetter}${second}${thirdLetter}${third}`}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.snakeToCamelCase=snakeToCamelCase;function snakeToCamelCase(value){const words=value.toLowerCase().split("_"),first=words[0]??"",secondLetter=words[1]?.[0]?.toUpperCase()??"",second=words[1]?.substring(1)??"",thirdLetter=words[2]?.[0]?.toUpperCase()??"",third=words[2]?.substring(1)??"";return`${first}${secondLetter}${second}${thirdLetter}${third}`}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkPaymentIntent=checkPaymentIntent;const tslib_1=require("tslib"),stripe_js_1=require("@stripe/stripe-js");function retrievePaymentIntent(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({publicApiKey,paymentIntentClientSecret}){const stripe=yield(0,stripe_js_1.loadStripe)(publicApiKey);try{return yield stripe?.retrievePaymentIntent(paymentIntentClientSecret)}catch(error){return console.error("Error retrieving payment intent:",error),null}})}function paymentIntentValidation({paymentIntent}){switch(paymentIntent?.status){case"succeeded":case"requires_capture":return"valid";case"processing":return"processing";case"requires_payment_method":return"invalid";default:return"invalid"}}function checkPaymentIntent(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({publicApiKey,paymentIntentClientSecret}){const paymentIntentResult=yield retrievePaymentIntent({publicApiKey,paymentIntentClientSecret});if(!paymentIntentResult)return{status:"invalid",message:"Payment intent not found"};const paymentIntent=paymentIntentResult.paymentIntent,error=paymentIntent?.last_payment_error,status=paymentIntentValidation({paymentIntent});return{status,message:status==="invalid"&&error?.message!=null?error.message:""}})}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkPaymentIntent=checkPaymentIntent;const stripe_js_1=require("@stripe/stripe-js");async function retrievePaymentIntent({publicApiKey,paymentIntentClientSecret}){const stripe=await(0,stripe_js_1.loadStripe)(publicApiKey);try{return await stripe?.retrievePaymentIntent(paymentIntentClientSecret)}catch(error){return console.error("Error retrieving payment intent:",error),null}}function paymentIntentValidation({paymentIntent}){switch(paymentIntent?.status){case"succeeded":case"requires_capture":return"valid";case"processing":return"processing";case"requires_payment_method":return"invalid";default:return"invalid"}}async function checkPaymentIntent({publicApiKey,paymentIntentClientSecret}){const paymentIntentResult=await retrievePaymentIntent({publicApiKey,paymentIntentClientSecret});if(!paymentIntentResult)return{status:"invalid",message:"Payment intent not found"};const paymentIntent=paymentIntentResult.paymentIntent,error=paymentIntent?.last_payment_error,status=paymentIntentValidation({paymentIntent});return{status,message:status==="invalid"&&error?.message!=null?error.message:""}}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.triggerAttributeHelper=triggerAttributeHelper;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk"));function triggerAttributeHelper(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,id,attribute,resource}){return yield(0,getSdk_1.default)(config)[resource].update({id,[attribute]:!0})})}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.triggerAttributeHelper=triggerAttributeHelper;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk"));async function triggerAttributeHelper({config,id,attribute,resource}){return await(0,getSdk_1.default)(config)[resource].update({id,[attribute]:!0})}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.updateOrderSubscriptionCustomerPaymentSource=updateOrderSubscriptionCustomerPaymentSource;function updateOrderSubscriptionCustomerPaymentSource(order,paymentType,sdk){order.subscription_created_at!=null&&sdk.orders.retrieve(order.id,{include:["order_subscription","payment_source"]}).then(order2=>{if(order2.payment_source_details!=null&&order2.order_subscription!=null){const paymentSourceToken=getPaymentSourceToken(order2,paymentType);paymentSourceToken!=null&&sdk.customer_payment_sources.list({filters:{payment_source_token_eq:paymentSourceToken}}).then(customerPaymentSources2=>{var _a;if(customerPaymentSources2.length>0&&order2.order_subscription!=null){const customerPaymentSource=customerPaymentSources2[0];customerPaymentSource!=null&&sdk.order_subscriptions.update({id:(_a=order2.order_subscription)===null||_a===void 0?void 0:_a.id,customer_payment_source:sdk.customer_payment_sources.relationship(customerPaymentSource?.id)})}})}})}function getPaymentSourceToken(order,paymentType){var _a,_b;switch(paymentType){case"braintree_payments":return order.payment_source!=null&&order.payment_source.type==="braintree_payments"&&order.payment_source.options!=null?order.payment_source.options.payment_method_token:void 0;default:return(_b=(_a=order?.payment_source_details)===null||_a===void 0?void 0:_a.payment_method_id)!==null&&_b!==void 0?_b:void 0}}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.updateOrderSubscriptionCustomerPaymentSource=updateOrderSubscriptionCustomerPaymentSource;function updateOrderSubscriptionCustomerPaymentSource(order,paymentType,sdk){order.subscription_created_at!=null&&sdk.orders.retrieve(order.id,{include:["order_subscription","payment_source"]}).then(order2=>{if(order2.payment_source_details!=null&&order2.order_subscription!=null){const paymentSourceToken=getPaymentSourceToken(order2,paymentType);paymentSourceToken!=null&&sdk.customer_payment_sources.list({filters:{payment_source_token_eq:paymentSourceToken}}).then(customerPaymentSources2=>{if(customerPaymentSources2.length>0&&order2.order_subscription!=null){const customerPaymentSource=customerPaymentSources2[0];customerPaymentSource!=null&&sdk.order_subscriptions.update({id:order2.order_subscription?.id,customer_payment_source:sdk.customer_payment_sources.relationship(customerPaymentSource?.id)})}})}})}function getPaymentSourceToken(order,paymentType){switch(paymentType){case"braintree_payments":return order.payment_source!=null&&order.payment_source.type==="braintree_payments"&&order.payment_source.options!=null?order.payment_source.options.payment_method_token:void 0;default:return order?.payment_source_details?.payment_method_id??void 0}}
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateValue=void 0,exports.fieldsExist=fieldsExist,exports.businessMandatoryField=businessMandatoryField;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),isString_1=tslib_1.__importDefault(require("lodash/isString")),keys_1=tslib_1.__importDefault(require("lodash/keys")),map_1=tslib_1.__importDefault(require("lodash/map")),without_1=tslib_1.__importDefault(require("lodash/without")),AddressReducer_1=require("../reducers/AddressReducer"),EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,validateValue=(val,name,type,resource)=>val?type==="email"&&(0,isString_1.default)(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};exports.validateValue=validateValue;const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return(0,map_1.default)(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=(0,exports.validateValue)(val,v.name,v.type,resourceType);(0,isEmpty_1.default)(error)||errors.push(error),values=Object.assign(Object.assign({},values),{[`${v.name}`]:val})}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?Object.assign(Object.assign({},values),{metadata:Object.assign(Object.assign({},values.metadata),{[`${v.name}`]:val})}):Object.assign(Object.assign({},values),{[`${v.name}`]:val}))}),{errors,values}};function fieldsExist(address,schema=AddressReducer_1.addressFields){if(!address.business){const required2=(0,without_1.default)(schema,"line_2","company","state_code"),validAddress2=(0,keys_1.default)(address).filter(k=>required2.includes(k));return required2.length>validAddress2.length}const required=(0,without_1.default)(schema,"first_name","last_name","line_2","state_code"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}exports.default=validateFormFields;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateValue=void 0,exports.fieldsExist=fieldsExist,exports.businessMandatoryField=businessMandatoryField;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),isString_1=tslib_1.__importDefault(require("lodash/isString")),keys_1=tslib_1.__importDefault(require("lodash/keys")),map_1=tslib_1.__importDefault(require("lodash/map")),without_1=tslib_1.__importDefault(require("lodash/without")),AddressReducer_1=require("../reducers/AddressReducer"),EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,validateValue=(val,name,type,resource)=>val?type==="email"&&(0,isString_1.default)(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};exports.validateValue=validateValue;const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return(0,map_1.default)(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=(0,exports.validateValue)(val,v.name,v.type,resourceType);(0,isEmpty_1.default)(error)||errors.push(error),values={...values,[`${v.name}`]:val}}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?{...values,metadata:{...values.metadata,[`${v.name}`]:val}}:{...values,[`${v.name}`]:val})}),{errors,values}};function fieldsExist(address,schema=AddressReducer_1.addressFields){if(!address.business){const required2=(0,without_1.default)(schema,"line_2","company","state_code"),validAddress2=(0,keys_1.default)(address).filter(k=>required2.includes(k));return required2.length>validAddress2.length}const required=(0,without_1.default)(schema,"first_name","last_name","line_2","state_code"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}exports.default=validateFormFields;
@@ -1,6 +1,6 @@
1
- import { type JSX } from 'react';
2
- import type { BaseInputComponentProps, AddressInputName } from '../../typings/index';
3
- import { type AddressValuesKeys } from '../../context/BillingAddressFormContext';
1
+ import { type JSX } from "react";
2
+ import { type AddressValuesKeys } from "../../context/BillingAddressFormContext";
3
+ import type { AddressInputName, BaseInputComponentProps } from "../../typings/index";
4
4
  type Props = {
5
5
  /**
6
6
  * The name of the input.
@@ -11,7 +11,7 @@ type Props = {
11
11
  * Used to add a custom validation rule. Accept a regex as param.
12
12
  */
13
13
  pattern?: RegExp;
14
- } & Omit<BaseInputComponentProps, 'name'> & Omit<JSX.IntrinsicElements['input'], 'pattern'> & Omit<JSX.IntrinsicElements['textarea'], 'children' | 'pattern'>;
14
+ } & Omit<BaseInputComponentProps, "name"> & Omit<JSX.IntrinsicElements["input"], "pattern"> & Omit<JSX.IntrinsicElements["textarea"], "children" | "pattern">;
15
15
  /**
16
16
  * The AddressInput component creates a form `input` related to a particular address attribute.
17
17
  *
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo}from"react";import BaseInput from"../utils/BaseInput";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import{businessMandatoryField}from"../../utils/validateFormFields";import CustomerAddressFormContext from"../../context/CustomerAddressFormContext";export function AddressInput(props){const{placeholder="",required,value,className,...p}=props,billingAddress=useContext(BillingAddressFormContext),shippingAddress=useContext(ShippingAddressFormContext),customerAddress=useContext(CustomerAddressFormContext);useEffect(()=>{value&&billingAddress?.setValue&&billingAddress.setValue(p.name,value),value&&shippingAddress?.setValue&&shippingAddress.setValue(p.name,value),value&&customerAddress?.setValue&&customerAddress.setValue(p.name,value)},[value]);const hasError=useMemo(()=>!!(billingAddress?.errors?.[p.name]?.error||shippingAddress?.errors?.[p.name]?.error||customerAddress?.errors?.[p.name]?.error),[value,billingAddress?.errors,shippingAddress?.errors,customerAddress?.errors]),mandatoryField=billingAddress?.isBusiness?businessMandatoryField(p.name,billingAddress.isBusiness):businessMandatoryField(p.name,shippingAddress.isBusiness),reqField=required!==void 0?required:mandatoryField,errorClassName=billingAddress?.errorClassName||shippingAddress?.errorClassName,classNameComputed=`${className||""} ${hasError&&errorClassName?errorClassName:""}`;return p.name==="billing_address_billing_info"&&billingAddress.requiresBillingInfo===!1&&required===void 0||p.name==="shipping_address_billing_info"&&shippingAddress.requiresBillingInfo===!1&&required===void 0?null:_jsx(BaseInput,{ref:billingAddress?.validation||shippingAddress?.validation||customerAddress?.validation,className:classNameComputed,required:reqField,placeholder,defaultValue:value,...p})}export default AddressInput;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo}from"react";import BaseInput from"../utils/BaseInput";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import CustomerAddressFormContext from"../../context/CustomerAddressFormContext";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import{businessMandatoryField}from"../../utils/validateFormFields";export function AddressInput(props){const{placeholder="",required,value,className,...p}=props,billingAddress=useContext(BillingAddressFormContext),shippingAddress=useContext(ShippingAddressFormContext),customerAddress=useContext(CustomerAddressFormContext);useEffect(()=>{value&&billingAddress?.setValue&&billingAddress.setValue(p.name,value),value&&shippingAddress?.setValue&&shippingAddress.setValue(p.name,value),value&&customerAddress?.setValue&&customerAddress.setValue(p.name,value)},[value]);const hasError=useMemo(()=>!!(billingAddress?.errors?.[p.name]?.error||shippingAddress?.errors?.[p.name]?.error||customerAddress?.errors?.[p.name]?.error),[value,billingAddress?.errors,shippingAddress?.errors,customerAddress?.errors]),mandatoryField=billingAddress?.isBusiness?businessMandatoryField(p.name,billingAddress.isBusiness):businessMandatoryField(p.name,shippingAddress.isBusiness),reqField=required!==void 0?required:mandatoryField,errorClassName=billingAddress?.errorClassName||shippingAddress?.errorClassName,classNameComputed=`${className||""} ${hasError&&errorClassName?errorClassName:""}`;return p.name==="billing_address_billing_info"&&billingAddress.requiresBillingInfo===!1&&required===void 0||p.name==="shipping_address_billing_info"&&shippingAddress.requiresBillingInfo===!1&&required===void 0?null:_jsx(BaseInput,{ref:billingAddress?.validation||shippingAddress?.validation||customerAddress?.validation,className:classNameComputed,required:reqField,placeholder,defaultValue:value,...p})}export default AddressInput;
@@ -1,5 +1,5 @@
1
- import { type ReactNode, type JSX } from 'react';
2
- import type { CustomFieldMessageError } from '../../reducers/AddressReducer';
1
+ import { type JSX, type ReactNode } from "react";
2
+ import type { CustomFieldMessageError } from "../../reducers/AddressReducer";
3
3
  type Props = {
4
4
  children: ReactNode;
5
5
  /**
@@ -10,12 +10,12 @@ type Props = {
10
10
  * Define children input and select classnames assigned in case of validation error.
11
11
  */
12
12
  errorClassName?: string;
13
- fieldEvent?: 'blur' | 'change';
13
+ fieldEvent?: "blur" | "change";
14
14
  /**
15
15
  * Callback to customize the error message for a specific field. Called for each error in the form.
16
16
  */
17
17
  customFieldMessageError?: CustomFieldMessageError;
18
- } & Omit<JSX.IntrinsicElements['form'], 'onSubmit'>;
18
+ } & Omit<JSX.IntrinsicElements["form"], "onSubmit">;
19
19
  /**
20
20
  * Form container for creating or editing an order related billing address or a customer address, depending on the context in use.
21
21
  *
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext from"../../context/AddressContext";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import OrderContext from"../../context/OrderContext";import{getSaveBillingAddressToAddressBook}from"../../utils/localStorage";export function BillingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,customFieldMessageError,fieldEvent="change",...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm,setError:setErrorForm}=useRapidForm({fieldEvent}),{setAddressErrors,setAddress,isBusiness}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,order,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),customFieldMessageError!=null&&Object.keys(values).length>0){for(const name in values)if(Object.prototype.hasOwnProperty.call(values,name)){const field=values[name],fieldName=field.name,value=field.value,inError=errors[fieldName]!=null;if(customFieldMessageError!=null&&fieldName!=null&&value!=null){values[fieldName.replace("shipping_address_","")]=value;const customMessage=customFieldMessageError({field:fieldName,value,values});if(customMessage!=null)if(typeof customMessage=="string")if(inError){const errorMsg=errors[fieldName]?.message;errorMsg!=null&&errorMsg!==customMessage&&(errors[fieldName].message=customMessage)}else setErrorForm({name:fieldName,code:"VALIDATION_ERROR",message:customMessage});else customMessage.forEach(element=>{const{field:field2,value:value2,isValid,message}=element,fieldInError=errors[field2]!=null;if(isValid)fieldInError&&(delete errors[field2],setValueForm(field2,value2??""));else if(fieldInError){const errorMsg=errors[field2]?.message;errorMsg!=null&&errorMsg!==message&&(errors[field2].message=message,setValueForm(field2,value2??""))}else setErrorForm({name:field2,code:"VALIDATION_ERROR",message})})}}}if(errors!=null&&Object.keys(errors).length>0){const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;formErrors.push({code,message:message??"",resource:"billing_address",field:fieldName})}setAddressErrors(formErrors,"billing_address")}else if(values&&Object.keys(values).length>0){setAddressErrors([],"billing_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("billing_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"billing_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"billing_address"})}const checkboxChecked=ref.current?.querySelector('[name="billing_address_save_to_customer_book"]')?.checked||getSaveBillingAddressToAddressBook();reset&&(values!=null&&Object.keys(values).length>0||errors!=null&&Object.keys(errors).length>0||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"billing_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"billing_address"),setAddress({values:{},resource:"billing_address"})))},[errors,values,reset,include,includeLoaded,isBusiness]);const providerValues={isBusiness,values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("billing_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"billing_address"})},errorClassName,requiresBillingInfo:order?.requires_billing_info||!1,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(BillingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default BillingAddressForm;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import AddressesContext from"../../context/AddressContext";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import OrderContext from"../../context/OrderContext";import{getSaveBillingAddressToAddressBook}from"../../utils/localStorage";export function BillingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,customFieldMessageError,fieldEvent="change",...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm,setError:setErrorForm}=useRapidForm({fieldEvent}),{setAddressErrors,setAddress,isBusiness}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,order,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),customFieldMessageError!=null&&Object.keys(values).length>0){for(const name in values)if(Object.hasOwn(values,name)){const field=values[name],fieldName=field.name,value=field.value,inError=errors[fieldName]!=null;if(customFieldMessageError!=null&&fieldName!=null&&value!=null){values[fieldName.replace("shipping_address_","")]=value;const customMessage=customFieldMessageError({field:fieldName,value,values});if(customMessage!=null)if(typeof customMessage=="string")if(inError){const errorMsg=errors[fieldName]?.message;errorMsg!=null&&errorMsg!==customMessage&&(errors[fieldName].message=customMessage)}else setErrorForm({name:fieldName,code:"VALIDATION_ERROR",message:customMessage});else customMessage.forEach(element=>{const{field:field2,value:value2,isValid,message}=element,fieldInError=errors[field2]!=null;if(isValid)fieldInError&&(delete errors[field2],setValueForm(field2,value2??""));else if(fieldInError){const errorMsg=errors[field2]?.message;errorMsg!=null&&errorMsg!==message&&(errors[field2].message=message,setValueForm(field2,value2??""))}else setErrorForm({name:field2,code:"VALIDATION_ERROR",message})})}}}if(errors!=null&&Object.keys(errors).length>0){const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;formErrors.push({code,message:message??"",resource:"billing_address",field:fieldName})}setAddressErrors(formErrors,"billing_address")}else if(values&&Object.keys(values).length>0){setAddressErrors([],"billing_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("billing_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"billing_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"billing_address"})}const checkboxChecked=ref.current?.querySelector('[name="billing_address_save_to_customer_book"]')?.checked||getSaveBillingAddressToAddressBook();checkboxChecked&&(ref.current?.querySelector('[name="billing_address_save_to_customer_book"]')?.setAttribute("checked","true"),saveAddressToCustomerAddressBook({type:"billing_address",value:!0})),reset&&(values!=null&&Object.keys(values).length>0||errors!=null&&Object.keys(errors).length>0||checkboxChecked)&&(saveAddressToCustomerAddressBook&&(console.log("Unchecking billing address save to customer book"),saveAddressToCustomerAddressBook({type:"billing_address",value:!1})),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"billing_address"),setAddress({values:{},resource:"billing_address"})))},[errors,values,reset,include,includeLoaded,isBusiness]);const providerValues={isBusiness,values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("billing_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"billing_address"})},errorClassName,requiresBillingInfo:order?.requires_billing_info||!1,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(BillingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default BillingAddressForm;
@@ -1,10 +1,10 @@
1
- import { type ReactNode, type JSX } from 'react';
2
- import type { CustomFieldMessageError } from '../../reducers/AddressReducer';
3
- interface Props extends Omit<JSX.IntrinsicElements['form'], 'onSubmit'> {
1
+ import { type JSX, type ReactNode } from "react";
2
+ import type { CustomFieldMessageError } from "../../reducers/AddressReducer";
3
+ interface Props extends Omit<JSX.IntrinsicElements["form"], "onSubmit"> {
4
4
  children: ReactNode;
5
5
  reset?: boolean;
6
6
  errorClassName?: string;
7
- fieldEvent?: 'blur' | 'change';
7
+ fieldEvent?: "blur" | "change";
8
8
  /**
9
9
  * Callback to customize the error message for a specific field. Called for each error in the form.
10
10
  */
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext from"../../context/AddressContext";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import OrderContext from"../../context/OrderContext";import{getSaveShippingAddressToAddressBook}from"../../utils/localStorage";export function ShippingAddressForm(props){const{children,errorClassName,autoComplete="on",fieldEvent="change",reset=!1,customFieldMessageError,...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm,setError:setErrorForm}=useRapidForm({fieldEvent}),{setAddressErrors,setAddress,shipToDifferentAddress,isBusiness,invertAddresses}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address"}),customFieldMessageError!=null&&Object.keys(values).length>0){for(const name in values)if(Object.prototype.hasOwnProperty.call(values,name)){const field=values[name],fieldName=field.name,value=field.value,inError=errors[fieldName]!=null;if(customFieldMessageError!=null&&fieldName!=null&&value!=null){values[fieldName.replace("shipping_address_","")]=value;const customMessage=customFieldMessageError({field:fieldName,value,values});if(customMessage!=null)if(typeof customMessage=="string")if(inError){const errorMsg=errors[fieldName]?.message;errorMsg!=null&&errorMsg!==customMessage&&(errors[fieldName].message=customMessage)}else setErrorForm({name:fieldName,code:"VALIDATION_ERROR",message:customMessage});else customMessage.forEach(element=>{const{field:field2,value:value2,isValid,message}=element,fieldInError=errors[field2]!=null;if(isValid)fieldInError&&(delete errors[field2],setValueForm(field2,value2??""));else if(fieldInError){const errorMsg=errors[field2]?.message;errorMsg!=null&&errorMsg!==message&&(errors[field2].message=message,setValueForm(field2,value2??""))}else setErrorForm({name:field2,code:"VALIDATION_ERROR",message})})}}}if(errors!=null&&Object.keys(errors).length>0){const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;formErrors.push({code,message:message??"",resource:"shipping_address",field:fieldName})}(shipToDifferentAddress||invertAddresses)&&setAddressErrors(formErrors,"shipping_address")}else if(values&&Object.keys(values).length>0&&(shipToDifferentAddress||invertAddresses)){setAddressErrors([],"shipping_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("shipping_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"shipping_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})}const checkboxChecked=ref.current?.querySelector('[name="shipping_address_save_to_customer_book"]')?.checked||getSaveShippingAddressToAddressBook();reset&&(values!=null&&Object.keys(values).length>0||errors!=null&&Object.keys(errors).length>0||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"shipping_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"shipping_address"),setAddress({values:{},resource:"shipping_address"})))},[values,errors,shipToDifferentAddress,reset,include,includeLoaded,isBusiness]);const providerValues={values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("shipping_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})},errorClassName,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(ShippingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default ShippingAddressForm;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import AddressesContext from"../../context/AddressContext";import OrderContext from"../../context/OrderContext";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import{getSaveShippingAddressToAddressBook}from"../../utils/localStorage";export function ShippingAddressForm(props){const{children,errorClassName,autoComplete="on",fieldEvent="change",reset=!1,customFieldMessageError,...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm,setError:setErrorForm}=useRapidForm({fieldEvent}),{setAddressErrors,setAddress,shipToDifferentAddress,isBusiness,invertAddresses}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address"}),customFieldMessageError!=null&&Object.keys(values).length>0){for(const name in values)if(Object.hasOwn(values,name)){const field=values[name],fieldName=field.name,value=field.value,inError=errors[fieldName]!=null;if(customFieldMessageError!=null&&fieldName!=null&&value!=null){values[fieldName.replace("shipping_address_","")]=value;const customMessage=customFieldMessageError({field:fieldName,value,values});if(customMessage!=null)if(typeof customMessage=="string")if(inError){const errorMsg=errors[fieldName]?.message;errorMsg!=null&&errorMsg!==customMessage&&(errors[fieldName].message=customMessage)}else setErrorForm({name:fieldName,code:"VALIDATION_ERROR",message:customMessage});else customMessage.forEach(element=>{const{field:field2,value:value2,isValid,message}=element,fieldInError=errors[field2]!=null;if(isValid)fieldInError&&(delete errors[field2],setValueForm(field2,value2??""));else if(fieldInError){const errorMsg=errors[field2]?.message;errorMsg!=null&&errorMsg!==message&&(errors[field2].message=message,setValueForm(field2,value2??""))}else setErrorForm({name:field2,code:"VALIDATION_ERROR",message})})}}}if(errors!=null&&Object.keys(errors).length>0){const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;formErrors.push({code,message:message??"",resource:"shipping_address",field:fieldName})}(shipToDifferentAddress||invertAddresses)&&setAddressErrors(formErrors,"shipping_address")}else if(values&&Object.keys(values).length>0&&(shipToDifferentAddress||invertAddresses)){setAddressErrors([],"shipping_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("shipping_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"shipping_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})}const checkboxChecked=ref.current?.querySelector('[name="shipping_address_save_to_customer_book"]')?.checked||getSaveShippingAddressToAddressBook();checkboxChecked&&ref.current?.querySelector('[name="shipping_address_save_to_customer_book"]')?.setAttribute("checked","true"),reset&&(values!=null&&Object.keys(values).length>0||errors!=null&&Object.keys(errors).length>0||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"shipping_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"shipping_address"),setAddress({values:{},resource:"shipping_address"})))},[values,errors,shipToDifferentAddress,reset,include,includeLoaded,isBusiness]);const providerValues={values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("shipping_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})},errorClassName,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(ShippingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default ShippingAddressForm;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&getCustomerPayments({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize:pageSize2,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&getCustomerPayments({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
@@ -1,6 +1,6 @@
1
+ import type { Order, OrderCreate } from "@commercelayer/sdk";
1
2
  import { type JSX } from "react";
2
3
  import type { BaseMetadataObject } from "../../typings/index";
3
- import type { OrderCreate, Order } from "@commercelayer/sdk";
4
4
  import type { DefaultChildrenType } from "../../typings/globals";
5
5
  interface Props {
6
6
  children: DefaultChildrenType;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart,paymentSourceRequest}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,manageAdyenGiftCard,paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo,useReducer,useState}from"react";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import orderReducer,{addToCart,createOrder,getApiOrder,orderInitialState,paymentSourceRequest,setOrder,setOrderErrors,updateOrder}from"../../reducers/OrderReducer";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,manageAdyenGiftCard,paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useReactTable,getCoreRowModel,getPaginationRowModel,getSortedRowModel,flexRender}from"@tanstack/react-table";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),[sorting,setSorting]=useState(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=useState({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=useContext(CustomerContext),defaultSdkSorting=sortBy.length&&sortBy[0]!=null?{[sortBy[0].id]:sortBy[0].desc?"desc":"asc"}:void 0;useEffect(()=>{const sdkSorting=sorting.length&&sorting[0]!=null?{[sorting[0].id]:sorting[0].desc?"desc":"asc"}:defaultSdkSorting;type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,id})},[pageIndex,currentPageSize,sorting,id!=null]);const data=useMemo(()=>type==="orders"?orders??[]:id==null?subscriptions??[]:subscriptions?.[0]?.type==="orders"?subscriptions:[],[orders,subscriptions]),cols=useMemo(()=>columns,[columns]),pagination=useMemo(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=orders?.pageCount??subscriptions?.pageCount??-1,table=useReactTable({data,columns:cols,getSortedRowModel:getSortedRowModel(),getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),manualPagination:!0,manualSorting:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";useEffect(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:columns[k]?.className,children:_jsxs("span",{className:`${columns[k]?.titleClassName??""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[flexRender(header.column.columnDef.header,header.getContext()),{asc:sortAscIcon,desc:sortDescIcon}[header.column.getIsSorted()]??null]})},header.id)});return _jsx(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return _jsx(TrHtmlElement,{className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?orders?.meta.recordCount??0:subscriptions?.meta.recordCount??0,Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?_jsx(_Fragment,{children:LoadingComponent}):(type==="orders"?orders:subscriptions)?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{children:components})]}),totalRows<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
2
+ import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useReactTable,getCoreRowModel,getPaginationRowModel,getSortedRowModel,flexRender}from"@tanstack/react-table";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),[sorting,setSorting]=useState(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=useState({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=useContext(CustomerContext),defaultSdkSorting=sortBy.length&&sortBy[0]!=null?{[sortBy[0].id]:sortBy[0].desc?"desc":"asc"}:void 0;useEffect(()=>{const sdkSorting=sorting.length&&sorting[0]!=null?{[sorting[0].id]:sorting[0].desc?"desc":"asc"}:defaultSdkSorting;type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting,id})},[pageIndex,currentPageSize,sorting,id!=null]);const data=useMemo(()=>type==="orders"?orders??[]:id==null?subscriptions??[]:subscriptions?.[0]?.type==="orders"?subscriptions:[],[orders,subscriptions]),cols=useMemo(()=>columns,[columns]),pagination=useMemo(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=orders?.pageCount??subscriptions?.pageCount??-1,table=useReactTable({data,columns:cols,getSortedRowModel:getSortedRowModel(),getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),manualPagination:!0,manualSorting:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";useEffect(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:columns[k]?.className,children:_jsxs("span",{className:`${columns[k]?.titleClassName??""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[flexRender(header.column.columnDef.header,header.getContext()),{asc:sortAscIcon,desc:sortDescIcon}[header.column.getIsSorted()]??null]})},header.id)});return _jsx(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return _jsx(TrHtmlElement,{className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?orders?.meta.recordCount??0:subscriptions?.meta.recordCount??0,Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?_jsx(_Fragment,{children:LoadingComponent}):(type==="orders"?orders:subscriptions)?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{children:components})]}),totalRows<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){console.log("Stripe redirect flow");const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(console.log("Checkout.com redirect flow",{order,status}),paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){console.log("Placing order with Checkout.com express payments");const paymentSourceStatus=order?.payment_source?.payment_response?.status;console.log("Payment source status:",paymentSourceStatus),paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null&&(placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null&&(placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";import{jwt}from"../../utils/jwt";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{setPlaceOrderStatus}=useContext(PlaceOrderContext),{containerClassName,templateCustomerSaveToWallet,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{ref.current&&component.isValid()&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:async(_component,paymentResponse)=>{console.log("onPaymentCompleted",{paymentResponse}),paymentResponse.status.toLowerCase()==="approved"&&(await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";import{jwt}from"../../utils/jwt";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{setPlaceOrderStatus}=useContext(PlaceOrderContext),{containerClassName,templateCustomerSaveToWallet,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{ref.current&&component.isValid()&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:async(_component,paymentResponse)=>{paymentResponse.status.toLowerCase()==="approved"&&(await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error,paymentIntent}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return console.log({paymentIntent}),error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
@@ -1,5 +1,5 @@
1
- import React, { type JSX } from 'react';
2
- import type { BaseInputComponentProps } from '../../typings/index';
3
- export type BaseInputProps = BaseInputComponentProps & Omit<JSX.IntrinsicElements['input'], 'children' | 'pattern'> & Omit<JSX.IntrinsicElements['textarea'], 'children' | 'pattern'>;
1
+ import React, { type JSX } from "react";
2
+ import type { BaseInputComponentProps } from "../../typings/index";
3
+ export type BaseInputProps = BaseInputComponentProps & Omit<JSX.IntrinsicElements["input"], "children" | "pattern"> & Omit<JSX.IntrinsicElements["textarea"], "children" | "pattern">;
4
4
  declare const _default: React.ForwardRefExoticComponent<Omit<BaseInputProps, "ref"> & React.RefAttributes<any>>;
5
5
  export default _default;
@@ -1,5 +1,5 @@
1
- import type { Address } from '@commercelayer/sdk';
2
- export type AddressValuesKeys = `${keyof Address}` | `billing_address_${keyof Address}` | `shipping_address_${keyof Address}` | `billing_address_${`metadata_${string}`}` | `shipping_address_${`metadata_${string}`}`;
1
+ import type { Address } from "@commercelayer/sdk";
2
+ export type AddressValuesKeys = `${keyof Address}` | `billing_address_${keyof Address}` | `shipping_address_${keyof Address}` | `billing_address_${`metadata_${string}`}` | `shipping_address_${`metadata_${string}`}` | `billing_address_save_to_customer_book` | `shipping_address_save_to_customer_book`;
3
3
  export interface DefaultContextAddress {
4
4
  validation?: void;
5
5
  setValue?: (name: AddressValuesKeys, value: string | number | readonly string[]) => void;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import baseReducer from"../utils/baseReducer";import{formCleaner}from"../utils/formCleaner";import getSdk from"../utils/getSdk";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config),billingAddress=formCleaner(billingAddressForm),shippingAddress=formCleaner(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=sanitizeMetadataFields(shippingAddress);let address;order?.shipping_address?.id&&order?.shipping_address?.reference==null?address=await sdk.addresses.update({id:order.shipping_address.id,...shippingAddressWithMeta}):(address=await sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder){const orderUpdated=await updateOrder({id:order.id,attributes:orderAttributes});return(order?.billing_address?.id&&order?.billing_address?.reference==null||order?.shipping_address?.id&&order?.shipping_address?.reference==null)&&await updateOrder({id:order.id,attributes:{_refresh:!0}}),{success:!0,order:orderUpdated?.order}}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default addressReducer;
2
+ import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import baseReducer from"../utils/baseReducer";import{formCleaner}from"../utils/formCleaner";import getSdk from"../utils/getSdk";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config),billingAddress=formCleaner(billingAddressForm),shippingAddress=formCleaner(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=sanitizeMetadataFields(shippingAddress);let address;order?.shipping_address?.id&&order?.shipping_address?.reference==null?address=await sdk.addresses.update({id:order.shipping_address.id,...shippingAddressWithMeta}):(address=await sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder)return{success:!0,order:(await updateOrder({id:order.id,attributes:orderAttributes}))?.order}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default addressReducer;
@@ -104,8 +104,7 @@ export interface GetCustomerPaymentSources {
104
104
  order?: Order;
105
105
  }
106
106
  export declare function getCustomerPaymentSources(params?: GetCustomerPaymentSources): void;
107
- type GetCustomerOrdersResource = Order | OrderSubscription;
108
- interface GetCustomerOrdersProps<T extends GetCustomerOrdersResource> {
107
+ interface GetCustomerOrdersProps {
109
108
  /**
110
109
  * The Commerce Layer config
111
110
  */
@@ -125,14 +124,14 @@ interface GetCustomerOrdersProps<T extends GetCustomerOrdersResource> {
125
124
  /**
126
125
  * The sort order
127
126
  */
128
- sortBy?: QuerySort<T>;
127
+ sortBy?: QuerySort<Order>;
129
128
  /**
130
129
  * Retrieve a specific subscription or order by id
131
130
  */
132
131
  id?: string;
133
132
  }
134
- export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps<Order>): Promise<void>;
135
- export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps<OrderSubscription>): Promise<void>;
133
+ export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps): Promise<void>;
134
+ export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps): Promise<void>;
136
135
  export type TCustomerAddress = AddressCreate & AddressUpdate & Record<string, string | null | undefined>;
137
136
  interface TCreateCustomerAddress {
138
137
  /**
@@ -153,7 +152,7 @@ interface TCreateCustomerAddress {
153
152
  state?: CustomerState;
154
153
  }
155
154
  export declare function createCustomerAddress({ address, config, dispatch, state }: TCreateCustomerAddress): Promise<void>;
156
- interface GetCustomerPaymentsParams extends GetCustomerOrdersProps<Order> {
155
+ interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
157
156
  }
158
157
  export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
159
158
  export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
2
+ import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.27.0-beta.0",
3
+ "version": "4.28.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",