@commercelayer/react-components 4.23.2 → 4.23.3-beta.1

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"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent");function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e=options?.adyen)===null||_e===void 0)&&_e.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e;if(e?.preventDefault(),e?.stopPropagation(),order?.status==="placed"){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e=checkPaymentSource?.payment_response)===null||_e===void 0?void 0:_e.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer"));function PlaceOrderButton(props){var _a,_b,_c,_d,_e;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e2,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e2=options?.adyen)===null||_e2===void 0)&&_e2.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2;if(paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentResponse=(_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.payment_response;((_c2=paymentResponse?.status)===null||_c2===void 0?void 0:_c2.toLowerCase())==="pending"&&setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}).then(res=>{var _a3;const paymentStatus2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.status;paymentStatus2.toLowerCase()==="authorized"?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})}},[options?.checkoutCom,paymentType,(_e=order?.payment_source)===null||_e===void 0?void 0:_e.id]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e2,_f,_g,_h,_j,_k;e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;const{status:status2}=yield sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e2=checkPaymentSource?.payment_response)===null||_e2===void 0?void 0:_e2.resultCode)==="Authorised"&&(isValid=!0)):!((_f=currentPaymentMethodRef?.current)===null||_f===void 0)&&_f.onsubmit&&(!((_g=options?.checkoutCom)===null||_g===void 0)&&_g.session_id)&&((_j=(_h=checkPaymentSource?.payment_response)===null||_h===void 0?void 0:_h.status)===null||_j===void 0?void 0:_j.toLowerCase())==="declined"?isValid=yield(_k=currentPaymentMethodRef.current)===null||_k===void 0?void 0:_k.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=(0,jwt_1.jwt)(accessToken).test?"sandbox":"production",locale=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){(yield window.CheckoutWebComponents({appearance:Object.assign({},options?.appearance),showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3,_b2;const element=(_a3=ref.current)===null||_a3===void 0?void 0:_a3.elements,savePaymentSourceToCustomerWallet=(_b2=element?.save_payment_source_to_customer_wallet)===null||_b2===void 0?void 0:_b2.checked;savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=yield component.tokenize(),token=data?.token,paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1}),setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",error,"Component",component.type)}})).create("flow").mount(document.getElementById("flow-container"))}))()}}},[loaded,(_b=order?.payment_source)===null||_b===void 0?void 0:_b.id,accessToken]),loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})})),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=(0,jwt_1.jwt)(accessToken).test?"sandbox":"production",locale=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const flowComponent=(yield window.CheckoutWebComponents({appearance:Object.assign({},options?.appearance),showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3,_b2;const element=(_a3=ref.current)===null||_a3===void 0?void 0:_a3.elements,savePaymentSourceToCustomerWallet=(_b2=element?.save_payment_source_to_customer_wallet)===null||_b2===void 0?void 0:_b2.checked;savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=yield component.tokenize(),token=data?.token,paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1}),setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)}})).create("card");(yield flowComponent.isAvailable())&&flowComponent.mount(document.getElementById("flow-container"))}))()}}},[loaded,(_b=order?.payment_source)===null||_b===void 0?void 0:_b.id,accessToken]),loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})})),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
@@ -4,7 +4,7 @@ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
4
4
  import type { BaseMetadataObject } from "../typings/index";
5
5
  import type { BaseError } from "../typings/errors";
6
6
  import type { AddressResource } from "./AddressReducer";
7
- import type { Order, OrderUpdate, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
7
+ import type { Order, OrderUpdate, QueryParamsRetrieve, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
8
8
  import type { LooseAutocomplete } from "../typings/globals";
9
9
  export type GetOrderParams = Partial<{
10
10
  clearWhenPlaced: boolean;
@@ -14,6 +14,7 @@ export type GetOrderParams = Partial<{
14
14
  id: string;
15
15
  persistKey: string;
16
16
  state: OrderState;
17
+ options: QueryParamsRetrieve;
17
18
  }>;
18
19
  export type GetOrder = (params: GetOrderParams) => Promise<undefined | Order>;
19
20
  type CreateOrderParams = Pick<AddToCartParams, "config" | "dispatch" | "persistKey" | "state" | "orderMetadata" | "orderAttributes" | "setLocalOrder">;
@@ -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.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"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=require("../utils/organization"),events_1=require("../utils/events"),getDomain_1=require("../utils/getDomain"),getApplicationLink_1=require("../utils/getApplicationLink"),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];function createOrder(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){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=yield sdk?.orders.create(Object.assign({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=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield 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;function updateOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({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=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}function paymentSourceRequest(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};yield sdk[resource][requestType](attributes);const orderUpdated=yield updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state});return{success:!0,order:orderUpdated?.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=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}function addToCart(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f;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=yield 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(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:(_c=lineItem?._update_quantity)!==null&&_c!==void 0?_c:!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=yield 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};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({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=${(_d=config.accessToken)!==null&&_d!==void 0?_d:""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=yield(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:(_f=(_e=organizationConfig?.links)===null||_e===void 0?void 0:_e.checkout)!==null&&_f!==void 0?_f: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;function setGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield 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}}})}function removeGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield 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.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"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=require("../utils/organization"),events_1=require("../utils/events"),getDomain_1=require("../utils/getDomain"),getApplicationLink_1=require("../utils/getApplicationLink"),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];function createOrder(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){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=yield sdk?.orders.create(Object.assign({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=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){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=yield 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;function updateOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({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=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}function paymentSourceRequest(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};yield sdk[resource][requestType](attributes);const orderUpdated=yield updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state});return{success:!0,order:orderUpdated?.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=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}function addToCart(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f;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=yield 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(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:(_c=lineItem?._update_quantity)!==null&&_c!==void 0?_c:!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=yield 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};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({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=${(_d=config.accessToken)!==null&&_d!==void 0?_d:""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=yield(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:(_f=(_e=organizationConfig?.links)===null||_e===void 0?void 0:_e.checkout)!==null&&_f!==void 0?_f: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;function setGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield 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}}})}function removeGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield 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;
@@ -12,7 +12,7 @@ export interface PlaceOrderOptions {
12
12
  redirectResult?: string;
13
13
  };
14
14
  checkoutCom?: {
15
- session_id: string;
15
+ session_id: string | undefined;
16
16
  };
17
17
  stripe?: {
18
18
  /**
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d,_e,_f,_g;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_b=options?.checkoutCom)===null||_b===void 0)&&_b.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0});if(((_c=payment?.payment_response)===null||_c===void 0?void 0:_c.status)!=="Authorized"){const[action]=((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_e=ps?.options)===null||_e===void 0?void 0:_e.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_f=order?.total_amount_cents)!==null&&_f!==void 0?_f:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_g=orderUpdated?.total_amount_cents)!==null&&_g!==void 0?_g:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_b=ps?.options)===null||_b===void 0?void 0:_b.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_c=order?.total_amount_cents)!==null&&_c!==void 0?_c:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_d=orderUpdated?.total_amount_cents)!==null&&_d!==void 0?_d:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";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),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),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 resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&ref?.current?.disabled===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{if(e?.preventDefault(),e?.stopPropagation(),order?.status==="placed"){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import useCommerceLayer from"../../hooks/useCommerceLayer";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),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 resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&ref?.current?.disabled===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&order?.payment_source?.payment_response?.status?.toLowerCase()==="pending"&&setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}).then(res=>{const paymentStatus2=res?.payment_response?.status;paymentStatus2.toLowerCase()==="authorized"?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})},[options?.checkoutCom,paymentType,order?.payment_source?.id]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",error,"Component",component.type)}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{const flowComponent=(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)}})).create("card");await flowComponent.isAvailable()&&flowComponent.mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
@@ -4,7 +4,7 @@ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
4
4
  import type { BaseMetadataObject } from "../typings/index";
5
5
  import type { BaseError } from "../typings/errors";
6
6
  import type { AddressResource } from "./AddressReducer";
7
- import type { Order, OrderUpdate, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
7
+ import type { Order, OrderUpdate, QueryParamsRetrieve, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
8
8
  import type { LooseAutocomplete } from "../typings/globals";
9
9
  export type GetOrderParams = Partial<{
10
10
  clearWhenPlaced: boolean;
@@ -14,6 +14,7 @@ export type GetOrderParams = Partial<{
14
14
  id: string;
15
15
  persistKey: string;
16
16
  state: OrderState;
17
+ options: QueryParamsRetrieve;
17
18
  }>;
18
19
  export type GetOrder = (params: GetOrderParams) => Promise<undefined | Order>;
19
20
  type CreateOrderParams = Pick<AddToCartParams, "config" | "dispatch" | "persistKey" | "state" | "orderMetadata" | "orderAttributes" | "setLocalOrder">;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import{getOrganizationConfig}from"../utils/organization";import{publish}from"../utils/events";import{getDomain}from"../utils/getDomain";import{getApplicationLink}from"../utils/getApplicationLink";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}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;const options={};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 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};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{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{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import{getOrganizationConfig}from"../utils/organization";import{publish}from"../utils/events";import{getDomain}from"../utils/getDomain";import{getApplicationLink}from"../utils/getApplicationLink";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 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};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{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;
@@ -12,7 +12,7 @@ export interface PlaceOrderOptions {
12
12
  redirectResult?: string;
13
13
  };
14
14
  checkoutCom?: {
15
- session_id: string;
15
+ session_id: string | undefined;
16
16
  };
17
17
  stripe?: {
18
18
  /**
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
2
+ import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.23.2",
3
+ "version": "4.23.3-beta.1",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",