@commercelayer/react-components 4.29.0-beta.3 → 4.29.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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))},[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.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),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")),localStorage_1=require("../../utils/localStorage"),StripeExpressPayment_1=require("./StripeExpressPayment"),defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.useEffect)(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)(react_stripe_js_1.Elements,{stripe,options:elementsOptions,children:expressPayments?(0,jsx_runtime_1.jsx)(StripeExpressPayment_1.StripeExpressPayment,{clientSecret}):(0,jsx_runtime_1.jsx)(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}exports.default=StripePayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),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")),localStorage_1=require("../../utils/localStorage"),StripeExpressPayment_1=require("./StripeExpressPayment"),defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{errors,currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.useEffect)(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(selectedPaymentMethodType=event.value.type,console.log("Errors",errors),event.complete&&(errors&&errors.length>0&&setPaymentMethodErrors([]),["apple_pay","google_pay"].includes(event.value.type))){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)(react_stripe_js_1.Elements,{stripe,options:elementsOptions,children:expressPayments?(0,jsx_runtime_1.jsx)(StripeExpressPayment_1.StripeExpressPayment,{clientSecret}):(0,jsx_runtime_1.jsx)(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}exports.default=StripePayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.saveAddressToCustomerAddressBook=exports.unsetOrderState=exports.setOrder=exports.getApiOrder=void 0,exports.createOrder=createOrder,exports.getOrderByFields=getOrderByFields,exports.updateOrder=updateOrder,exports.paymentSourceRequest=paymentSourceRequest,exports.addResourceToInclude=addResourceToInclude,exports.addToCart=addToCart,exports.setOrderErrors=setOrderErrors,exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode,exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),events_1=require("../utils/events"),getApplicationLink_1=require("../utils/getApplicationLink"),getDomain_1=require("../utils/getDomain"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),localStorage_1=require("../utils/localStorage"),organization_1=require("../utils/organization"),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}};exports.getApiOrder=getApiOrder;async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id},currentTotalAmountWithTaxesCents=state?.order?.total_amount_with_taxes_cents;await sdk.orders.update(resource,{include});let order=await(0,exports.getApiOrder)({id,config,dispatch,state});const newTotalAmountWithTaxesCents=order?.total_amount_with_taxes_cents;return currentTotalAmountWithTaxesCents!==newTotalAmountWithTaxesCents&&order?.payment_source?.id&&order?.payment_source?.expires_at<=new Date().toISOString()&&(console.log("Total amount with taxes cents changed, updating payment source...",{old:state?.order,new:order}),await sdk.orders.update({id,payment_source:null}),order=await(0,exports.getApiOrder)({id,config,dispatch,state})),dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Update order",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1,error}}}async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await(0,exports.getApiOrder)({id,...params})}else await(0,exports.getApiOrder)({id,...params,state});if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.saveAddressToCustomerAddressBook=exports.unsetOrderState=exports.setOrder=exports.getApiOrder=void 0,exports.createOrder=createOrder,exports.getOrderByFields=getOrderByFields,exports.updateOrder=updateOrder,exports.paymentSourceRequest=paymentSourceRequest,exports.addResourceToInclude=addResourceToInclude,exports.addToCart=addToCart,exports.setOrderErrors=setOrderErrors,exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode,exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),events_1=require("../utils/events"),getApplicationLink_1=require("../utils/getApplicationLink"),getDomain_1=require("../utils/getDomain"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),localStorage_1=require("../utils/localStorage"),organization_1=require("../utils/organization"),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}};exports.getApiOrder=getApiOrder;async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id},currentTotalAmountWithTaxesCents=state?.order?.total_amount_with_taxes_cents;await sdk.orders.update(resource,{include});let order=await(0,exports.getApiOrder)({id,config,dispatch,state});const newTotalAmountWithTaxesCents=order?.total_amount_with_taxes_cents;return currentTotalAmountWithTaxesCents!==newTotalAmountWithTaxesCents&&order?.payment_source?.id&&order?.payment_source?.expires_at<=new Date().toISOString()&&(await sdk.orders.update({id,payment_source:null}),order=await(0,exports.getApiOrder)({id,config,dispatch,state})),dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Update order",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1,error}}}async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await(0,exports.getApiOrder)({id,...params})}else await(0,exports.getApiOrder)({id,...params,state});if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
@@ -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))},[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,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{errors,currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(selectedPaymentMethodType=event.value.type,console.log("Errors",errors),event.complete&&(errors&&errors.length>0&&setPaymentMethodErrors([]),["apple_pay","google_pay"].includes(event.value.type))){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{publish}from"../utils/events";import{getApplicationLink}from"../utils/getApplicationLink";import{getDomain}from"../utils/getDomain";import getSdk from"../utils/getSdk";import{setCustomerOrderParam}from"../utils/localStorage";import{getOrganizationConfig}from"../utils/organization";import getErrors,{setErrors}from"../utils/getErrors";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?getSdk(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id},currentTotalAmountWithTaxesCents=state?.order?.total_amount_with_taxes_cents;await sdk.orders.update(resource,{include});let order=await getApiOrder({id,config,dispatch,state});const newTotalAmountWithTaxesCents=order?.total_amount_with_taxes_cents;return currentTotalAmountWithTaxesCents!==newTotalAmountWithTaxesCents&&order?.payment_source?.id&&order?.payment_source?.expires_at<=new Date().toISOString()&&(console.log("Total amount with taxes cents changed, updating payment source...",{old:state?.order,new:order}),await sdk.orders.update({id,payment_source:null}),order=await getApiOrder({id,config,dispatch,state})),dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return console.error("Update order",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1,error}}}export async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?getSdk(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=getErrors({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
2
+ import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{publish}from"../utils/events";import{getApplicationLink}from"../utils/getApplicationLink";import{getDomain}from"../utils/getDomain";import getSdk from"../utils/getSdk";import{setCustomerOrderParam}from"../utils/localStorage";import{getOrganizationConfig}from"../utils/organization";import getErrors,{setErrors}from"../utils/getErrors";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?getSdk(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id},currentTotalAmountWithTaxesCents=state?.order?.total_amount_with_taxes_cents;await sdk.orders.update(resource,{include});let order=await getApiOrder({id,config,dispatch,state});const newTotalAmountWithTaxesCents=order?.total_amount_with_taxes_cents;return currentTotalAmountWithTaxesCents!==newTotalAmountWithTaxesCents&&order?.payment_source?.id&&order?.payment_source?.expires_at<=new Date().toISOString()&&(await sdk.orders.update({id,payment_source:null}),order=await getApiOrder({id,config,dispatch,state})),dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return console.error("Update order",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1,error}}}export async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?getSdk(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=getErrors({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.29.0-beta.3",
3
+ "version": "4.29.0-beta.4",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",