@commercelayer/react-components 4.24.1-beta.1 → 4.24.1-beta.4
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.
- package/lib/cjs/components/payment_methods/PaymentMethod.js +1 -1
- package/lib/cjs/components/payment_methods/PaymentMethodsContainer.js +1 -1
- package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
- package/lib/cjs/components/payment_source/CheckoutComPayment.js +1 -1
- package/lib/cjs/components/payment_source/StripePayment.js +1 -1
- package/lib/cjs/components/utils/GenericFieldComponent.js +1 -1
- package/lib/cjs/reducers/PaymentMethodReducer.js +1 -1
- package/lib/esm/components/payment_methods/PaymentMethod.js +1 -1
- package/lib/esm/components/payment_methods/PaymentMethodsContainer.js +1 -1
- package/lib/esm/components/payment_source/CheckoutComPayment.js +1 -1
- package/lib/esm/components/payment_source/StripePayment.js +1 -1
- package/lib/esm/reducers/PaymentMethodReducer.js +1 -1
- package/package.json +12 -12
|
@@ -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"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),isEmpty_1=require("../../utils/isEmpty"),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod(_a){var{children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy}=_a,p=tslib_1.__rest(_a,["children","className","activeClass","loader","clickableContainer","autoSelectSinglePaymentMethod","expressPayments","hide","onClick","sortBy"]);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}=(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&&tslib_1.__awaiter(this,void 0,void 0,function*(){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield setPaymentMethod({paymentResource,paymentMethodId});const ps=yield setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&tslib_1.__awaiter(this,void 0,void 0,function*(){if(paymentMethods.length===1){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield 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));const ps=yield setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)}))},[!(0,isEmpty_1.isEmpty)(paymentMethods),order?.payment_source!=null]),(0,react_1.useEffect)(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);const sortedPaymentMethods=paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods,components=sortedPaymentMethods?.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?e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2;e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=(_a2=order?.payment_method)===null||_a2===void 0?void 0:_a2.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=yield setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}):void 0;return(0,jsx_runtime_1.jsx)("div",Object.assign({"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"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),isEmpty_1=require("../../utils/isEmpty"),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod(_a){var{children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy}=_a,p=tslib_1.__rest(_a,["children","className","activeClass","loader","clickableContainer","autoSelectSinglePaymentMethod","expressPayments","hide","onClick","sortBy"]);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}=(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&&tslib_1.__awaiter(this,void 0,void 0,function*(){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield setPaymentMethod({paymentResource,paymentMethodId});const ps=yield setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&tslib_1.__awaiter(this,void 0,void 0,function*(){if(paymentMethods.length===1){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield 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=yield setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)}))},[!(0,isEmpty_1.isEmpty)(paymentMethods),order?.payment_source!=null]),(0,react_1.useEffect)(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);const sortedPaymentMethods=paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods,components=sortedPaymentMethods?.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?e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2;e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=(_a2=order?.payment_method)===null||_a2===void 0?void 0:_a2.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=yield setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}):void 0;return(0,jsx_runtime_1.jsx)("div",Object.assign({"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.PaymentMethodsContainer=PaymentMethodsContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importStar(require("../../context/PaymentMethodContext")),react_1=require("react"),PaymentMethodReducer_1=tslib_1.__importStar(require("../../reducers/PaymentMethodReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),localStorage_1=require("../../utils/localStorage");function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=(0,react_1.useReducer)(PaymentMethodReducer_1.default,PaymentMethodReducer_1.paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=(0,react_1.useContext)(CommerceLayerContext_1.default);function getPayMethods(){return tslib_1.__awaiter(this,void 0,void 0,function*(){order&&(yield(0,PaymentMethodReducer_1.getPaymentMethods)({order,dispatch}))})}(0,react_1.useEffect)(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&(0,isEmpty_1.isEmpty)(state.config)&&(0,PaymentMethodReducer_1.setPaymentMethodConfig)(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethodsContainer=PaymentMethodsContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importStar(require("../../context/PaymentMethodContext")),react_1=require("react"),PaymentMethodReducer_1=tslib_1.__importStar(require("../../reducers/PaymentMethodReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),localStorage_1=require("../../utils/localStorage");function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=(0,react_1.useReducer)(PaymentMethodReducer_1.default,PaymentMethodReducer_1.paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=(0,react_1.useContext)(CommerceLayerContext_1.default);function getPayMethods(){return tslib_1.__awaiter(this,void 0,void 0,function*(){order&&(yield(0,PaymentMethodReducer_1.getPaymentMethods)({order,dispatch}))})}(0,react_1.useEffect)(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&(0,isEmpty_1.isEmpty)(state.config)&&(0,PaymentMethodReducer_1.setPaymentMethodConfig)(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source===null&&((0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})),order?.id&&order?.payment_source==null&&!["draft","pending"].includes(order?.status)&&!state.paymentMethods&&getOrder(order.id)},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({},state),{setLoading:({loading})=>{PaymentMethodContext_1.defaultPaymentMethodContext.setLoading({loading,dispatch})},setPaymentRef:({ref})=>{(0,PaymentMethodReducer_1.setPaymentRef)({ref,dispatch})},setPaymentMethodErrors:errors=>{PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch)},setPaymentMethod:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethod(Object.assign(Object.assign({},args),{config:credentials,updateOrder,order,dispatch,setOrderErrors}))}),setPaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentSource(Object.assign(Object.assign(Object.assign({},state),args),{config:credentials,dispatch,getOrder,updateOrder,order}))}),updatePaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield PaymentMethodContext_1.defaultPaymentMethodContext.updatePaymentSource(Object.assign(Object.assign({},args),{config:credentials,dispatch}))}),destroyPaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield PaymentMethodContext_1.defaultPaymentMethodContext.destroyPaymentSource(Object.assign(Object.assign({},args),{dispatch,config:credentials,updateOrder,orderId:order?.id}))})}),[state]);return(0,jsx_runtime_1.jsx)(PaymentMethodContext_1.default.Provider,{value:contextValue,children})}exports.default=PaymentMethodsContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),auto_1=require("@adyen/adyen-web/auto"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getPublicIp_1=require("../../utils/getPublicIp"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),hasSubscriptions_1=require("../../utils/hasSubscriptions"),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}=Object.assign(Object.assign({},defaultConfig),config),[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),[giftcardError,setGiftcardError]=(0,react_1.useState)(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder}=(0,react_1.useContext)(OrderContext_1.default),{placeOrderButtonRef,setPlaceOrder}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const savePaymentSourceToCustomerWallet=(_b=(_a=e?.elements)===null||_a===void 0?void 0:_a.save_payment_source_to_customer_wallet)===null||_b===void 0?void 0:_b.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1}),handleChange=state=>tslib_1.__awaiter(this,void 0,void 0,function*(){state.isValid&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit(ref.current)}),setPaymentRef({ref}))}),handleOnAdditionalDetails=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&(yield setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes})),resultCode=(_a=pSource?.payment_response)===null||_a===void 0?void 0:_a.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=(_b=pSource?.payment_response)===null||_b===void 0?void 0:_b.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}}),onSubmit=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w;const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=yield(0,getPublicIp_1.getPublicIP)(),control=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=(_a=control?.payment_response)===null||_a===void 0?void 0:_a.resultCode,paymentMethodType=(_d=(_c=(_b=control?.payment_response)===null||_b===void 0?void 0:_b.paymentMethod)===null||_c===void 0?void 0:_c.type)!==null&&_d!==void 0?_d:(_f=(_e=control?.payment_request_data)===null||_e===void 0?void 0:_e.payment_method)===null||_f===void 0?void 0:_f.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:Object.assign(Object.assign({},state.data),{payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:Object.assign({},(0,browserInfo_1.default)())})};delete attributes.payment_request_data.paymentMethod;try{if(yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(["Cancelled","Refused"].includes(controlCode)&&paymentMethodType==="giftcard"&¤tPaymentMethodType2!=="giftcard"){const availableGiftCardAmount=Number.parseInt((_h=(_g=control?.payment_response)===null||_g===void 0?void 0:_g.additionalData)===null||_h===void 0?void 0:_h.currentBalanceValue),totalPartialAmount=order?.total_amount_with_taxes_cents!=null&&availableGiftCardAmount!=null?order?.total_amount_with_taxes_cents-availableGiftCardAmount:0;return yield updateOrder({id:order.id,attributes:{_authorization_amount_cents:totalPartialAmount,_place:!0}}),yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:control?.payment_request_data}}),yield updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),resultCode2=(_j=firstAuthorization?.payment_response)===null||_j===void 0?void 0:_j.resultCode,refusalReasonCode=(_k=firstAuthorization?.payment_response)===null||_k===void 0?void 0:_k.refusalReasonCode,errorCode=(_l=firstAuthorization?.payment_response)===null||_l===void 0?void 0:_l.errorCode;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=(_o=(_m=firstAuthorization?.payment_response)===null||_m===void 0?void 0:_m.refusalReason)!==null&&_o!==void 0?_o:(_p=firstAuthorization?.payment_response)===null||_p===void 0?void 0:_p.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=(_q=res?.payment_response)===null||_q===void 0?void 0:_q.action,resultCode=(_r=res?.payment_response)===null||_r===void 0?void 0:_r.resultCode;if(action!=null)return{resultCode,action};const issuerType=(_s=res?.payment_instrument)===null||_s===void 0?void 0:_s.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(yield setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=(_t=res?.payment_response)===null||_t===void 0?void 0:_t.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if((_u=res?.payment_response)===null||_u===void 0?void 0:_u.errorType)if(((_v=res?.payment_response)===null||_v===void 0?void 0:_v.errorCode)==="14_006")onSubmit(state,component);else{const message=(_w=res?.payment_response)===null||_w===void 0?void 0:_w.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}});return(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;const paymentMethodsResponse={paymentMethods:!((_a=paymentSource?.payment_methods)===null||_a===void 0)&&_a.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:!((_b=paymentSource?.payment_methods)===null||_b===void 0)&&_b.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=(_d=((_c=paymentSource?.payment_methods)===null||_c===void 0?void 0:_c.storedPaymentMethods)!=null)!==null&&_d!==void 0?_d:!1;order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:(_e=order?.language_code)!==null&&_e!==void 0?_e:locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const{resultCode}=yield handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})}))()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2;const{resultCode,action,message}=yield onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?(_a2=dropinRef.current)===null||_a2===void 0||_a2.handleAction(action):(actions.resolve({resultCode}),(_b2=dropinRef.current)===null||_b2===void 0||_b2.mount("#adyen-dropin"),setGiftcardError(null))}))()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2;const checkout2=yield(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:Object.assign({showStoredPaymentMethods,paypal:Object.assign({showPayButton:!0,style:styles?.paypal},(_a2=config?.paymentMethodsConfiguration)===null||_a2===void 0?void 0:_a2.paypal),card:Object.assign({enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1},(_b2=config?.paymentMethodsConfiguration)===null||_b2===void 0?void 0:_b2.card),giftcard:Object.assign({showPayButton:!0},(_c2=config?.paymentMethodsConfiguration)===null||_c2===void 0?void 0:_c2.giftcard)},config?.paymentMethodsConfiguration),onDisableStoredPaymentMethod:state=>{var _a3;const recurringDetailReference=state,shopperReference=(_a3=customers?.shopper_reference)!==null&&_a3!==void 0?_a3:void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit(ref.current)}):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))});dropinRef.current||initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),auto_1=require("@adyen/adyen-web/auto"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getPublicIp_1=require("../../utils/getPublicIp"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),hasSubscriptions_1=require("../../utils/hasSubscriptions"),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}=Object.assign(Object.assign({},defaultConfig),config),[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),[giftcardError,setGiftcardError]=(0,react_1.useState)(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder}=(0,react_1.useContext)(OrderContext_1.default),{placeOrderButtonRef,setPlaceOrder}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const savePaymentSourceToCustomerWallet=(_b=(_a=e?.elements)===null||_a===void 0?void 0:_a.save_payment_source_to_customer_wallet)===null||_b===void 0?void 0:_b.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1}),handleChange=state=>tslib_1.__awaiter(this,void 0,void 0,function*(){state.isValid&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit(ref.current)}),setPaymentRef({ref}))}),handleOnAdditionalDetails=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&(yield setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes})),resultCode=(_a=pSource?.payment_response)===null||_a===void 0?void 0:_a.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=(_b=pSource?.payment_response)===null||_b===void 0?void 0:_b.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}}),onSubmit=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w;const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=yield(0,getPublicIp_1.getPublicIP)(),control=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=(_a=control?.payment_response)===null||_a===void 0?void 0:_a.resultCode,paymentMethodType=(_d=(_c=(_b=control?.payment_response)===null||_b===void 0?void 0:_b.paymentMethod)===null||_c===void 0?void 0:_c.type)!==null&&_d!==void 0?_d:(_f=(_e=control?.payment_request_data)===null||_e===void 0?void 0:_e.payment_method)===null||_f===void 0?void 0:_f.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:Object.assign(Object.assign({},state.data),{payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:Object.assign({},(0,browserInfo_1.default)())})};delete attributes.payment_request_data.paymentMethod;try{if(yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(["Cancelled","Refused"].includes(controlCode)&&paymentMethodType==="giftcard"&¤tPaymentMethodType2!=="giftcard"){const availableGiftCardAmount=Number.parseInt((_h=(_g=control?.payment_response)===null||_g===void 0?void 0:_g.additionalData)===null||_h===void 0?void 0:_h.currentBalanceValue),totalPartialAmount=order?.total_amount_with_taxes_cents!=null&&availableGiftCardAmount!=null?order?.total_amount_with_taxes_cents-availableGiftCardAmount:0;return yield updateOrder({id:order.id,attributes:{_authorization_amount_cents:totalPartialAmount,_place:!0}}),yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:control?.payment_request_data}}),yield updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),resultCode2=(_j=firstAuthorization?.payment_response)===null||_j===void 0?void 0:_j.resultCode,refusalReasonCode=(_k=firstAuthorization?.payment_response)===null||_k===void 0?void 0:_k.refusalReasonCode,errorCode=(_l=firstAuthorization?.payment_response)===null||_l===void 0?void 0:_l.errorCode;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=(_o=(_m=firstAuthorization?.payment_response)===null||_m===void 0?void 0:_m.refusalReason)!==null&&_o!==void 0?_o:(_p=firstAuthorization?.payment_response)===null||_p===void 0?void 0:_p.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=(_q=res?.payment_response)===null||_q===void 0?void 0:_q.action,resultCode=(_r=res?.payment_response)===null||_r===void 0?void 0:_r.resultCode;if(action!=null)return{resultCode,action};const issuerType=(_s=res?.payment_instrument)===null||_s===void 0?void 0:_s.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(yield setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=(_t=res?.payment_response)===null||_t===void 0?void 0:_t.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if((_u=res?.payment_response)===null||_u===void 0?void 0:_u.errorType)if(((_v=res?.payment_response)===null||_v===void 0?void 0:_v.errorCode)==="14_006")onSubmit(state,component);else{const message=(_w=res?.payment_response)===null||_w===void 0?void 0:_w.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}});return(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;const paymentMethodsResponse={paymentMethods:!((_a=paymentSource?.payment_methods)===null||_a===void 0)&&_a.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:!((_b=paymentSource?.payment_methods)===null||_b===void 0)&&_b.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=(_d=((_c=paymentSource?.payment_methods)===null||_c===void 0?void 0:_c.storedPaymentMethods)!=null)!==null&&_d!==void 0?_d:!1;order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:(_e=order?.language_code)!==null&&_e!==void 0?_e:locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{tslib_1.__awaiter(this,void 0,void 0,function*(){const{resultCode}=yield handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2;const{resultCode,action,message}=yield onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?(_a2=dropinRef.current)===null||_a2===void 0||_a2.handleAction(action):(actions.resolve({resultCode}),(_b2=dropinRef.current)===null||_b2===void 0||_b2.mount("#adyen-dropin"),setGiftcardError(null))})}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2;const checkout2=yield(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:Object.assign({showStoredPaymentMethods,paypal:Object.assign({showPayButton:!0,style:styles?.paypal},(_a2=config?.paymentMethodsConfiguration)===null||_a2===void 0?void 0:_a2.paypal),card:Object.assign({enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1},(_b2=config?.paymentMethodsConfiguration)===null||_b2===void 0?void 0:_b2.card),giftcard:Object.assign({showPayButton:!0},(_c2=config?.paymentMethodsConfiguration)===null||_c2===void 0?void 0:_c2.giftcard)},config?.paymentMethodsConfiguration),onDisableStoredPaymentMethod:state=>{var _a3;const recurringDetailReference=state,shopperReference=(_a3=customers?.shopper_reference)!==null&&_a3!==void 0?_a3:void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit(ref.current)}):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))});dropinRef.current||initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
|
|
@@ -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"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);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,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;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=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";
|
|
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"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);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,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;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=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";tslib_1.__awaiter(this,void 0,void 0,function*(){(yield window.CheckoutWebComponents({appearance:Object.assign({},options?.appearance),showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3,_b2;const element=(_a3=ref.current)===null||_a3===void 0?void 0:_a3.elements,savePaymentSourceToCustomerWallet=(_b2=element?.save_payment_source_to_customer_wallet)===null||_b2===void 0?void 0:_b2.checked;savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=yield component.tokenize(),token=data?.token,paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1}),setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:(_component,paymentResponse)=>tslib_1.__awaiter(this,void 0,void 0,function*(){paymentResponse.status.toLowerCase()==="approved"&&(yield 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,(_b=order?.payment_source)===null||_b===void 0?void 0:_b.id,accessToken]),loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({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.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),react_stripe_js_1=require("@stripe/react-stripe-js"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),StripeExpressPayment_1=require("./StripeExpressPayment"),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.useEffect)(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield onSubmit({event:ref.current,stripe,elements})}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=_a=>tslib_1.__awaiter(this,[_a],void 0,function*({event,stripe:stripe2,elements:elements2}){var _b,_c,_d,_e,_f,_g,_h;if(!stripe2)return!1;const savePaymentSourceToCustomerWallet=(_c=(_b=event?.elements)===null||_b===void 0?void 0:_b.save_payment_source_to_customer_wallet)===null||_c===void 0?void 0:_c.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=(_d=order?.customer_email)!==null&&_d!==void 0?_d:"",billingDetails={name:(_e=billingInfo?.full_name)!==null&&_e!==void 0?_e:"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:(_f=billingInfo?.line_2)!==null&&_f!==void 0?_f:"",postal_code:(_g=billingInfo?.zip_code)!==null&&_g!==void 0?_g:"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=yield stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:(_h=error.message)!==null&&_h!==void 0?_h:""}]),!1):!0}return!1});function handleChange(event){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(event.complete){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}})}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:Object.assign(Object.assign({},defaultOptions),options),onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment(_a){var{publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount}=_a,p=tslib_1.__rest(_a,["publishableKey","show","options","clientSecret","locale","expressPayments","connectedAccount"]);const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","fonts","appearance"]);(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),react_stripe_js_1=require("@stripe/react-stripe-js"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),StripeExpressPayment_1=require("./StripeExpressPayment"),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.useEffect)(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield onSubmit({event:ref.current,stripe,elements})}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=_a=>tslib_1.__awaiter(this,[_a],void 0,function*({event,stripe:stripe2,elements:elements2}){var _b,_c,_d,_e,_f,_g,_h;if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1;const savePaymentSourceToCustomerWallet=(_c=(_b=event?.elements)===null||_b===void 0?void 0:_b.save_payment_source_to_customer_wallet)===null||_c===void 0?void 0:_c.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=(_d=order?.customer_email)!==null&&_d!==void 0?_d:"",billingDetails={name:(_e=billingInfo?.full_name)!==null&&_e!==void 0?_e:"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:(_f=billingInfo?.line_2)!==null&&_f!==void 0?_f:"",postal_code:(_g=billingInfo?.zip_code)!==null&&_g!==void 0?_g:"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=yield stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:(_h=error.message)!==null&&_h!==void 0?_h:""}]),!1):!0}return!1});function handleChange(event){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(console.debug("StripePaymentElement onChange event",{event}),event.complete&&["applepay","googlepay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}})}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:Object.assign(Object.assign({},defaultOptions),options),onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment(_a){var{publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount}=_a,p=tslib_1.__rest(_a,["publishableKey","show","options","clientSecret","locale","expressPayments","connectedAccount"]);const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","fonts","appearance"]);(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{tslib_1.__awaiter(this,void 0,void 0,function*(){const options2=Object.assign({locale},connectedAccount?{stripeAccount:connectedAccount}:{}),res=yield loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:Object.assign(Object.assign({},defaultAppearance),appearance),fonts};return isLoaded&&stripe!=null&&clientSecret!=null?(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)(react_stripe_js_1.Elements,{stripe,options:elementsOptions,children:expressPayments?(0,jsx_runtime_1.jsx)(StripeExpressPayment_1.StripeExpressPayment,{clientSecret}):(0,jsx_runtime_1.jsx)(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})})):null}exports.default=StripePayment;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=GenericFieldComponent;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("./Parent")),react_1=require("react"),placeholderImages_1=require("../../utils/placeholderImages");function GenericFieldComponent(props){const{children,tagElement,attribute,context,resource}=props,p=tslib_1.__rest(props,["children","tagElement","attribute","context","resource"]),resourceContext=(0,react_1.useContext)(context);let attributeValue="";const keysContext=Object.keys(resourceContext).filter(key=>key===resource);if(keysContext.length===1){const[keyResource]=keysContext;keyResource&&attribute&&(attributeValue=resourceContext[keyResource][attribute])}const Tag=tagElement||"span";if(Tag==="img"&&!children){const src=attributeValue||placeholderImages_1.defaultImgUrl
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=GenericFieldComponent;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("./Parent")),react_1=require("react"),placeholderImages_1=require("../../utils/placeholderImages");function GenericFieldComponent(props){const{children,tagElement,attribute,context,resource}=props,p=tslib_1.__rest(props,["children","tagElement","attribute","context","resource"]),resourceContext=(0,react_1.useContext)(context);let attributeValue="";const keysContext=Object.keys(resourceContext).filter(key=>key===resource);if(keysContext.length===1){const[keyResource]=keysContext;keyResource&&attribute&&(attributeValue=resourceContext[keyResource][attribute])}const Tag=tagElement||"span";if(Tag==="img"&&!children){const src=attributeValue||placeholderImages_1.defaultImgUrl;return(0,jsx_runtime_1.jsx)("img",Object.assign({alt:"",src},p))}const parentProps=Object.assign({attributeValue,tagElement},p);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)(Tag,Object.assign({"data-testid":attributeValue},p,{children:attributeValue}),attributeValue)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=void 0,exports.setLoading=setLoading,exports.setPaymentMethod=setPaymentMethod,exports.setPaymentSource=setPaymentSource,exports.getPaymentConfig=getPaymentConfig;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),snakeToCamelCase_1=require("../utils/snakeToCamelCase"),replace_1=require("../utils/replace"),pick_1=require("../utils/pick");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({order,dispatch}){const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})});exports.getPaymentMethods=getPaymentMethods;function setPaymentMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=yield updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}})}function setPaymentSource(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){var _b;try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs=Object.assign({id:paymentSourceId},attributes);paymentSource=attributes!=null?yield sdk[paymentResource].update(attrs):yield sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs=Object.assign(Object.assign({},attributes),{order:sdk.orders.relationship(order.id)});paymentSource=yield sdk[paymentResource].create(attrs)}return getOrder&&(yield getOrder(order.id)),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=yield updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:(_b=orderUpdated.payment_source)===null||_b===void 0?void 0:_b.id}})}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=yield getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}})}const updatePaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({id,attributes,config,dispatch,paymentResource}){if(config)try{const paymentSource=yield(0,getSdk_1.default)(config)[paymentResource].update(Object.assign({id},attributes));dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}});exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({paymentSourceId,paymentResource,dispatch}){paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})});exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=void 0,exports.setLoading=setLoading,exports.setPaymentMethod=setPaymentMethod,exports.setPaymentSource=setPaymentSource,exports.getPaymentConfig=getPaymentConfig;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),snakeToCamelCase_1=require("../utils/snakeToCamelCase"),replace_1=require("../utils/replace"),pick_1=require("../utils/pick");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({order,dispatch}){const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})});exports.getPaymentMethods=getPaymentMethods;function setPaymentMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=yield updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}})}function setPaymentSource(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){var _b;try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs=Object.assign({id:paymentSourceId},attributes);paymentSource=attributes!=null?yield sdk[paymentResource].update(attrs):yield sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs=Object.assign(Object.assign({},attributes),{order:sdk.orders.relationship(order.id)});paymentSource=yield sdk[paymentResource].create(attrs)}return getOrder&&(yield getOrder(order.id)),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=yield updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:(_b=orderUpdated.payment_source)===null||_b===void 0?void 0:_b.id}})}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource});if(console.error("Set payment source:",errors),errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=yield getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}})}const updatePaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({id,attributes,config,dispatch,paymentResource}){if(config)try{const paymentSource=yield(0,getSdk_1.default)(config)[paymentResource].update(Object.assign({id},attributes));dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}});exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({paymentSourceId,paymentResource,dispatch}){paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})});exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useState,useEffect,useContext}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import useCustomContext from"../../utils/hooks/useCustomContext";import OrderContext from"../../context/OrderContext";import CustomerContext from"../../context/CustomerContext";import{getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import{isEmpty}from"../../utils/isEmpty";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import PlaceOrderContext from"../../context/PlaceOrderContext";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config}=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(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{if(paymentMethods.length===1){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));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)})())},[!isEmpty(paymentMethods),order?.payment_source!=null]),useEffect(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);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{useState,useEffect,useContext}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import useCustomContext from"../../utils/hooks/useCustomContext";import OrderContext from"../../context/OrderContext";import CustomerContext from"../../context/CustomerContext";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import{isEmpty}from"../../utils/isEmpty";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import PlaceOrderContext from"../../context/PlaceOrderContext";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config}=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(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{if(paymentMethods.length===1){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(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)})())},[!isEmpty(paymentMethods),order?.payment_source!=null]),useEffect(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);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}from"react/jsx-runtime";import PaymentMethodContext,{defaultPaymentMethodContext}from"../../context/PaymentMethodContext";import{useContext,useEffect,useReducer,useMemo}from"react";import paymentMethodReducer,{paymentMethodInitialState,getPaymentMethods,setPaymentMethodConfig,setPaymentRef}from"../../reducers/PaymentMethodReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{setCustomerOrderParam}from"../../utils/localStorage";export function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=useReducer(paymentMethodReducer,paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=useContext(CommerceLayerContext);async function getPayMethods(){order&&await getPaymentMethods({order,dispatch})}useEffect(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&isEmpty(state.config)&&setPaymentMethodConfig(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext,{defaultPaymentMethodContext}from"../../context/PaymentMethodContext";import{useContext,useEffect,useReducer,useMemo}from"react";import paymentMethodReducer,{paymentMethodInitialState,getPaymentMethods,setPaymentMethodConfig,setPaymentRef}from"../../reducers/PaymentMethodReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{setCustomerOrderParam}from"../../utils/localStorage";export function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=useReducer(paymentMethodReducer,paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=useContext(CommerceLayerContext);async function getPayMethods(){order&&await getPaymentMethods({order,dispatch})}useEffect(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&isEmpty(state.config)&&setPaymentMethodConfig(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source===null&&(setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})),order?.id&&order?.payment_source==null&&!["draft","pending"].includes(order?.status)&&!state.paymentMethods&&getOrder(order.id)},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=useMemo(()=>({...state,setLoading:({loading})=>{defaultPaymentMethodContext.setLoading({loading,dispatch})},setPaymentRef:({ref})=>{setPaymentRef({ref,dispatch})},setPaymentMethodErrors:errors=>{defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch)},setPaymentMethod:async args=>await defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>{await defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch})},destroyPaymentSource:async args=>{await defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}}),[state]);return _jsx(PaymentMethodContext.Provider,{value:contextValue,children})}export default PaymentMethodsContainer;
|
|
@@ -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 useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import PlaceOrderContext from"../../context/PlaceOrderContext";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,successUrl=window.location.href,failureUrl=window.location.href,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=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:async(_component,paymentResponse)=>{
|
|
2
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import PlaceOrderContext from"../../context/PlaceOrderContext";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,successUrl=window.location.href,failureUrl=window.location.href,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=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:async(_component,paymentResponse)=>{paymentResponse.status.toLowerCase()==="approved"&&(await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import OrderContext from"../../context/OrderContext";import{StripeExpressPayment}from"./StripeExpressPayment";import useCommerceLayer from"../../hooks/useCommerceLayer";import PlaceOrderContext from"../../context/PlaceOrderContext";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(event.complete){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
|
|
2
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import OrderContext from"../../context/OrderContext";import{StripeExpressPayment}from"./StripeExpressPayment";import useCommerceLayer from"../../hooks/useCommerceLayer";import PlaceOrderContext from"../../context/PlaceOrderContext";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1;const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),event.complete&&["applepay","googlepay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{snakeToCamelCase}from"../utils/snakeToCamelCase";import{replace}from"../utils/replace";import{pick}from"../utils/pick";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=await updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=getSdk(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{snakeToCamelCase}from"../utils/snakeToCamelCase";import{replace}from"../utils/replace";import{pick}from"../utils/pick";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=await updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=getSdk(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource});if(console.error("Set payment source:",errors),errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}else setErrors({currentErrors,newErrors:errors,dispatch})}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commercelayer/react-components",
|
|
3
|
-
"version": "4.24.1-beta.
|
|
3
|
+
"version": "4.24.1-beta.4",
|
|
4
4
|
"description": "The Official Commerce Layer React Components",
|
|
5
5
|
"main": "lib/cjs/index.js",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -186,14 +186,14 @@
|
|
|
186
186
|
},
|
|
187
187
|
"homepage": "https://github.com/commercelayer/commercelayer-react-components#readme",
|
|
188
188
|
"dependencies": {
|
|
189
|
-
"@adyen/adyen-web": "^6.
|
|
189
|
+
"@adyen/adyen-web": "^6.17.0",
|
|
190
190
|
"@commercelayer/organization-config": "^2.3.0",
|
|
191
|
-
"@commercelayer/sdk": "^6.
|
|
191
|
+
"@commercelayer/sdk": "^6.44.0",
|
|
192
192
|
"@stripe/react-stripe-js": "^3.7.0",
|
|
193
193
|
"@stripe/stripe-js": "^7.3.1",
|
|
194
194
|
"@tanstack/react-table": "^8.21.3",
|
|
195
195
|
"@types/iframe-resizer": "^3.5.13",
|
|
196
|
-
"braintree-web": "^3.
|
|
196
|
+
"braintree-web": "^3.123.0",
|
|
197
197
|
"frames-react": "^1.2.2",
|
|
198
198
|
"iframe-resizer": "^4.3.6",
|
|
199
199
|
"jwt-decode": "^4.0.0",
|
|
@@ -203,21 +203,21 @@
|
|
|
203
203
|
"devDependencies": {
|
|
204
204
|
"@commercelayer/js-auth": "^6.7.2",
|
|
205
205
|
"@faker-js/faker": "^9.8.0",
|
|
206
|
-
"@playwright/test": "^1.
|
|
206
|
+
"@playwright/test": "^1.53.1",
|
|
207
207
|
"@testing-library/dom": "^10.4.0",
|
|
208
208
|
"@testing-library/react": "^16.3.0",
|
|
209
209
|
"@types/braintree-web": "^3.96.17",
|
|
210
|
-
"@types/lodash": "^4.17.
|
|
211
|
-
"@types/node": "^
|
|
212
|
-
"@types/prop-types": "^15.7.
|
|
210
|
+
"@types/lodash": "^4.17.18",
|
|
211
|
+
"@types/node": "^24.0.3",
|
|
212
|
+
"@types/prop-types": "^15.7.15",
|
|
213
213
|
"@types/react": "^18.3.1",
|
|
214
214
|
"@types/react-test-renderer": "^18.3.1",
|
|
215
215
|
"@types/react-window": "^1.8.8",
|
|
216
|
-
"@vitejs/plugin-react": "^4.5.
|
|
217
|
-
"@vitest/coverage-v8": "^3.2.
|
|
216
|
+
"@vitejs/plugin-react": "^4.5.2",
|
|
217
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
218
218
|
"jsdom": "^26.1.0",
|
|
219
219
|
"minimize-js": "^1.4.0",
|
|
220
|
-
"msw": "^2.
|
|
220
|
+
"msw": "^2.10.2",
|
|
221
221
|
"react": "^18.3.1",
|
|
222
222
|
"react-dom": "^18.3.1",
|
|
223
223
|
"react-test-renderer": "^18.3.1",
|
|
@@ -226,7 +226,7 @@
|
|
|
226
226
|
"typescript": "^5.8.3",
|
|
227
227
|
"vite": "^6.3.5",
|
|
228
228
|
"vite-tsconfig-paths": "^5.1.4",
|
|
229
|
-
"vitest": "^3.2.
|
|
229
|
+
"vitest": "^3.2.4"
|
|
230
230
|
},
|
|
231
231
|
"peerDependencies": {
|
|
232
232
|
"react": ">=18.0.0"
|