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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ /** biome-ignore-all lint/correctness/useExhaustiveDependencies: Avoid infinite loop */
1
2
  import type { Order } from "@commercelayer/sdk";
2
3
  import { type JSX, type ReactNode } from "react";
3
4
  import type { BaseError } from "../../typings/errors";
@@ -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){const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{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,errors:paymentMethodErrors}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase(),card=(0,getCardDetails_1.default)({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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),(0,react_1.useEffect)(()=>{errors&&errors.length>0||paymentMethodErrors&&paymentMethodErrors.length>0?(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1)):setNotPermitted(!1)},[errors?.length,paymentMethodErrors?.length]),(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)(()=>{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(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()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.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,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.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)(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),(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=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase(),card=paymentType&&(0,getCardDetails_1.default)({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&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("button",{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){const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{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,errors:paymentMethodErrors}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase?.(),card=(0,getCardDetails_1.default)({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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),(0,react_1.useEffect)(()=>{errors&&errors.length>0||paymentMethodErrors&&paymentMethodErrors.length>0?(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1)):setNotPermitted(!1)},[errors?.length,paymentMethodErrors?.length]),(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)(()=>{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(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()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.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,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.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)(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),(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=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase?.(),card=paymentType&&(0,getCardDetails_1.default)({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&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}exports.default=PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethod=PaymentMethod;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=(0,react_1.useState)(!0),[paymentSelected,setPaymentSelected]=(0,react_1.useState)(""),[paymentSourceCreated,setPaymentSourceCreated]=(0,react_1.useState)(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=(0,useCustomContext_1.default)({context:PaymentMethodContext_1.default,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default);(0,react_1.useEffect)(()=>{if(paymentMethods!=null&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&expressPayments){const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments,errors?.length]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!(0,isEmpty_1.isEmpty)(paymentMethods),errors?.length]),(0,react_1.useEffect)(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),(0,react_1.useEffect)(()=>{const status2=order?.payment_source?.payment_response?.status?.toLowerCase();showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return(0,jsx_runtime_1.jsx)("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:(0,jsx_runtime_1.jsx)(PaymentMethodChildrenContext_1.default.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?(0,getLoaderComponent_1.default)(loader):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.default=PaymentMethod;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethod=PaymentMethod;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=(0,react_1.useState)(!0),[paymentSelected,setPaymentSelected]=(0,react_1.useState)(""),[paymentSourceCreated,setPaymentSourceCreated]=(0,react_1.useState)(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=(0,useCustomContext_1.default)({context:PaymentMethodContext_1.default,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default);(0,react_1.useEffect)(()=>{if(paymentMethods!=null&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&expressPayments){const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments,errors?.length]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase?.():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!(0,isEmpty_1.isEmpty)(paymentMethods),errors?.length]),(0,react_1.useEffect)(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase?.():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),(0,react_1.useEffect)(()=>{const status2=order?.payment_source?.payment_response?.status;showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return(0,jsx_runtime_1.jsx)("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:(0,jsx_runtime_1.jsx)(PaymentMethodChildrenContext_1.default.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?(0,getLoaderComponent_1.default)(loader):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.default=PaymentMethod;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.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")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),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}={...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,getOrderByFields}=(0,react_1.useContext)(OrderContext_1.default),authConfig=(0,react_1.useContext)(CommerceLayerContext_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=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.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=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await(0,getPublicIp_1.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,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")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:{...(0,browserInfo_1.default)()}}};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(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}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(0,react_1.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&&(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: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,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.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=async()=>{const checkout2=await(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.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&&id.search("giftcard")===-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:(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")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),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}={...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,getOrderByFields}=(0,react_1.useContext)(OrderContext_1.default),authConfig=(0,react_1.useContext)(CommerceLayerContext_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=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.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),setPaymentMethodErrors([]),setPaymentRef({ref}),placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled=!1))},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=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await(0,getPublicIp_1.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,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")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:{...(0,browserInfo_1.default)()}}};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(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}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(0,react_1.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&&(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: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,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.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=async()=>{const checkout2=await(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.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,isValid=component.isValid;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1&&id.search("giftcard")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentMethodErrors([]),setPaymentRef({ref}),placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled=!1)),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,setPaymentMethodErrors!=null]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
@@ -1,3 +1,4 @@
1
+ /** biome-ignore-all lint/correctness/useExhaustiveDependencies: Avoid infinite loop */
1
2
  import { type JSX } from "react";
2
3
  import type { LoaderType } from "../../typings/index";
3
4
  import type { CustomerCardsTemplateChildren } from "../utils/PaymentCardsTemplate";
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentSource=PaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),PaymentGateway_1=tslib_1.__importDefault(require("../payment_gateways/PaymentGateway"));function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{payments}=(0,react_1.useContext)(CustomerContext_1.default),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),[show,setShow]=(0,react_1.useState)(!1),[showCard,setShowCard]=(0,react_1.useState)(!1);(0,react_1.useEffect)(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&&currentCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=(0,getCardDetails_1.default)({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&card.brand!=="giftcard"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&&currentPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return(0,jsx_runtime_1.jsx)(PaymentGateway_1.default,{...gatewayProps})}exports.default=PaymentSource;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentSource=PaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),PaymentGateway_1=tslib_1.__importDefault(require("../payment_gateways/PaymentGateway"));function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{payments}=(0,react_1.useContext)(CustomerContext_1.default),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),[show,setShow]=(0,react_1.useState)(!1),[showCard,setShowCard]=(0,react_1.useState)(!1);(0,react_1.useEffect)(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&&currentCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase?.();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=(0,getCardDetails_1.default)({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&card.brand!=="giftcard"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&&currentPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return(0,jsx_runtime_1.jsx)(PaymentGateway_1.default,{...gatewayProps})}exports.default=PaymentSource;
@@ -1,3 +1,4 @@
1
+ /** biome-ignore-all lint/correctness/useExhaustiveDependencies: Avoid infinite loop */
1
2
  import type { Order } from "@commercelayer/sdk";
2
3
  import { type JSX, type ReactNode } from "react";
3
4
  import type { BaseError } from "../../typings/errors";
@@ -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,errors:paymentMethodErrors}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase(),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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),useEffect(()=>{errors&&errors.length>0||paymentMethodErrors&&paymentMethodErrors.length>0?(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1)):setNotPermitted(!1)},[errors?.length,paymentMethodErrors?.length]),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,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase(),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&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId,errors:paymentMethodErrors}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase?.(),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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),useEffect(()=>{errors&&errors.length>0||paymentMethodErrors&&paymentMethodErrors.length>0?(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1)):setNotPermitted(!1)},[errors?.length,paymentMethodErrors?.length]),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,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase?.(),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&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=useCustomContext({context:PaymentMethodContext,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext);useEffect(()=>{if(paymentMethods!=null&&!isEmpty(paymentMethods)&&expressPayments){const[paymentMethod]=getAvailableExpressPayments(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments,errors?.length]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!isEmpty(paymentMethods),errors?.length]),useEffect(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),useEffect(()=>{const status2=order?.payment_source?.payment_response?.status?.toLowerCase();showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?sortPaymentMethods(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return _jsx("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:_jsx(PaymentMethodChildrenContext.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default PaymentMethod;
2
+ import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,showLoader,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config,errors}=useCustomContext({context:PaymentMethodContext,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext);useEffect(()=>{if(paymentMethods!=null&&!isEmpty(paymentMethods)&&expressPayments){const[paymentMethod]=getAvailableExpressPayments(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments,errors?.length]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase?.():null;if(isSingle){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{showLoader&&errors?.length===0?setLoading(showLoader):setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200)})())},[!isEmpty(paymentMethods),errors?.length]),useEffect(()=>{if(paymentMethods){const isSingle=paymentMethods.length===1,paymentSourceStatus=paymentSource?paymentSource.payment_response?.status?.toLowerCase?.():null;isSingle&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)},200):showLoader&&errors?.length===0&&paymentSourceStatus!=="declined"?setLoading(showLoader):setLoading(!1)}return currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}},[paymentMethods,currentPaymentMethodId,errors?.length]),useEffect(()=>{const status2=order?.payment_source?.payment_response?.status;showLoader&&status2?status2.toLowerCase()==="declined"?setLoading(!1):setLoading(!0):setLoading(!1)},[showLoader,order?.payment_source?.payment_response?.status]);const components=(paymentMethods!=null&&sortBy!=null?sortPaymentMethods(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return _jsx("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:_jsx(PaymentMethodChildrenContext.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default PaymentMethod;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";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,getOrderByFields}=useContext(OrderContext),authConfig=useContext(CommerceLayerContext),{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,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")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(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}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,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&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&&id.search("giftcard")===-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;
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 CommerceLayerContext from"../../context/CommerceLayerContext";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,getOrderByFields}=useContext(OrderContext),authConfig=useContext(CommerceLayerContext),{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),setPaymentMethodErrors([]),setPaymentRef({ref}),placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled=!1))},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,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")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(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}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,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&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,isValid=component.isValid;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1&&id.search("giftcard")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentMethodErrors([]),setPaymentRef({ref}),placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled=!1)),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,setPaymentMethodErrors!=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;
@@ -1,3 +1,4 @@
1
+ /** biome-ignore-all lint/correctness/useExhaustiveDependencies: Avoid infinite loop */
1
2
  import { type JSX } from "react";
2
3
  import type { LoaderType } from "../../typings/index";
3
4
  import type { CustomerCardsTemplateChildren } from "../utils/PaymentCardsTemplate";
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import getCardDetails from"../../utils/getCardDetails";import PaymentGateway from"../payment_gateways/PaymentGateway";export function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{payments}=useContext(CustomerContext),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),[show,setShow]=useState(!1),[showCard,setShowCard]=useState(!1);useEffect(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&&currentCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=getCardDetails({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&card.brand!=="giftcard"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&&currentPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return _jsx(PaymentGateway,{...gatewayProps})}export default PaymentSource;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import getCardDetails from"../../utils/getCardDetails";import PaymentGateway from"../payment_gateways/PaymentGateway";export function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{payments}=useContext(CustomerContext),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),[show,setShow]=useState(!1),[showCard,setShowCard]=useState(!1);useEffect(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&&currentCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase?.();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=getCardDetails({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&card.brand!=="giftcard"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&&currentPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return _jsx(PaymentGateway,{...gatewayProps})}export default PaymentSource;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.29.4",
3
+ "version": "4.29.5-beta.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",