@commercelayer/react-components 4.29.0-beta.5 → 4.29.3

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.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=CustomerContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.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]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await(0,CustomerReducer_1.setResourceTrigger)({...props2,dispatch,config}),createCustomerAddress:async address=>{await(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.default=CustomerContainer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=CustomerContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.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]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerPayment:async({customerPaymentSourceId})=>{await(0,CustomerReducer_1.deleteCustomerPayment)({customerPaymentSourceId,dispatch,config})},deleteCustomerAddress:async({customerAddressId})=>{await(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await(0,CustomerReducer_1.setResourceTrigger)({...props2,dispatch,config}),createCustomerAddress:async address=>{await(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.default=CustomerContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerPaymentSource=CustomerPaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),CustomerPaymentSourceContext_1=tslib_1.__importDefault(require("../../context/CustomerPaymentSourceContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function CustomerPaymentSource({children,loader="Loading..."}){const{sdkClient}=(0,useCommerceLayer_1.default)(),[loading,setLoading]=(0,react_1.useState)(!0),{payments,getCustomerPaymentSources}=(0,useCustomContext_1.default)({context:CustomerContext_1.default,contextComponentName:"CustomerContainer",currentComponentName:"CustomerPaymentSource",key:"payments"});(0,react_1.useEffect)(()=>(payments!=null&&setLoading(!1),()=>{setLoading(!0)}),[payments]);const provider=payments?.filter(p=>p?.payment_source!=null).map(p=>{const paymentType=p.payment_source?.type,customerPayment=p,value={...(0,getCardDetails_1.default)({paymentType,customerPayment}),handleDeleteClick:e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();sdk?.customer_payment_sources.delete(p.id).then(()=>{getCustomerPaymentSources&&getCustomerPaymentSources()})}};return(0,jsx_runtime_1.jsx)(CustomerPaymentSourceContext_1.default.Provider,{value,children},p.id)});return loading?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:loader}):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:provider})}exports.default=CustomerPaymentSource;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerPaymentSource=CustomerPaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),CustomerPaymentSourceContext_1=tslib_1.__importDefault(require("../../context/CustomerPaymentSourceContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function CustomerPaymentSource({children,loader="Loading..."}){const[loading,setLoading]=(0,react_1.useState)(!0),{payments,deleteCustomerPayment}=(0,useCustomContext_1.default)({context:CustomerContext_1.default,contextComponentName:"CustomerContainer",currentComponentName:"CustomerPaymentSource",key:"payments"});(0,react_1.useEffect)(()=>(payments!=null&&setLoading(!1),()=>{setLoading(!0)}),[payments]);const provider=payments?.filter(p=>p?.payment_source!=null).map(p=>{const paymentType=p.payment_source?.type,customerPayment=p,value={...(0,getCardDetails_1.default)({paymentType,customerPayment}),handleDeleteClick:e=>{e?.preventDefault(),e?.stopPropagation(),deleteCustomerPayment?.({customerPaymentSourceId:p.id})}};return(0,jsx_runtime_1.jsx)(CustomerPaymentSourceContext_1.default.Provider,{value,children},p.id)});return loading?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:loader}):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:provider})}exports.default=CustomerPaymentSource;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BraintreePayment=BraintreePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),promisify_1=tslib_1.__importDefault(require("../../utils/promisify")),defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}={...defaultConfig,...config},[loadBraintree,setLoadBraintree]=(0,react_1.useState)(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null),handleSubmitForm=async({event,hostedFieldsInstance,threeDSInstance})=>{const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=await(0,promisify_1.default)(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:order?.customer_email??"",billingAddress:{givenName:billingAddress?.first_name??"",surname:billingAddress?.last_name??"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:billingAddress?.zip_code??"",region:billingAddress?.state_code,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=await threeDSInstance.verifyCard(verifyCardOptions);if(response?.liabilityShiftPossible===!0&&response?.liabilityShifted===!0&&paymentSource!=null)return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"braintree_payments",attributes:{payment_method_nonce:response.nonce,options:{id:response.nonce,card:{last4:response.details.lastFour,exp_year:response.details.expirationYear,exp_month:response.details.expirationMonth,brand:response.details.cardType.toLowerCase()}}}}),!0;throw new Error(`3D Secure authentication failed - ${response?.threeDSecureInfo?.status}`)}catch(error){return console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}return!1};return(0,react_1.useEffect)(()=>{if(!ref&&authorization&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),authorization&&!loadBraintree&&!(0,isEmpty_1.default)(window)){const braintreeClient=require("braintree-web/client"),hostedFields=require("braintree-web/hosted-fields"),threeDSecure=require("braintree-web/three-d-secure");braintreeClient.create({authorization,challengeRequested:config?.challengeRequested??!0},(clientErr,clientInstance)=>{if(clientErr){console.error(clientErr);return}hostedFields.create({client:clientInstance,fields,styles},(hostedFieldsErr,hostedFieldsInstance)=>{if(hostedFieldsErr){console.error(hostedFieldsErr);return}setLoadBraintree(!0),threeDSecure.create({authorization,version:2},(threeDSecureErr,threeDSInstance)=>{threeDSecureErr&&(console.error("3DSecure error",threeDSecureErr),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:threeDSecureErr.message}])),ref.current&&(ref.current.onsubmit=async paymentSource2=>await handleSubmitForm({event:ref.current,hostedFieldsInstance,threeDSInstance,paymentSource:paymentSource2}),setPaymentRef({ref}))})})})}return()=>{setPaymentRef({ref:{current:null}}),setLoadBraintree(!1)}},[authorization,ref]),!authorization&&!loadBraintree?null:(0,jsx_runtime_1.jsx)("div",{className:containerClassName,children:(0,jsx_runtime_1.jsxs)("form",{ref,id:"braintree-form",onSubmit:handleSubmitForm,className:containerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:fieldsContainerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:cardContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"card-number",children:fields?.number?.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"card-number"})]}),(0,jsx_runtime_1.jsxs)("div",{className:cardDetailsContainerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:expDateContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"expiration-date",children:fields?.expirationDate?.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"expiration-date"})]}),(0,jsx_runtime_1.jsxs)("div",{className:cvvContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"cvv",children:fields?.cvv?.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"cvv"})]})]})]}),(0,jsx_runtime_1.jsx)("div",{className:fieldsContainerClassName,children:templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})})]})})}exports.default=BraintreePayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BraintreePayment=BraintreePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),promisify_1=tslib_1.__importDefault(require("../../utils/promisify")),defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}={...defaultConfig,...config},[loadBraintree,setLoadBraintree]=(0,react_1.useState)(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null),handleSubmitForm=async({event,hostedFieldsInstance,threeDSInstance})=>{const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=await(0,promisify_1.default)(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:order?.customer_email??"",billingAddress:{givenName:billingAddress?.first_name??"",surname:billingAddress?.last_name??"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:billingAddress?.zip_code??"",region:billingAddress?.state_code??void 0,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=await threeDSInstance.verifyCard(verifyCardOptions);if(response?.liabilityShiftPossible===!0&&response?.liabilityShifted===!0&&paymentSource!=null)return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"braintree_payments",attributes:{payment_method_nonce:response.nonce,options:{id:response.nonce,card:{last4:response.details.lastFour,exp_year:response.details.expirationYear,exp_month:response.details.expirationMonth,brand:response.details.cardType.toLowerCase()}}}}),!0;throw new Error(`3D Secure authentication failed - ${response?.threeDSecureInfo?.status}`)}catch(error){return console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}return!1};return(0,react_1.useEffect)(()=>{if(!ref&&authorization&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),authorization&&!loadBraintree&&!(0,isEmpty_1.default)(window)){const braintreeClient=require("braintree-web/client"),hostedFields=require("braintree-web/hosted-fields"),threeDSecure=require("braintree-web/three-d-secure");braintreeClient.create({authorization,challengeRequested:config?.challengeRequested??!0},(clientErr,clientInstance)=>{if(clientErr){console.error(clientErr);return}hostedFields.create({client:clientInstance,fields,styles},(hostedFieldsErr,hostedFieldsInstance)=>{if(hostedFieldsErr){console.error(hostedFieldsErr);return}setLoadBraintree(!0),threeDSecure.create({authorization,version:2},(threeDSecureErr,threeDSInstance)=>{threeDSecureErr&&(console.error("3DSecure error",threeDSecureErr),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:threeDSecureErr.message}])),ref.current&&(ref.current.onsubmit=async paymentSource2=>await handleSubmitForm({event:ref.current,hostedFieldsInstance,threeDSInstance,paymentSource:paymentSource2}),setPaymentRef({ref}))})})})}return()=>{setPaymentRef({ref:{current:null}}),setLoadBraintree(!1)}},[authorization,ref]),!authorization&&!loadBraintree?null:(0,jsx_runtime_1.jsx)("div",{className:containerClassName,children:(0,jsx_runtime_1.jsxs)("form",{ref,id:"braintree-form",onSubmit:handleSubmitForm,className:containerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:fieldsContainerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:cardContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"card-number",children:fields?.number?.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"card-number"})]}),(0,jsx_runtime_1.jsxs)("div",{className:cardDetailsContainerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:expDateContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"expiration-date",children:fields?.expirationDate?.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"expiration-date"})]}),(0,jsx_runtime_1.jsxs)("div",{className:cvvContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"cvv",children:fields?.cvv?.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"cvv"})]})]})]}),(0,jsx_runtime_1.jsx)("div",{className:fieldsContainerClassName,children:templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})})]})})}exports.default=BraintreePayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),jwt_1=require("../../utils/jwt"),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment({publicKey,options,...p}){const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,show,...divProps}=p;return(0,react_1.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=(0,jwt_1.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&&(0,localStorage_1.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 paymentStatus=paymentSource.payment_response?.status.toLowerCase(),securityRedirect=paymentSource?.redirect_uri;if(paymentStatus==="pending"&&securityRedirect)return window.location.href=securityRedirect,!1;if(paymentStatus==="declined")return!1}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?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),jwt_1=require("../../utils/jwt"),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment({publicKey,options,...p}){const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,show,...divProps}=p;return(0,react_1.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=(0,jwt_1.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&&(0,localStorage_1.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 paymentStatus=paymentSource.payment_response?.status.toLowerCase(),securityRedirect=paymentSource?.redirect_uri;if(paymentStatus==="pending"&&securityRedirect)return window.location.href=securityRedirect,!1;if(paymentStatus==="declined")return!1}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?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=KlarnaPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript"));function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";case"payment_methods":default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=(0,react_1.useRef)(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),loaded=(0,useExternalScript_1.default)("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=(0,react_1.useState)(),{containerClassName,...divProps}=p;(0,react_1.useEffect)(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),(0,react_1.useEffect)(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async res=>{if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return(0,jsx_runtime_1.jsx)("form",{ref,children:(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)("div",{id:"klarna-payments-container"})})})}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=KlarnaPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript"));function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=(0,react_1.useRef)(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),loaded=(0,useExternalScript_1.default)("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=(0,react_1.useState)(),{containerClassName,...divProps}=p;(0,react_1.useEffect)(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),(0,react_1.useEffect)(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async res=>{if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return(0,jsx_runtime_1.jsx)("form",{ref,children:(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)("div",{id:"klarna-payments-container"})})})}
@@ -1,9 +1,10 @@
1
- import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger } from '../reducers/CustomerReducer';
1
+ import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger, deleteCustomerPayment } from '../reducers/CustomerReducer';
2
2
  export type InitialCustomerContext = Partial<{
3
3
  saveCustomerUser: (customerEmail: string) => Promise<void>;
4
4
  setCustomerErrors: SetCustomerErrors;
5
5
  setCustomerEmail: typeof setCustomerEmail;
6
6
  getCustomerPaymentSources: typeof getCustomerPaymentSources;
7
+ deleteCustomerPayment: typeof deleteCustomerPayment;
7
8
  deleteCustomerAddress: typeof deleteCustomerAddress;
8
9
  getCustomerAddresses: typeof getCustomerAddresses;
9
10
  createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
@@ -18,6 +19,7 @@ declare const CustomerContext: import("react").Context<Partial<{
18
19
  setCustomerErrors: SetCustomerErrors;
19
20
  setCustomerEmail: typeof setCustomerEmail;
20
21
  getCustomerPaymentSources: typeof getCustomerPaymentSources;
22
+ deleteCustomerPayment: typeof deleteCustomerPayment;
21
23
  deleteCustomerAddress: typeof deleteCustomerAddress;
22
24
  getCustomerAddresses: typeof getCustomerAddresses;
23
25
  createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
@@ -155,6 +155,12 @@ export declare function createCustomerAddress({ address, config, dispatch, state
155
155
  interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
156
156
  }
157
157
  export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
158
+ export interface DeleteCustomerPayment {
159
+ customerPaymentSourceId: string;
160
+ dispatch?: Dispatch<CustomerAction>;
161
+ config?: CommerceLayerConfig;
162
+ }
163
+ export declare function deleteCustomerPayment({ customerPaymentSourceId, dispatch, config, }: DeleteCustomerPayment): Promise<void>;
158
164
  export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
159
165
  export type SetResourceTriggerParams = {
160
166
  /**
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await(0,getSdk_1.default)(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=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await(0,getSdk_1.default)(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")}}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}})}}async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=await(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(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}})}}}}async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.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=(0,addressesManager_1.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")}}}async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.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}})}}}async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if(await(0,triggerAttributeHelper_1.triggerAttributeHelper)(params)!=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}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.deleteCustomerPayment=deleteCustomerPayment,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await(0,getSdk_1.default)(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=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await(0,getSdk_1.default)(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")}}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}})}}async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=await(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(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}})}}}}async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.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=(0,addressesManager_1.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")}}}async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.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}})}}}async function deleteCustomerPayment({customerPaymentSourceId,dispatch,config}){if(config&&dispatch)try{await(0,getSdk_1.default)(config).customer_payment_sources.delete(customerPaymentSourceId),getCustomerPayments({config,dispatch})}catch{throw new Error("Couldn't delete payment source")}}async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if(await(0,triggerAttributeHelper_1.triggerAttributeHelper)(params)!=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}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),customerOrderOptions_1=require("../utils/customerOrderOptions"),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),hasSubscriptions_1=require("../utils/hasSubscriptions"),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),shipments_1=require("../utils/shipments"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),(0,customerOrderOptions_1.saveShippingAddress)()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),customerOrderOptions_1=require("../utils/customerOrderOptions"),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),hasSubscriptions_1=require("../utils/hasSubscriptions"),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),shipments_1=require("../utils/shipments"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),(0,customerOrderOptions_1.saveShippingAddress)()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}if((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType==="braintree_payments"){const total=order?.total_amount_cents??0;await Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}else{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
@@ -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=>{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}}
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){return paymentType==="braintree_payments"?order.payment_source!=null&&order.payment_source.type==="braintree_payments"&&order.payment_source.options!=null?order.payment_source.options.payment_method_token:void 0:order?.payment_source_details?.payment_method_id??void 0}
@@ -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,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;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,deleteCustomerPayment,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})},deleteCustomerPayment:async({customerPaymentSourceId})=>{await deleteCustomerPayment({customerPaymentSourceId,dispatch,config})},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,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import useCustomContext from"../../utils/hooks/useCustomContext";export function CustomerPaymentSource({children,loader="Loading..."}){const{sdkClient}=useCommerceLayer(),[loading,setLoading]=useState(!0),{payments,getCustomerPaymentSources}=useCustomContext({context:CustomerContext,contextComponentName:"CustomerContainer",currentComponentName:"CustomerPaymentSource",key:"payments"});useEffect(()=>(payments!=null&&setLoading(!1),()=>{setLoading(!0)}),[payments]);const provider=payments?.filter(p=>p?.payment_source!=null).map(p=>{const paymentType=p.payment_source?.type,value={...getCardDetails({paymentType,customerPayment:p}),handleDeleteClick:e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();sdk?.customer_payment_sources.delete(p.id).then(()=>{getCustomerPaymentSources&&getCustomerPaymentSources()})}};return _jsx(CustomerPaymentSourceContext.Provider,{value,children},p.id)});return loading?_jsx(_Fragment,{children:loader}):_jsx(_Fragment,{children:provider})}export default CustomerPaymentSource;
2
+ import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";import getCardDetails from"../../utils/getCardDetails";import useCustomContext from"../../utils/hooks/useCustomContext";export function CustomerPaymentSource({children,loader="Loading..."}){const[loading,setLoading]=useState(!0),{payments,deleteCustomerPayment}=useCustomContext({context:CustomerContext,contextComponentName:"CustomerContainer",currentComponentName:"CustomerPaymentSource",key:"payments"});useEffect(()=>(payments!=null&&setLoading(!1),()=>{setLoading(!0)}),[payments]);const provider=payments?.filter(p=>p?.payment_source!=null).map(p=>{const paymentType=p.payment_source?.type,value={...getCardDetails({paymentType,customerPayment:p}),handleDeleteClick:e=>{e?.preventDefault(),e?.stopPropagation(),deleteCustomerPayment?.({customerPaymentSourceId:p.id})}};return _jsx(CustomerPaymentSourceContext.Provider,{value,children},p.id)});return loading?_jsx(_Fragment,{children:loader}):_jsx(_Fragment,{children:provider})}export default CustomerPaymentSource;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import promisify from"../../utils/promisify";const defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};export function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}={...defaultConfig,...config},[loadBraintree,setLoadBraintree]=useState(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),ref=useRef(null),handleSubmitForm=async({event,hostedFieldsInstance,threeDSInstance})=>{const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=await promisify(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:order?.customer_email??"",billingAddress:{givenName:billingAddress?.first_name??"",surname:billingAddress?.last_name??"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:billingAddress?.zip_code??"",region:billingAddress?.state_code,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=await threeDSInstance.verifyCard(verifyCardOptions);if(response?.liabilityShiftPossible===!0&&response?.liabilityShifted===!0&&paymentSource!=null)return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"braintree_payments",attributes:{payment_method_nonce:response.nonce,options:{id:response.nonce,card:{last4:response.details.lastFour,exp_year:response.details.expirationYear,exp_month:response.details.expirationMonth,brand:response.details.cardType.toLowerCase()}}}}),!0;throw new Error(`3D Secure authentication failed - ${response?.threeDSecureInfo?.status}`)}catch(error){return console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}return!1};return useEffect(()=>{if(!ref&&authorization&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),authorization&&!loadBraintree&&!isEmpty(window)){const braintreeClient=require("braintree-web/client"),hostedFields=require("braintree-web/hosted-fields"),threeDSecure=require("braintree-web/three-d-secure");braintreeClient.create({authorization,challengeRequested:config?.challengeRequested??!0},(clientErr,clientInstance)=>{if(clientErr){console.error(clientErr);return}hostedFields.create({client:clientInstance,fields,styles},(hostedFieldsErr,hostedFieldsInstance)=>{if(hostedFieldsErr){console.error(hostedFieldsErr);return}setLoadBraintree(!0),threeDSecure.create({authorization,version:2},(threeDSecureErr,threeDSInstance)=>{threeDSecureErr&&(console.error("3DSecure error",threeDSecureErr),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:threeDSecureErr.message}])),ref.current&&(ref.current.onsubmit=async paymentSource2=>await handleSubmitForm({event:ref.current,hostedFieldsInstance,threeDSInstance,paymentSource:paymentSource2}),setPaymentRef({ref}))})})})}return()=>{setPaymentRef({ref:{current:null}}),setLoadBraintree(!1)}},[authorization,ref]),!authorization&&!loadBraintree?null:_jsx("div",{className:containerClassName,children:_jsxs("form",{ref,id:"braintree-form",onSubmit:handleSubmitForm,className:containerClassName,children:[_jsxs("div",{className:fieldsContainerClassName,children:[_jsxs("div",{className:cardContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"card-number",children:fields?.number?.label}),_jsx("div",{className:inputWrapperClassName,id:"card-number"})]}),_jsxs("div",{className:cardDetailsContainerClassName,children:[_jsxs("div",{className:expDateContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"expiration-date",children:fields?.expirationDate?.label}),_jsx("div",{className:inputWrapperClassName,id:"expiration-date"})]}),_jsxs("div",{className:cvvContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"cvv",children:fields?.cvv?.label}),_jsx("div",{className:inputWrapperClassName,id:"cvv"})]})]})]}),_jsx("div",{className:fieldsContainerClassName,children:templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})})]})})}export default BraintreePayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import promisify from"../../utils/promisify";const defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};export function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}={...defaultConfig,...config},[loadBraintree,setLoadBraintree]=useState(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),ref=useRef(null),handleSubmitForm=async({event,hostedFieldsInstance,threeDSInstance})=>{const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=await promisify(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:order?.customer_email??"",billingAddress:{givenName:billingAddress?.first_name??"",surname:billingAddress?.last_name??"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:billingAddress?.zip_code??"",region:billingAddress?.state_code??void 0,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=await threeDSInstance.verifyCard(verifyCardOptions);if(response?.liabilityShiftPossible===!0&&response?.liabilityShifted===!0&&paymentSource!=null)return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"braintree_payments",attributes:{payment_method_nonce:response.nonce,options:{id:response.nonce,card:{last4:response.details.lastFour,exp_year:response.details.expirationYear,exp_month:response.details.expirationMonth,brand:response.details.cardType.toLowerCase()}}}}),!0;throw new Error(`3D Secure authentication failed - ${response?.threeDSecureInfo?.status}`)}catch(error){return console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}return!1};return useEffect(()=>{if(!ref&&authorization&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),authorization&&!loadBraintree&&!isEmpty(window)){const braintreeClient=require("braintree-web/client"),hostedFields=require("braintree-web/hosted-fields"),threeDSecure=require("braintree-web/three-d-secure");braintreeClient.create({authorization,challengeRequested:config?.challengeRequested??!0},(clientErr,clientInstance)=>{if(clientErr){console.error(clientErr);return}hostedFields.create({client:clientInstance,fields,styles},(hostedFieldsErr,hostedFieldsInstance)=>{if(hostedFieldsErr){console.error(hostedFieldsErr);return}setLoadBraintree(!0),threeDSecure.create({authorization,version:2},(threeDSecureErr,threeDSInstance)=>{threeDSecureErr&&(console.error("3DSecure error",threeDSecureErr),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:threeDSecureErr.message}])),ref.current&&(ref.current.onsubmit=async paymentSource2=>await handleSubmitForm({event:ref.current,hostedFieldsInstance,threeDSInstance,paymentSource:paymentSource2}),setPaymentRef({ref}))})})})}return()=>{setPaymentRef({ref:{current:null}}),setLoadBraintree(!1)}},[authorization,ref]),!authorization&&!loadBraintree?null:_jsx("div",{className:containerClassName,children:_jsxs("form",{ref,id:"braintree-form",onSubmit:handleSubmitForm,className:containerClassName,children:[_jsxs("div",{className:fieldsContainerClassName,children:[_jsxs("div",{className:cardContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"card-number",children:fields?.number?.label}),_jsx("div",{className:inputWrapperClassName,id:"card-number"})]}),_jsxs("div",{className:cardDetailsContainerClassName,children:[_jsxs("div",{className:expDateContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"expiration-date",children:fields?.expirationDate?.label}),_jsx("div",{className:inputWrapperClassName,id:"expiration-date"})]}),_jsxs("div",{className:cvvContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"cvv",children:fields?.cvv?.label}),_jsx("div",{className:inputWrapperClassName,id:"cvv"})]})]})]}),_jsx("div",{className:fieldsContainerClassName,children:templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})})]})})}export default BraintreePayment;
@@ -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 paymentStatus=paymentSource.payment_response?.status.toLowerCase(),securityRedirect=paymentSource?.redirect_uri;if(paymentStatus==="pending"&&securityRedirect)return window.location.href=securityRedirect,!1;if(paymentStatus==="declined")return!1}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;
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 paymentStatus=paymentSource.payment_response?.status.toLowerCase(),securityRedirect=paymentSource?.redirect_uri;if(paymentStatus==="pending"&&securityRedirect)return window.location.href=securityRedirect,!1;if(paymentStatus==="declined")return!1}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}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";case"payment_methods":default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}export default function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=useRef(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),loaded=useExternalScript("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=useState(),{containerClassName,...divProps}=p;useEffect(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),useEffect(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async res=>{if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}export default function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=useRef(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),loaded=useExternalScript("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=useState(),{containerClassName,...divProps}=p;useEffect(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),useEffect(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async res=>{if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
@@ -1,9 +1,10 @@
1
- import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger } from '../reducers/CustomerReducer';
1
+ import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger, deleteCustomerPayment } from '../reducers/CustomerReducer';
2
2
  export type InitialCustomerContext = Partial<{
3
3
  saveCustomerUser: (customerEmail: string) => Promise<void>;
4
4
  setCustomerErrors: SetCustomerErrors;
5
5
  setCustomerEmail: typeof setCustomerEmail;
6
6
  getCustomerPaymentSources: typeof getCustomerPaymentSources;
7
+ deleteCustomerPayment: typeof deleteCustomerPayment;
7
8
  deleteCustomerAddress: typeof deleteCustomerAddress;
8
9
  getCustomerAddresses: typeof getCustomerAddresses;
9
10
  createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
@@ -18,6 +19,7 @@ declare const CustomerContext: import("react").Context<Partial<{
18
19
  setCustomerErrors: SetCustomerErrors;
19
20
  setCustomerEmail: typeof setCustomerEmail;
20
21
  getCustomerPaymentSources: typeof getCustomerPaymentSources;
22
+ deleteCustomerPayment: typeof deleteCustomerPayment;
21
23
  deleteCustomerAddress: typeof deleteCustomerAddress;
22
24
  getCustomerAddresses: typeof getCustomerAddresses;
23
25
  createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
@@ -155,6 +155,12 @@ export declare function createCustomerAddress({ address, config, dispatch, state
155
155
  interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
156
156
  }
157
157
  export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
158
+ export interface DeleteCustomerPayment {
159
+ customerPaymentSourceId: string;
160
+ dispatch?: Dispatch<CustomerAction>;
161
+ config?: CommerceLayerConfig;
162
+ }
163
+ export declare function deleteCustomerPayment({ customerPaymentSourceId, dispatch, config, }: DeleteCustomerPayment): Promise<void>;
158
164
  export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
159
165
  export type SetResourceTriggerParams = {
160
166
  /**
@@ -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,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;
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 deleteCustomerPayment({customerPaymentSourceId,dispatch,config}){if(config&&dispatch)try{await getSdk(config).customer_payment_sources.delete(customerPaymentSourceId),getCustomerPayments({config,dispatch})}catch{throw new Error("Couldn't delete payment source")}}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;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getErrors from"../utils/getErrors";import getSdk from"../utils/getSdk";import{hasSubscriptions}from"../utils/hasSubscriptions";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
2
+ import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getErrors from"../utils/getErrors";import getSdk from"../utils/getSdk";import{hasSubscriptions}from"../utils/hasSubscriptions";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}if(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType==="braintree_payments"){const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}else{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export 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}}
2
+ export 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){return paymentType==="braintree_payments"?order.payment_source!=null&&order.payment_source.type==="braintree_payments"&&order.payment_source.options!=null?order.payment_source.options.payment_method_token:void 0:order?.payment_source_details?.payment_method_id??void 0}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.29.0-beta.5",
3
+ "version": "4.29.3",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",