@commercelayer/react-components 4.29.2 → 4.29.4-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentGateway=PaymentGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),AdyenGateway_1=tslib_1.__importDefault(require("./AdyenGateway")),BraintreeGateway_1=tslib_1.__importDefault(require("./BraintreeGateway")),CheckoutComGateway_1=tslib_1.__importDefault(require("./CheckoutComGateway")),ExternalGateway_1=tslib_1.__importDefault(require("./ExternalGateway")),KlarnaGateway_1=tslib_1.__importDefault(require("./KlarnaGateway")),PaypalGateway_1=tslib_1.__importDefault(require("./PaypalGateway")),StripeGateway_1=tslib_1.__importDefault(require("./StripeGateway")),WireTransferGateway_1=tslib_1.__importDefault(require("./WireTransferGateway"));function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=(0,getLoaderComponent_1.default)(loader),[loading,setLoading]=(0,react_1.useState)(!0),{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;(0,react_1.useEffect)(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=(0,getPaymentAttributes_1.getStripeAttributes)(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1),paymentSource||setLoading(!0)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource?.id]),(0,react_1.useEffect)(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return(0,jsx_runtime_1.jsx)(AdyenGateway_1.default,{...gatewayConfig,children});case"braintree_payments":return(0,jsx_runtime_1.jsx)(BraintreeGateway_1.default,{...gatewayConfig,children});case"checkout_com_payments":return(0,jsx_runtime_1.jsx)(CheckoutComGateway_1.default,{...gatewayConfig,children});case"external_payments":return(0,jsx_runtime_1.jsx)(ExternalGateway_1.default,{...gatewayConfig,children});case"klarna_payments":return(0,jsx_runtime_1.jsx)(KlarnaGateway_1.default,{...gatewayConfig,children});case"stripe_payments":return(0,jsx_runtime_1.jsx)(StripeGateway_1.default,{...gatewayConfig,children});case"wire_transfers":return(0,jsx_runtime_1.jsx)(WireTransferGateway_1.default,{...gatewayConfig,children});case"paypal_payments":return(0,jsx_runtime_1.jsx)(PaypalGateway_1.default,{...gatewayConfig,children});default:return null}}exports.default=PaymentGateway;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentGateway=PaymentGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),AdyenGateway_1=tslib_1.__importDefault(require("./AdyenGateway")),BraintreeGateway_1=tslib_1.__importDefault(require("./BraintreeGateway")),CheckoutComGateway_1=tslib_1.__importDefault(require("./CheckoutComGateway")),ExternalGateway_1=tslib_1.__importDefault(require("./ExternalGateway")),KlarnaGateway_1=tslib_1.__importDefault(require("./KlarnaGateway")),PaypalGateway_1=tslib_1.__importDefault(require("./PaypalGateway")),StripeGateway_1=tslib_1.__importDefault(require("./StripeGateway")),WireTransferGateway_1=tslib_1.__importDefault(require("./WireTransferGateway"));function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=(0,getLoaderComponent_1.default)(loader),[loading,setLoading]=(0,react_1.useState)(!0),{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource,paymentMethods}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;(0,react_1.useEffect)(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=(0,getPaymentAttributes_1.getStripeAttributes)(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const setPaymentSources=async()=>{order!=null&&paymentMethods&&paymentMethods?.length>1&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1),paymentSource||setLoading(!0)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource?.id]),(0,react_1.useEffect)(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return(0,jsx_runtime_1.jsx)(AdyenGateway_1.default,{...gatewayConfig,children});case"braintree_payments":return(0,jsx_runtime_1.jsx)(BraintreeGateway_1.default,{...gatewayConfig,children});case"checkout_com_payments":return(0,jsx_runtime_1.jsx)(CheckoutComGateway_1.default,{...gatewayConfig,children});case"external_payments":return(0,jsx_runtime_1.jsx)(ExternalGateway_1.default,{...gatewayConfig,children});case"klarna_payments":return(0,jsx_runtime_1.jsx)(KlarnaGateway_1.default,{...gatewayConfig,children});case"stripe_payments":return(0,jsx_runtime_1.jsx)(StripeGateway_1.default,{...gatewayConfig,children});case"wire_transfers":return(0,jsx_runtime_1.jsx)(WireTransferGateway_1.default,{...gatewayConfig,children});case"paypal_payments":return(0,jsx_runtime_1.jsx)(PaypalGateway_1.default,{...gatewayConfig,children});default:return null}}exports.default=PaymentGateway;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethod=PaymentMethod;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=(0,react_1.useState)(!0),[paymentSelected,setPaymentSelected]=(0,react_1.useState)(""),[paymentSourceCreated,setPaymentSourceCreated]=(0,react_1.useState)(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=(0,useCustomContext_1.default)({context:PaymentMethodContext_1.default,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default);(0,react_1.useEffect)(()=>{if(paymentMethods!=null&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&expressPayments){const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments,errors?.length]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!(0,isEmpty_1.isEmpty)(paymentMethods),order?.payment_source!=null,errors?.length]),(0,react_1.useEffect)(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),(0,react_1.useEffect)(()=>{const status2=order?.payment_source?.payment_response?.status?.toLowerCase();showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return(0,jsx_runtime_1.jsx)("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:(0,jsx_runtime_1.jsx)(PaymentMethodChildrenContext_1.default.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?(0,getLoaderComponent_1.default)(loader):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.default=PaymentMethod;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethod=PaymentMethod;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=(0,react_1.useState)(!0),[paymentSelected,setPaymentSelected]=(0,react_1.useState)(""),[paymentSourceCreated,setPaymentSourceCreated]=(0,react_1.useState)(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=(0,useCustomContext_1.default)({context:PaymentMethodContext_1.default,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default);(0,react_1.useEffect)(()=>{if(paymentMethods!=null&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&expressPayments){const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments,errors?.length]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config)),console.log("Attributes:",order?.payment_source,attributes);const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!(0,isEmpty_1.isEmpty)(paymentMethods),errors?.length]),(0,react_1.useEffect)(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),(0,react_1.useEffect)(()=>{const status2=order?.payment_source?.payment_response?.status?.toLowerCase();showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return(0,jsx_runtime_1.jsx)("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:(0,jsx_runtime_1.jsx)(PaymentMethodChildrenContext_1.default.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?(0,getLoaderComponent_1.default)(loader):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.default=PaymentMethod;
@@ -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,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,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes,getStripeAttributes}from"../../utils/getPaymentAttributes";import AdyenGateway from"./AdyenGateway";import BraintreeGateway from"./BraintreeGateway";import CheckoutComGateway from"./CheckoutComGateway";import ExternalGateway from"./ExternalGateway";import KlarnaGateway from"./KlarnaGateway";import PaypalGateway from"./PaypalGateway";import StripeGateway from"./StripeGateway";import WireTransferGateway from"./WireTransferGateway";export function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=getLoaderComponent(loader),[loading,setLoading]=useState(!0),{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=useContext(PaymentMethodContext),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;useEffect(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=getStripeAttributes(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1),paymentSource||setLoading(!0)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource?.id]),useEffect(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return _jsx(AdyenGateway,{...gatewayConfig,children});case"braintree_payments":return _jsx(BraintreeGateway,{...gatewayConfig,children});case"checkout_com_payments":return _jsx(CheckoutComGateway,{...gatewayConfig,children});case"external_payments":return _jsx(ExternalGateway,{...gatewayConfig,children});case"klarna_payments":return _jsx(KlarnaGateway,{...gatewayConfig,children});case"stripe_payments":return _jsx(StripeGateway,{...gatewayConfig,children});case"wire_transfers":return _jsx(WireTransferGateway,{...gatewayConfig,children});case"paypal_payments":return _jsx(PaypalGateway,{...gatewayConfig,children});default:return null}}export default PaymentGateway;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes,getStripeAttributes}from"../../utils/getPaymentAttributes";import AdyenGateway from"./AdyenGateway";import BraintreeGateway from"./BraintreeGateway";import CheckoutComGateway from"./CheckoutComGateway";import ExternalGateway from"./ExternalGateway";import KlarnaGateway from"./KlarnaGateway";import PaypalGateway from"./PaypalGateway";import StripeGateway from"./StripeGateway";import WireTransferGateway from"./WireTransferGateway";export function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=getLoaderComponent(loader),[loading,setLoading]=useState(!0),{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource,paymentMethods}=useContext(PaymentMethodContext),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;useEffect(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=getStripeAttributes(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const setPaymentSources=async()=>{order!=null&&paymentMethods&&paymentMethods?.length>1&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1),paymentSource||setLoading(!0)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource?.id]),useEffect(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return _jsx(AdyenGateway,{...gatewayConfig,children});case"braintree_payments":return _jsx(BraintreeGateway,{...gatewayConfig,children});case"checkout_com_payments":return _jsx(CheckoutComGateway,{...gatewayConfig,children});case"external_payments":return _jsx(ExternalGateway,{...gatewayConfig,children});case"klarna_payments":return _jsx(KlarnaGateway,{...gatewayConfig,children});case"stripe_payments":return _jsx(StripeGateway,{...gatewayConfig,children});case"wire_transfers":return _jsx(WireTransferGateway,{...gatewayConfig,children});case"paypal_payments":return _jsx(PaypalGateway,{...gatewayConfig,children});default:return null}}export default PaymentGateway;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=useCustomContext({context:PaymentMethodContext,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext);useEffect(()=>{if(paymentMethods!=null&&!isEmpty(paymentMethods)&&expressPayments){const[paymentMethod]=getAvailableExpressPayments(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments,errors?.length]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!isEmpty(paymentMethods),order?.payment_source!=null,errors?.length]),useEffect(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),useEffect(()=>{const status2=order?.payment_source?.payment_response?.status?.toLowerCase();showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?sortPaymentMethods(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return _jsx("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:_jsx(PaymentMethodChildrenContext.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default PaymentMethod;
2
+ import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=useCustomContext({context:PaymentMethodContext,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext);useEffect(()=>{if(paymentMethods!=null&&!isEmpty(paymentMethods)&&expressPayments){const[paymentMethod]=getAvailableExpressPayments(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments,errors?.length]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config)),console.log("Attributes:",order?.payment_source,attributes);const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!isEmpty(paymentMethods),errors?.length]),useEffect(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),useEffect(()=>{const status2=order?.payment_source?.payment_response?.status?.toLowerCase();showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?sortPaymentMethods(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return _jsx("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:_jsx(PaymentMethodChildrenContext.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default PaymentMethod;
@@ -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,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.2",
3
+ "version": "4.29.4-beta.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",