@commercelayer/react-components 4.25.5 → 4.25.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){var _a,_b,_c,_d,_e,_f,_g;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,((_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit)!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e2,_f2;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const paymentDetails=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_request_details)===null||_b2===void 0?void 0:_b2.details)!=null;if(paymentType==="adyen_payments"&&(!((_c2=options?.adyen)===null||_c2===void 0)&&_c2.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_d2=options?.adyen)===null||_d2===void 0?void 0:_d2.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&(!((_e2=options?.adyen)===null||_e2===void 0)&&_e2.MD)&&(!((_f2=options?.adyen)===null||_f2===void 0)&&_f2.PaRes)&&autoPlaceOrder&&handleClick()}},[((_c=options?.adyen)===null||_c===void 0?void 0:_c.MD)!=null,paymentType!=null,(_e=(_d=order?.payment_source)===null||_d===void 0?void 0:_d.payment_response)===null||_e===void 0?void 0:_e.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentResponse=(_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.payment_response,paymentStatus=paymentResponse?.status;paymentStatus&&paymentStatus.toLowerCase()==="pending"&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3;const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}),paymentStatus2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})}()}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=(_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_response)===null||_d2===void 0?void 0:_d2.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[(_f=options?.checkoutCom)===null||_f===void 0?void 0:_f.session_id,(_g=order?.payment_source)===null||_g===void 0?void 0:_g.id]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k,_l;e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=yield sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e2=checkPaymentSource?.payment_response)===null||_e2===void 0?void 0:_e2.resultCode)==="Authorised"&&(isValid=!0)):!((_f2=currentPaymentMethodRef?.current)===null||_f2===void 0)&&_f2.onsubmit&&(!((_g2=options?.checkoutCom)===null||_g2===void 0)&&_g2.session_id)&&(!((_h=checkPaymentSource?.payment_response)===null||_h===void 0)&&_h.status)&&((_k=(_j=checkPaymentSource?.payment_response)===null||_j===void 0?void 0:_j.status)===null||_k===void 0?void 0:_k.toLowerCase())==="declined"?isValid=yield(_l=currentPaymentMethodRef.current)===null||_l===void 0?void 0:_l.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){var _a,_b,_c,_d,_e,_f,_g;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,((_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit)!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e2=options?.adyen)===null||_e2===void 0)&&_e2.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f2=options?.adyen)===null||_f2===void 0?void 0:_f2.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!(!((_g2=options?.adyen)===null||_g2===void 0)&&_g2.redirectResult)&&!((_k=(_j=(_h=order?.payment_source)===null||_h===void 0?void 0:_h.payment_response)===null||_j===void 0?void 0:_j.merchantReference)===null||_k===void 0)&&_k.includes(order?.number)&&handleClick()}},[((_c=options?.adyen)===null||_c===void 0?void 0:_c.redirectResult)!=null,(_e=(_d=order?.payment_source)===null||_d===void 0?void 0:_d.payment_response)===null||_e===void 0?void 0:_e.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentResponse=(_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.payment_response,paymentStatus=paymentResponse?.status;paymentStatus&&paymentStatus.toLowerCase()==="pending"&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3;const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}),paymentStatus2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})}()}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=(_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_response)===null||_d2===void 0?void 0:_d2.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[(_f=options?.checkoutCom)===null||_f===void 0?void 0:_f.session_id,(_g=order?.payment_source)===null||_g===void 0?void 0:_g.id]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k,_l;e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=yield sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e2=checkPaymentSource?.payment_response)===null||_e2===void 0?void 0:_e2.resultCode)==="Authorised"&&(isValid=!0)):!((_f2=currentPaymentMethodRef?.current)===null||_f2===void 0)&&_f2.onsubmit&&(!((_g2=options?.checkoutCom)===null||_g2===void 0)&&_g2.session_id)&&(!((_h=checkPaymentSource?.payment_response)===null||_h===void 0)&&_h.status)&&((_k=(_j=checkPaymentSource?.payment_response)===null||_j===void 0?void 0:_j.status)===null||_k===void 0?void 0:_k.toLowerCase())==="declined"?isValid=yield(_l=currentPaymentMethodRef.current)===null||_l===void 0?void 0:_l.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
@@ -1,5 +1,5 @@
1
- import type { GatewayBaseType } from "../payment_gateways/PaymentGateway";
2
1
  import { type JSX } from "react";
2
+ import type { GatewayBaseType } from "../payment_gateways/PaymentGateway";
3
3
  type Props = GatewayBaseType;
4
4
  export declare function AdyenGateway(props: Props): JSX.Element | null;
5
5
  export default AdyenGateway;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenGateway=AdyenGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentSourceContext_1=tslib_1.__importDefault(require("../../context/PaymentSourceContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),react_1=require("react"),AdyenPayment_1=tslib_1.__importDefault(require("../payment_source/AdyenPayment")),PaymentCardsTemplate_1=tslib_1.__importDefault(require("../utils/PaymentCardsTemplate")),jwt_1=require("../../utils/jwt"),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),hasSubscriptions_1=require("../../utils/hasSubscriptions");function AdyenGateway(props){var _a,_b;const{readonly,showCard,handleEditClick,children,templateCustomerCards,loading,loaderComponent,templateCustomerSaveToWallet}=props,p=tslib_1.__rest(props,["readonly","showCard","handleEditClick","children","templateCustomerCards","loading","loaderComponent","templateCustomerSaveToWallet"]),{order}=(0,react_1.useContext)(OrderContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{payment}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{payments,isGuest}=(0,react_1.useContext)(CustomerContext_1.default),{currentPaymentMethodId,config,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource="adyen_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const clientKey=paymentSource?.public_key,environment=accessToken&&(0,jwt_1.jwt)(accessToken).test?"test":"live",adyenConfig=(0,getPaymentAttributes_1.getPaymentAttributes)({resource:paymentResource,config:config??{},keys:["adyen_payments"]}),paymentConfig=adyenConfig?.adyenPayment;let customerPayments=!(0,isEmpty_1.default)(payments)&&payments?payments.filter(customerPayment=>{var _a2;return((_a2=customerPayment.payment_source)===null||_a2===void 0?void 0:_a2.type)==="adyen_payments"||customerPayment.payment_method!=null}):[];if(readonly||showCard){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value=Object.assign(Object.assign({},card),{showCard,handleEditClick,readonly});return(0,isEmpty_1.default)(card)?null:(0,jsx_runtime_1.jsx)(PaymentSourceContext_1.default.Provider,{value,children})}let hasStoredPaymentMethods=((_a=paymentSource?.payment_methods)===null||_a===void 0?void 0:_a.storedPaymentMethods)!=null&&((_b=paymentSource?.payment_methods)===null||_b===void 0?void 0:_b.storedPaymentMethods.length)>0;return order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(hasStoredPaymentMethods=!1,customerPayments=[]),!isGuest&&templateCustomerCards?(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[hasStoredPaymentMethods||(0,isEmpty_1.default)(customerPayments)?null:(0,jsx_runtime_1.jsx)("div",{className:p.className,children:(0,jsx_runtime_1.jsx)(PaymentCardsTemplate_1.default,{paymentResource,customerPayments,children:templateCustomerCards})}),(0,jsx_runtime_1.jsx)(AdyenPayment_1.default,{templateCustomerSaveToWallet,clientKey,locale,environment,config:paymentConfig})]}):(0,jsx_runtime_1.jsx)(AdyenPayment_1.default,{clientKey,locale,config:paymentConfig,environment})}exports.default=AdyenGateway;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenGateway=AdyenGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),react_1=require("react"),AdyenPayment_1=tslib_1.__importDefault(require("../payment_source/AdyenPayment")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentSourceContext_1=tslib_1.__importDefault(require("../../context/PaymentSourceContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),hasSubscriptions_1=require("../../utils/hasSubscriptions"),jwt_1=require("../../utils/jwt"),PaymentCardsTemplate_1=tslib_1.__importDefault(require("../utils/PaymentCardsTemplate"));function AdyenGateway(props){var _a,_b;const{readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet}=props,p=tslib_1.__rest(props,["readonly","showCard","handleEditClick","children","templateCustomerCards","templateCustomerSaveToWallet"]),{order}=(0,react_1.useContext)(OrderContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{payment}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{payments,isGuest}=(0,react_1.useContext)(CustomerContext_1.default),{currentPaymentMethodId,config,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource="adyen_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const clientKey=paymentSource?.public_key,environment=accessToken&&(0,jwt_1.jwt)(accessToken).test?"test":"live",adyenConfig=(0,getPaymentAttributes_1.getPaymentAttributes)({resource:paymentResource,config:config??{},keys:["adyen_payments"]}),paymentConfig=adyenConfig?.adyenPayment;let customerPayments=!(0,isEmpty_1.default)(payments)&&payments?payments.filter(customerPayment=>{var _a2;return((_a2=customerPayment.payment_source)===null||_a2===void 0?void 0:_a2.type)==="adyen_payments"||customerPayment.payment_method!=null}):[];if(readonly||showCard){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value=Object.assign(Object.assign({},card),{showCard,handleEditClick,readonly});return(0,isEmpty_1.default)(card)?null:(0,jsx_runtime_1.jsx)(PaymentSourceContext_1.default.Provider,{value,children})}let hasStoredPaymentMethods=((_a=paymentSource?.payment_methods)===null||_a===void 0?void 0:_a.storedPaymentMethods)!=null&&((_b=paymentSource?.payment_methods)===null||_b===void 0?void 0:_b.storedPaymentMethods.length)>0;return order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(hasStoredPaymentMethods=!1,customerPayments=[]),!isGuest&&templateCustomerCards?(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[hasStoredPaymentMethods||(0,isEmpty_1.default)(customerPayments)?null:(0,jsx_runtime_1.jsx)("div",{className:p.className,children:(0,jsx_runtime_1.jsx)(PaymentCardsTemplate_1.default,{paymentResource,customerPayments,children:templateCustomerCards})}),(0,jsx_runtime_1.jsx)(AdyenPayment_1.default,{templateCustomerSaveToWallet,clientKey,locale,environment,config:paymentConfig})]}):(0,jsx_runtime_1.jsx)(AdyenPayment_1.default,{clientKey,locale,config:paymentConfig,environment})}exports.default=AdyenGateway;
@@ -1,6 +1,6 @@
1
+ import { type CardConfiguration, type CoreConfiguration, type DropinConfiguration, type PayPalConfiguration, type UIElement, type UIElementProps } from "@adyen/adyen-web/auto";
1
2
  import { type JSX } from "react";
2
3
  import type { PaymentSourceProps } from "./PaymentSource";
3
- import { type CardConfiguration, type CoreConfiguration, type DropinConfiguration, type PayPalConfiguration, type UIElement, type UIElementProps } from "@adyen/adyen-web/auto";
4
4
  interface PaymentMethodsStyle {
5
5
  card?: CardConfiguration["styles"];
6
6
  paypal?: PayPalConfiguration["style"];
@@ -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"&&currentPaymentMethodType2!=="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"),auto_1=require("@adyen/adyen-web/auto"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),getPublicIp_1=require("../../utils/getPublicIp"),hasSubscriptions_1=require("../../utils/hasSubscriptions"),localStorage_1=require("../../utils/localStorage"),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,status}=(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"&&currentPaymentMethodType2!=="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))}),html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!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.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),customerOrderOptions_1=require("../utils/customerOrderOptions"),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),hasSubscriptions_1=require("../utils/hasSubscriptions"),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),shipments_1=require("../utils/shipments"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(console.log("Saving billing address to customer address book",{order}),yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(console.log("Saving shipping address to customer address book",{order}),yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_b=ps?.options)===null||_b===void 0?void 0:_b.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_c=order?.total_amount_cents)!==null&&_c!==void 0?_c:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_d=orderUpdated?.total_amount_cents)!==null&&_d!==void 0?_d:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),customerOrderOptions_1=require("../utils/customerOrderOptions"),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),hasSubscriptions_1=require("../utils/hasSubscriptions"),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),shipments_1=require("../utils/shipments"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_b=ps?.options)===null||_b===void 0?void 0:_b.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_c=order?.total_amount_cents)!==null&&_c!==void 0?_c:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_d=orderUpdated?.total_amount_cents)!==null&&_d!==void 0?_d:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder&&handleClick()}},[options?.adyen?.MD!=null,paymentType!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
@@ -1,5 +1,5 @@
1
- import type { GatewayBaseType } from "../payment_gateways/PaymentGateway";
2
1
  import { type JSX } from "react";
2
+ import type { GatewayBaseType } from "../payment_gateways/PaymentGateway";
3
3
  type Props = GatewayBaseType;
4
4
  export declare function AdyenGateway(props: Props): JSX.Element | null;
5
5
  export default AdyenGateway;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentSourceContext from"../../context/PaymentSourceContext";import isEmpty from"lodash/isEmpty";import{useContext}from"react";import AdyenPayment from"../payment_source/AdyenPayment";import PaymentCardsTemplate from"../utils/PaymentCardsTemplate";import{jwt}from"../../utils/jwt";import getCardDetails from"../../utils/getCardDetails";import{getPaymentAttributes}from"../../utils/getPaymentAttributes";import{hasSubscriptions}from"../../utils/hasSubscriptions";export function AdyenGateway(props){const{readonly,showCard,handleEditClick,children,templateCustomerCards,loading,loaderComponent,templateCustomerSaveToWallet,...p}=props,{order}=useContext(OrderContext),{accessToken}=useContext(CommerceLayerContext),{payment}=useContext(PaymentMethodChildrenContext),{payments,isGuest}=useContext(CustomerContext),{currentPaymentMethodId,config,paymentSource}=useContext(PaymentMethodContext),paymentResource="adyen_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const clientKey=paymentSource?.public_key,environment=accessToken&&jwt(accessToken).test?"test":"live",paymentConfig=getPaymentAttributes({resource:paymentResource,config:config??{},keys:["adyen_payments"]})?.adyenPayment;let customerPayments=!isEmpty(payments)&&payments?payments.filter(customerPayment=>customerPayment.payment_source?.type==="adyen_payments"||customerPayment.payment_method!=null):[];if(readonly||showCard){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value={...card,showCard,handleEditClick,readonly};return isEmpty(card)?null:_jsx(PaymentSourceContext.Provider,{value,children})}let hasStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null&&paymentSource?.payment_methods?.storedPaymentMethods.length>0;return order&&hasSubscriptions(order)&&(hasStoredPaymentMethods=!1,customerPayments=[]),!isGuest&&templateCustomerCards?_jsxs(_Fragment,{children:[hasStoredPaymentMethods||isEmpty(customerPayments)?null:_jsx("div",{className:p.className,children:_jsx(PaymentCardsTemplate,{paymentResource,customerPayments,children:templateCustomerCards})}),_jsx(AdyenPayment,{templateCustomerSaveToWallet,clientKey,locale,environment,config:paymentConfig})]}):_jsx(AdyenPayment,{clientKey,locale,config:paymentConfig,environment})}export default AdyenGateway;
2
+ import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";import isEmpty from"lodash/isEmpty";import{useContext}from"react";import AdyenPayment from"../payment_source/AdyenPayment";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentSourceContext from"../../context/PaymentSourceContext";import getCardDetails from"../../utils/getCardDetails";import{getPaymentAttributes}from"../../utils/getPaymentAttributes";import{hasSubscriptions}from"../../utils/hasSubscriptions";import{jwt}from"../../utils/jwt";import PaymentCardsTemplate from"../utils/PaymentCardsTemplate";export function AdyenGateway(props){const{readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,...p}=props,{order}=useContext(OrderContext),{accessToken}=useContext(CommerceLayerContext),{payment}=useContext(PaymentMethodChildrenContext),{payments,isGuest}=useContext(CustomerContext),{currentPaymentMethodId,config,paymentSource}=useContext(PaymentMethodContext),paymentResource="adyen_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const clientKey=paymentSource?.public_key,environment=accessToken&&jwt(accessToken).test?"test":"live",paymentConfig=getPaymentAttributes({resource:paymentResource,config:config??{},keys:["adyen_payments"]})?.adyenPayment;let customerPayments=!isEmpty(payments)&&payments?payments.filter(customerPayment=>customerPayment.payment_source?.type==="adyen_payments"||customerPayment.payment_method!=null):[];if(readonly||showCard){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value={...card,showCard,handleEditClick,readonly};return isEmpty(card)?null:_jsx(PaymentSourceContext.Provider,{value,children})}let hasStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null&&paymentSource?.payment_methods?.storedPaymentMethods.length>0;return order&&hasSubscriptions(order)&&(hasStoredPaymentMethods=!1,customerPayments=[]),!isGuest&&templateCustomerCards?_jsxs(_Fragment,{children:[hasStoredPaymentMethods||isEmpty(customerPayments)?null:_jsx("div",{className:p.className,children:_jsx(PaymentCardsTemplate,{paymentResource,customerPayments,children:templateCustomerCards})}),_jsx(AdyenPayment,{templateCustomerSaveToWallet,clientKey,locale,environment,config:paymentConfig})]}):_jsx(AdyenPayment,{clientKey,locale,config:paymentConfig,environment})}export default AdyenGateway;
@@ -1,6 +1,6 @@
1
+ import { type CardConfiguration, type CoreConfiguration, type DropinConfiguration, type PayPalConfiguration, type UIElement, type UIElementProps } from "@adyen/adyen-web/auto";
1
2
  import { type JSX } from "react";
2
3
  import type { PaymentSourceProps } from "./PaymentSource";
3
- import { type CardConfiguration, type CoreConfiguration, type DropinConfiguration, type PayPalConfiguration, type UIElement, type UIElementProps } from "@adyen/adyen-web/auto";
4
4
  interface PaymentMethodsStyle {
5
5
  card?: CardConfiguration["styles"];
6
6
  paypal?: PayPalConfiguration["style"];
@@ -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{setCustomerOrderParam}from"../../utils/localStorage";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import Parent from"../utils/Parent";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import{getPublicIP}from"../../utils/getPublicIp";import CustomerContext from"../../context/CustomerContext";import{hasSubscriptions}from"../../utils/hasSubscriptions";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),[giftcardError,setGiftcardError]=useState(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder}=useContext(OrderContext),{placeOrderButtonRef,setPlaceOrder}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.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=pSource?.payment_response?.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=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:{...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:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await 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"&&currentPaymentMethodType2!=="giftcard"){const availableGiftCardAmount=Number.parseInt(control?.payment_response?.additionalData?.currentBalanceValue),totalPartialAmount=order?.total_amount_with_taxes_cents!=null&&availableGiftCardAmount!=null?order?.total_amount_with_taxes_cents-availableGiftCardAmount:0;return await updateOrder({id:order.id,attributes:{_authorization_amount_cents:totalPartialAmount,_place:!0}}),await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:control?.payment_request_data}}),await updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),resultCode2=firstAuthorization?.payment_response?.resultCode,refusalReasonCode=firstAuthorization?.payment_response?.refusalReasonCode,errorCode=firstAuthorization?.payment_response?.errorCode;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=firstAuthorization?.payment_response?.refusalReason??firstAuthorization?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await 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=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.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 useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&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:order?.language_code??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)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??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=async()=>await 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:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import{getPublicIP}from"../../utils/getPublicIp";import{hasSubscriptions}from"../../utils/hasSubscriptions";import{setCustomerOrderParam}from"../../utils/localStorage";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),[giftcardError,setGiftcardError]=useState(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder}=useContext(OrderContext),{placeOrderButtonRef,setPlaceOrder,status}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.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=pSource?.payment_response?.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=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:{...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:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await 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"&&currentPaymentMethodType2!=="giftcard"){const availableGiftCardAmount=Number.parseInt(control?.payment_response?.additionalData?.currentBalanceValue),totalPartialAmount=order?.total_amount_with_taxes_cents!=null&&availableGiftCardAmount!=null?order?.total_amount_with_taxes_cents-availableGiftCardAmount:0;return await updateOrder({id:order.id,attributes:{_authorization_amount_cents:totalPartialAmount,_place:!0}}),await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:control?.payment_request_data}}),await updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),resultCode2=firstAuthorization?.payment_response?.resultCode,refusalReasonCode=firstAuthorization?.payment_response?.refusalReasonCode,errorCode=firstAuthorization?.payment_response?.errorCode;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=firstAuthorization?.payment_response?.refusalReason??firstAuthorization?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await 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=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.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 useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&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:order?.language_code??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)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??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=async()=>await 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))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getErrors from"../utils/getErrors";import getSdk from"../utils/getSdk";import{hasSubscriptions}from"../utils/hasSubscriptions";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&(console.log("Saving billing address to customer address book",{order}),await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),saveShippingAddress()&&(console.log("Saving shipping address to customer address book",{order}),await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
2
+ import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getErrors from"../utils/getErrors";import getSdk from"../utils/getSdk";import{hasSubscriptions}from"../utils/hasSubscriptions";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.25.5",
3
+ "version": "4.25.6",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",