@commercelayer/react-components 4.1.0 → 4.1.2

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 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=(0,react_1.useReducer)(OrderReducer_1.default,OrderReducer_1.orderInitialState),[lock,setLock]=(0,react_1.useState)(!1),[lockOrder,setLockOrder]=(0,react_1.useState)(!0),config=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer"});if(config.accessToken==null)throw new Error("Cannot use `OrderContainer` outside of `CommerceLayer`");const{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=(0,react_1.useContext)(OrderStorageContext_1.default);(0,react_1.useEffect)(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),(0,react_1.useEffect)(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=(0,compareObjAttribute_1.default)({attributes,object:state.order});Object.keys(updateAttributes).length>0&&((0,OrderReducer_1.updateOrder)({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=(0,compareObjAttribute_1.default)({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),(0,react_1.useEffect)(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0),getOrder=async()=>{const removeOrderPlaced=!!(persistKey&&clearWhenPlaced);localOrder&&await(0,OrderReducer_1.getApiOrder)({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:removeOrderPlaced,deleteLocalOrder,state})};return config.accessToken&&!state.loading?localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder?getOrder():state?.order&&fetchOrder?fetchOrder(state.order):state.withoutIncludes&&!state.include?.length&&startRequest.length===0&&getOrder():[config.accessToken,!state.order,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,!state.order,state.loading,!state.withoutIncludes].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{!state.order&&state.loading&&!state.withoutIncludes&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,state.includeLoaded,state.include,orderId,state.order,state.loading,state.withoutIncludes,lockOrder]);const orderValue=(0,react_1.useMemo)(()=>({...state,setOrder:order=>(0,OrderReducer_1.setOrder)(order,dispatch),getOrder:async id=>await(0,OrderReducer_1.getApiOrder)({id,dispatch,config,state}),setOrderErrors:errors=>(0,OrderReducer_1.setOrderErrors)({dispatch,errors}),createOrder:async()=>await(0,OrderReducer_1.createOrder)({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await(0,OrderReducer_1.addToCart)({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>OrderContext_1.defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch}),setGiftCardOrCouponCode:async({code,codeType})=>await OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await OrderContext_1.defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>OrderContext_1.defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded}),updateOrder:async args=>await OrderContext_1.defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken]);return(0,jsx_runtime_1.jsx)(OrderContext_1.default.Provider,{value:orderValue,children})}exports.OrderContainer=OrderContainer,exports.default=OrderContainer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=(0,react_1.useReducer)(OrderReducer_1.default,OrderReducer_1.orderInitialState),[lock,setLock]=(0,react_1.useState)(!1),[lockOrder,setLockOrder]=(0,react_1.useState)(!0),config=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=(0,react_1.useContext)(OrderStorageContext_1.default);(0,react_1.useEffect)(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),(0,react_1.useEffect)(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=(0,compareObjAttribute_1.default)({attributes,object:state.order});Object.keys(updateAttributes).length>0&&((0,OrderReducer_1.updateOrder)({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=(0,compareObjAttribute_1.default)({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),(0,react_1.useEffect)(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0),getOrder=async()=>{const removeOrderPlaced=!!(persistKey&&clearWhenPlaced);localOrder&&await(0,OrderReducer_1.getApiOrder)({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:removeOrderPlaced,deleteLocalOrder,state})};return config.accessToken&&state.loading===!1&&state?.order==null?localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder?getOrder():state?.order&&fetchOrder?fetchOrder(state.order):state.withoutIncludes&&!state.include?.length&&startRequest.length===0&&getOrder():[config.accessToken,state.order!=null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order!=null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,state.order,state.loading,state.withoutIncludes,lockOrder]);const orderValue=(0,react_1.useMemo)(()=>({...state,setOrder:order=>(0,OrderReducer_1.setOrder)(order,dispatch),getOrder:async id=>await(0,OrderReducer_1.getApiOrder)({id,dispatch,config,state}),setOrderErrors:errors=>(0,OrderReducer_1.setOrderErrors)({dispatch,errors}),createOrder:async()=>await(0,OrderReducer_1.createOrder)({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await(0,OrderReducer_1.addToCart)({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>OrderContext_1.defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch}),setGiftCardOrCouponCode:async({code,codeType})=>await OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await OrderContext_1.defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>OrderContext_1.defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded}),updateOrder:async args=>await OrderContext_1.defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken]);return(0,jsx_runtime_1.jsx)(OrderContext_1.default.Provider,{value:orderValue,children})}exports.OrderContainer=OrderContainer,exports.default=OrderContainer;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderListPaginationButtons=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),omit_1=tslib_1.__importDefault(require("../../utils/omit"));function OrderListPaginationButtons({previousPageButton,nextPageButton,navigationButtons,children,...props}){const{...prevButton}={show:!0,...previousPageButton},{...nextButton}={show:!0,...nextPageButton},{...navButton}={show:!0,...navigationButtons},ctx=(0,useCustomContext_1.default)({context:OrderListPaginationContext_1.default,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationButtons"}),PrevButton=prevButton.show?prevButton.hideWhenDisabled===!0&&ctx?.canPreviousPage===!1?null:(0,jsx_runtime_1.jsx)("button",{"data-testid":"prev-button",...(0,omit_1.default)(prevButton,["show","hideWhenDisabled"]),disabled:ctx?.canPreviousPage===!1,onClick:()=>ctx?.previousPage(),children:previousPageButton?.label??"<"}):null,NextButton=nextButton.show?nextButton.hideWhenDisabled===!0&&ctx?.canNextPage===!1?null:(0,jsx_runtime_1.jsx)("button",{"data-testid":"next-button",...(0,omit_1.default)(nextButton,["show","hideWhenDisabled"]),disabled:ctx?.canNextPage===!1,onClick:()=>ctx?.nextPage(),children:nextButton?.label??">"}):null,pagesToShow=ctx?.canPreviousPage===!1?ctx?.pageOptions.slice(0,3).map(v=>v+1):ctx?.canNextPage===!1?ctx?.pageOptions.slice(ctx?.pageOptions.length-3,ctx?.pageOptions.length).map(v=>v+1):ctx?.pageOptions.slice(ctx?.pageIndex-1,ctx?.pageIndex+2).map(v=>v+1),NavButtons=navButton.show?pagesToShow?.map(v=>{const className=(ctx?.pageIndex!=null?ctx?.pageIndex+1:1)===v?`${navButton?.className??""} ${navButton?.activeClassName??""}`:navButton?.className;return(0,jsx_runtime_1.jsx)("button",{"data-testid":`page-${v}`,...(0,omit_1.default)(navButton,["show","activeClassName","className"]),className,onClick:()=>ctx?.gotoPage(v-1),children:v},`page-${v}`)}):null,parentProps={navigationButtons,prevButton,nextButton,...ctx,...props};return children==null?ctx?.totalRows===0?null:(0,jsx_runtime_1.jsxs)("div",{...props,children:[PrevButton,NavButtons,NextButton]}):(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children})}exports.OrderListPaginationButtons=OrderListPaginationButtons,OrderListPaginationButtons.displayName="OrderListPaginationButtons",exports.default=OrderListPaginationButtons;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderListPaginationButtons=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),omit_1=tslib_1.__importDefault(require("../../utils/omit"));function OrderListPaginationButtons({previousPageButton,nextPageButton,navigationButtons,children,...props}){const{...prevButton}={show:!0,...previousPageButton},{...nextButton}={show:!0,...nextPageButton},{...navButton}={show:!0,...navigationButtons},ctx=(0,useCustomContext_1.default)({context:OrderListPaginationContext_1.default,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationButtons",key:"page"}),PrevButton=prevButton.show?prevButton.hideWhenDisabled===!0&&ctx?.canPreviousPage===!1?null:(0,jsx_runtime_1.jsx)("button",{"data-testid":"prev-button",...(0,omit_1.default)(prevButton,["show","hideWhenDisabled"]),disabled:ctx?.canPreviousPage===!1,onClick:()=>ctx?.previousPage(),children:previousPageButton?.label??"<"}):null,NextButton=nextButton.show?nextButton.hideWhenDisabled===!0&&ctx?.canNextPage===!1?null:(0,jsx_runtime_1.jsx)("button",{"data-testid":"next-button",...(0,omit_1.default)(nextButton,["show","hideWhenDisabled"]),disabled:ctx?.canNextPage===!1,onClick:()=>ctx?.nextPage(),children:nextButton?.label??">"}):null,pagesToShow=ctx?.canPreviousPage===!1?ctx?.pageOptions.slice(0,3).map(v=>v+1):ctx?.canNextPage===!1?ctx?.pageOptions.slice(ctx?.pageOptions.length-3,ctx?.pageOptions.length).map(v=>v+1):ctx?.pageOptions.slice(ctx?.pageIndex-1,ctx?.pageIndex+2).map(v=>v+1),NavButtons=navButton.show?pagesToShow?.map(v=>{const className=(ctx?.pageIndex!=null?ctx?.pageIndex+1:1)===v?`${navButton?.className??""} ${navButton?.activeClassName??""}`:navButton?.className;return(0,jsx_runtime_1.jsx)("button",{"data-testid":`page-${v}`,...(0,omit_1.default)(navButton,["show","activeClassName","className"]),className,onClick:()=>ctx?.gotoPage(v-1),children:v},`page-${v}`)}):null,parentProps={navigationButtons,prevButton,nextButton,...ctx,...props};return children==null?ctx?.totalRows===0?null:(0,jsx_runtime_1.jsxs)("div",{...props,children:[PrevButton,NavButtons,NextButton]}):(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children})}exports.OrderListPaginationButtons=OrderListPaginationButtons,OrderListPaginationButtons.displayName="OrderListPaginationButtons",exports.default=OrderListPaginationButtons;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderListPaginationInfo=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderListPaginationInfo({as="span",children,...props}){const ctx=(0,useCustomContext_1.default)({context:OrderListPaginationContext_1.default,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationInfo"}),TagElement=as,totRows=ctx?.totalRows??0,pageIndex=ctx?.pageIndex??0,pageSize=ctx?.pageSize??10;let firstRow=pageIndex===0?pageIndex+1:pageIndex,lastRow=firstRow*pageSize;ctx?.canPreviousPage===!0&&(firstRow=Math.floor(firstRow*pageSize)+1,lastRow=Math.floor(firstRow+pageSize-1)),ctx?.canNextPage===!1&&(lastRow=totRows);const parentProps={...props,as,firstRow,lastRow,totRows};return children==null?totRows===0?null:(0,jsx_runtime_1.jsx)(TagElement,{...props,children:`${firstRow} - ${lastRow} of ${totRows}`}):(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children})}exports.OrderListPaginationInfo=OrderListPaginationInfo,OrderListPaginationInfo.displayName="OrderListPaginationInfo",exports.default=OrderListPaginationInfo;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderListPaginationInfo=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderListPaginationInfo({as="span",children,...props}){const ctx=(0,useCustomContext_1.default)({context:OrderListPaginationContext_1.default,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationInfo",key:"page"}),TagElement=as,totRows=ctx?.totalRows??0,pageIndex=ctx?.pageIndex??0,pageSize=ctx?.pageSize??10;let firstRow=pageIndex===0?pageIndex+1:pageIndex,lastRow=firstRow*pageSize;ctx?.canPreviousPage===!0&&(firstRow=Math.floor(firstRow*pageSize)+1,lastRow=Math.floor(firstRow+pageSize-1)),ctx?.canNextPage===!1&&(lastRow=totRows);const parentProps={...props,as,firstRow,lastRow,totRows};return children==null?totRows===0?null:(0,jsx_runtime_1.jsx)(TagElement,{...props,children:`${firstRow} - ${lastRow} of ${totRows}`}):(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children})}exports.OrderListPaginationInfo=OrderListPaginationInfo,OrderListPaginationInfo.displayName="OrderListPaginationInfo",exports.default=OrderListPaginationInfo;
@@ -0,0 +1 @@
1
+ "use strict";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethodsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importStar(require("../../context/PaymentMethodContext")),react_1=require("react"),PaymentMethodReducer_1=tslib_1.__importStar(require("../../reducers/PaymentMethodReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=(0,react_1.useReducer)(PaymentMethodReducer_1.default,PaymentMethodReducer_1.paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=(0,react_1.useContext)(CommerceLayerContext_1.default);async function getPayMethods(){order&&await(0,PaymentMethodReducer_1.getPaymentMethods)({order,dispatch})}(0,react_1.useEffect)(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&(0,isEmpty_1.default)(state.config)&&(0,PaymentMethodReducer_1.setPaymentMethodConfig)(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},[order,credentials,include,includeLoaded]);const contextValue=(0,react_1.useMemo)(()=>({...state,setLoading:({loading})=>PaymentMethodContext_1.defaultPaymentMethodContext.setLoading({loading,dispatch}),setPaymentRef:({ref})=>(0,PaymentMethodReducer_1.setPaymentRef)({ref,dispatch}),setPaymentMethodErrors:errors=>PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch),setPaymentMethod:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch}),destroyPaymentSource:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}),[state]);return(0,jsx_runtime_1.jsx)(PaymentMethodContext_1.default.Provider,{value:contextValue,children})}exports.PaymentMethodsContainer=PaymentMethodsContainer,exports.default=PaymentMethodsContainer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethodsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importStar(require("../../context/PaymentMethodContext")),react_1=require("react"),PaymentMethodReducer_1=tslib_1.__importStar(require("../../reducers/PaymentMethodReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=(0,react_1.useReducer)(PaymentMethodReducer_1.default,PaymentMethodReducer_1.paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=(0,react_1.useContext)(CommerceLayerContext_1.default);async function getPayMethods(){order&&await(0,PaymentMethodReducer_1.getPaymentMethods)({order,dispatch})}(0,react_1.useEffect)(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&(0,isEmpty_1.default)(state.config)&&(0,PaymentMethodReducer_1.setPaymentMethodConfig)(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=(0,react_1.useMemo)(()=>({...state,setLoading:({loading})=>PaymentMethodContext_1.defaultPaymentMethodContext.setLoading({loading,dispatch}),setPaymentRef:({ref})=>(0,PaymentMethodReducer_1.setPaymentRef)({ref,dispatch}),setPaymentMethodErrors:errors=>PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch),setPaymentMethod:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch}),destroyPaymentSource:async args=>await PaymentMethodContext_1.defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}),[state]);return(0,jsx_runtime_1.jsx)(PaymentMethodContext_1.default.Provider,{value:contextValue,children})}exports.PaymentMethodsContainer=PaymentMethodsContainer,exports.default=PaymentMethodsContainer;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.removeGiftCardOrCouponCode=exports.setGiftCardOrCouponCode=exports.saveAddressToCustomerAddressBook=exports.setOrderErrors=exports.unsetOrderState=exports.addToCart=exports.addResourceToInclude=exports.setOrder=exports.updateOrder=exports.getApiOrder=exports.createOrder=void 0;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=tslib_1.__importDefault(require("../utils/organization")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"],createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=(0,getSdk_1.default)(config);try{const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)(error,"orders");console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""};exports.createOrder=createOrder;const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=(0,getSdk_1.default)(config);try{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=(0,getErrors_1.default)(error,"orders");console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}};exports.getApiOrder=getApiOrder;async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=(0,getSdk_1.default)(config);try{const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0}}catch(error){const errors=(0,getErrors_1.default)(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}exports.updateOrder=updateOrder;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=[...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}})}exports.addResourceToInclude=addResourceToInclude;async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=await(0,exports.createOrder)(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl;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:!0,bundle_code:bundleCode},newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await(0,exports.getApiOrder)({id,...params})}else await(0,exports.getApiOrder)({id,...params,state});if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=(0,organization_1.default)(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)(error,"orders");return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}exports.addToCart=addToCart;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}}exports.setOrderErrors=setOrderErrors;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;const setGiftCardOrCouponCode=async({code,codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}};exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode;const removeGiftCardOrCouponCode=async({codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&dispatch){const attributes={[codeType]:""};return await updateOrder({id:order.id,attributes,config,include,dispatch,state}),dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}};exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode,exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.removeGiftCardOrCouponCode=exports.setGiftCardOrCouponCode=exports.saveAddressToCustomerAddressBook=exports.setOrderErrors=exports.unsetOrderState=exports.addToCart=exports.addResourceToInclude=exports.setOrder=exports.updateOrder=exports.getApiOrder=exports.createOrder=void 0;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=tslib_1.__importDefault(require("../utils/organization")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"],createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=(0,getSdk_1.default)(config);try{const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)(error,"orders");console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""};exports.createOrder=createOrder;const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=(0,getSdk_1.default)(config);try{const options={};state?.include&&state.include.length>0&&(options.include=state.include),console.log("includes",options);const order=await sdk.orders.retrieve(id,options);return console.log("order",order),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,"orders");console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}};exports.getApiOrder=getApiOrder;async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=(0,getSdk_1.default)(config);try{const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0}}catch(error){const errors=(0,getErrors_1.default)(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}exports.updateOrder=updateOrder;const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,console.log(payload);debugger;dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}exports.addResourceToInclude=addResourceToInclude;async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=await(0,exports.createOrder)(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl;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:!0,bundle_code:bundleCode},newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await(0,exports.getApiOrder)({id,...params})}else await(0,exports.getApiOrder)({id,...params,state});if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=(0,organization_1.default)(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)(error,"orders");return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}exports.addToCart=addToCart;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}}exports.setOrderErrors=setOrderErrors;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;const setGiftCardOrCouponCode=async({code,codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}};exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode;const removeGiftCardOrCouponCode=async({codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&dispatch){const attributes={[codeType]:""};return await updateOrder({id:order.id,attributes,config,include,dispatch,state}),dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}};exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode,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;
@@ -15,7 +15,7 @@ interface TParams<C> {
15
15
  /**
16
16
  * Key of the context to check
17
17
  */
18
- key?: string;
18
+ key: string;
19
19
  }
20
20
  export default function useCustomContext<T>({ context, key, currentComponentName, contextComponentName }: TParams<T>): T;
21
21
  export {};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const react_1=require("react");function useCustomContext({context,key,currentComponentName,contextComponentName}){const currentContext=(0,react_1.useContext)(context),isProduction=process.env.NODE_ENV==="production",msg=`Cannot use <${currentComponentName}/> outside of <${contextComponentName}/>`;if(key!=null&&key in currentContext||key==null&&currentContext!=null||currentContext!=null)return currentContext;if(isProduction)console.error(msg);else throw new Error(msg);return currentContext}exports.default=useCustomContext;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const react_1=require("react");function useCustomContext({context,key,currentComponentName,contextComponentName}){const currentContext=(0,react_1.useContext)(context),isProduction=process.env.NODE_ENV==="production",msg=`Cannot use <${currentComponentName}/> outside of <${contextComponentName}/>`;if(key!=null&&key in currentContext||key==null&&currentContext!=null)return currentContext;if(isProduction)console.error(msg);else throw new Error(msg);return currentContext}exports.default=useCustomContext;
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer"});if(config.accessToken==null)throw new Error("Cannot use `OrderContainer` outside of `CommerceLayer`");const{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext);useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0),getOrder=async()=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};return config.accessToken&&!state.loading?localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder?getOrder():state?.order&&fetchOrder?fetchOrder(state.order):state.withoutIncludes&&!state.include?.length&&startRequest.length===0&&getOrder():[config.accessToken,!state.order,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,!state.order,state.loading,!state.withoutIncludes].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{!state.order&&state.loading&&!state.withoutIncludes&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,state.includeLoaded,state.include,orderId,state.order,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>({...state,setOrder:order=>setOrder(order,dispatch),getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch}),setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded}),updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
1
+ import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext);useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0),getOrder=async()=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};return config.accessToken&&state.loading===!1&&state?.order==null?localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder?getOrder():state?.order&&fetchOrder?fetchOrder(state.order):state.withoutIncludes&&!state.include?.length&&startRequest.length===0&&getOrder():[config.accessToken,state.order!=null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order!=null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,state.order,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>({...state,setOrder:order=>setOrder(order,dispatch),getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch}),setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded}),updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
@@ -1 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";import omit from"../../utils/omit";export function OrderListPaginationButtons({previousPageButton,nextPageButton,navigationButtons,children,...props}){const{...prevButton}={show:!0,...previousPageButton},{...nextButton}={show:!0,...nextPageButton},{...navButton}={show:!0,...navigationButtons},ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationButtons"}),PrevButton=prevButton.show?prevButton.hideWhenDisabled===!0&&ctx?.canPreviousPage===!1?null:_jsx("button",{"data-testid":"prev-button",...omit(prevButton,["show","hideWhenDisabled"]),disabled:ctx?.canPreviousPage===!1,onClick:()=>ctx?.previousPage(),children:previousPageButton?.label??"<"}):null,NextButton=nextButton.show?nextButton.hideWhenDisabled===!0&&ctx?.canNextPage===!1?null:_jsx("button",{"data-testid":"next-button",...omit(nextButton,["show","hideWhenDisabled"]),disabled:ctx?.canNextPage===!1,onClick:()=>ctx?.nextPage(),children:nextButton?.label??">"}):null,pagesToShow=ctx?.canPreviousPage===!1?ctx?.pageOptions.slice(0,3).map(v=>v+1):ctx?.canNextPage===!1?ctx?.pageOptions.slice(ctx?.pageOptions.length-3,ctx?.pageOptions.length).map(v=>v+1):ctx?.pageOptions.slice(ctx?.pageIndex-1,ctx?.pageIndex+2).map(v=>v+1),NavButtons=navButton.show?pagesToShow?.map(v=>{const className=(ctx?.pageIndex!=null?ctx?.pageIndex+1:1)===v?`${navButton?.className??""} ${navButton?.activeClassName??""}`:navButton?.className;return _jsx("button",{"data-testid":`page-${v}`,...omit(navButton,["show","activeClassName","className"]),className,onClick:()=>ctx?.gotoPage(v-1),children:v},`page-${v}`)}):null,parentProps={navigationButtons,prevButton,nextButton,...ctx,...props};return children==null?ctx?.totalRows===0?null:_jsxs("div",{...props,children:[PrevButton,NavButtons,NextButton]}):_jsx(Parent,{...parentProps,children})}OrderListPaginationButtons.displayName="OrderListPaginationButtons";export default OrderListPaginationButtons;
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";import omit from"../../utils/omit";export function OrderListPaginationButtons({previousPageButton,nextPageButton,navigationButtons,children,...props}){const{...prevButton}={show:!0,...previousPageButton},{...nextButton}={show:!0,...nextPageButton},{...navButton}={show:!0,...navigationButtons},ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationButtons",key:"page"}),PrevButton=prevButton.show?prevButton.hideWhenDisabled===!0&&ctx?.canPreviousPage===!1?null:_jsx("button",{"data-testid":"prev-button",...omit(prevButton,["show","hideWhenDisabled"]),disabled:ctx?.canPreviousPage===!1,onClick:()=>ctx?.previousPage(),children:previousPageButton?.label??"<"}):null,NextButton=nextButton.show?nextButton.hideWhenDisabled===!0&&ctx?.canNextPage===!1?null:_jsx("button",{"data-testid":"next-button",...omit(nextButton,["show","hideWhenDisabled"]),disabled:ctx?.canNextPage===!1,onClick:()=>ctx?.nextPage(),children:nextButton?.label??">"}):null,pagesToShow=ctx?.canPreviousPage===!1?ctx?.pageOptions.slice(0,3).map(v=>v+1):ctx?.canNextPage===!1?ctx?.pageOptions.slice(ctx?.pageOptions.length-3,ctx?.pageOptions.length).map(v=>v+1):ctx?.pageOptions.slice(ctx?.pageIndex-1,ctx?.pageIndex+2).map(v=>v+1),NavButtons=navButton.show?pagesToShow?.map(v=>{const className=(ctx?.pageIndex!=null?ctx?.pageIndex+1:1)===v?`${navButton?.className??""} ${navButton?.activeClassName??""}`:navButton?.className;return _jsx("button",{"data-testid":`page-${v}`,...omit(navButton,["show","activeClassName","className"]),className,onClick:()=>ctx?.gotoPage(v-1),children:v},`page-${v}`)}):null,parentProps={navigationButtons,prevButton,nextButton,...ctx,...props};return children==null?ctx?.totalRows===0?null:_jsxs("div",{...props,children:[PrevButton,NavButtons,NextButton]}):_jsx(Parent,{...parentProps,children})}OrderListPaginationButtons.displayName="OrderListPaginationButtons";export default OrderListPaginationButtons;
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderListPaginationInfo({as="span",children,...props}){const ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationInfo"}),TagElement=as,totRows=ctx?.totalRows??0,pageIndex=ctx?.pageIndex??0,pageSize=ctx?.pageSize??10;let firstRow=pageIndex===0?pageIndex+1:pageIndex,lastRow=firstRow*pageSize;ctx?.canPreviousPage===!0&&(firstRow=Math.floor(firstRow*pageSize)+1,lastRow=Math.floor(firstRow+pageSize-1)),ctx?.canNextPage===!1&&(lastRow=totRows);const parentProps={...props,as,firstRow,lastRow,totRows};return children==null?totRows===0?null:_jsx(TagElement,{...props,children:`${firstRow} - ${lastRow} of ${totRows}`}):_jsx(Parent,{...parentProps,children})}OrderListPaginationInfo.displayName="OrderListPaginationInfo";export default OrderListPaginationInfo;
1
+ import{jsx as _jsx}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderListPaginationInfo({as="span",children,...props}){const ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationInfo",key:"page"}),TagElement=as,totRows=ctx?.totalRows??0,pageIndex=ctx?.pageIndex??0,pageSize=ctx?.pageSize??10;let firstRow=pageIndex===0?pageIndex+1:pageIndex,lastRow=firstRow*pageSize;ctx?.canPreviousPage===!0&&(firstRow=Math.floor(firstRow*pageSize)+1,lastRow=Math.floor(firstRow+pageSize-1)),ctx?.canNextPage===!1&&(lastRow=totRows);const parentProps={...props,as,firstRow,lastRow,totRows};return children==null?totRows===0?null:_jsx(TagElement,{...props,children:`${firstRow} - ${lastRow} of ${totRows}`}):_jsx(Parent,{...parentProps,children})}OrderListPaginationInfo.displayName="OrderListPaginationInfo";export default OrderListPaginationInfo;
@@ -0,0 +1 @@
1
+ "use strict";
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext,{defaultPaymentMethodContext}from"../../context/PaymentMethodContext";import{useContext,useEffect,useReducer,useMemo}from"react";import paymentMethodReducer,{paymentMethodInitialState,getPaymentMethods,setPaymentMethodConfig,setPaymentRef}from"../../reducers/PaymentMethodReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import isEmpty from"lodash/isEmpty";import useCustomContext from"../../utils/hooks/useCustomContext";export function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=useReducer(paymentMethodReducer,paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=useContext(CommerceLayerContext);async function getPayMethods(){order&&await getPaymentMethods({order,dispatch})}useEffect(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&isEmpty(state.config)&&setPaymentMethodConfig(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},[order,credentials,include,includeLoaded]);const contextValue=useMemo(()=>({...state,setLoading:({loading})=>defaultPaymentMethodContext.setLoading({loading,dispatch}),setPaymentRef:({ref})=>setPaymentRef({ref,dispatch}),setPaymentMethodErrors:errors=>defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch),setPaymentMethod:async args=>await defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>await defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch}),destroyPaymentSource:async args=>await defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}),[state]);return _jsx(PaymentMethodContext.Provider,{value:contextValue,children})}export default PaymentMethodsContainer;
1
+ import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext,{defaultPaymentMethodContext}from"../../context/PaymentMethodContext";import{useContext,useEffect,useReducer,useMemo}from"react";import paymentMethodReducer,{paymentMethodInitialState,getPaymentMethods,setPaymentMethodConfig,setPaymentRef}from"../../reducers/PaymentMethodReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import isEmpty from"lodash/isEmpty";import useCustomContext from"../../utils/hooks/useCustomContext";export function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=useReducer(paymentMethodReducer,paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=useContext(CommerceLayerContext);async function getPayMethods(){order&&await getPaymentMethods({order,dispatch})}useEffect(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&isEmpty(state.config)&&setPaymentMethodConfig(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=useMemo(()=>({...state,setLoading:({loading})=>defaultPaymentMethodContext.setLoading({loading,dispatch}),setPaymentRef:({ref})=>setPaymentRef({ref,dispatch}),setPaymentMethodErrors:errors=>defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch),setPaymentMethod:async args=>await defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>await defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch}),destroyPaymentSource:async args=>await defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}),[state]);return _jsx(PaymentMethodContext.Provider,{value:contextValue,children})}export default PaymentMethodsContainer;
@@ -1 +1 @@
1
- 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 getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=getSdk(config);try{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,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{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,"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=getSdk(config);try{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}}catch(error){const errors=getErrors(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}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=[...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}=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;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:!0,bundle_code:bundleCode},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){const{organization}=getOrganizationSlug(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors(error,"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}})},setGiftCardOrCouponCode=async({code,codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},removeGiftCardOrCouponCode=async({codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&dispatch){const attributes={[codeType]:""};return await updateOrder({id:order.id,attributes,config,include,dispatch,state}),dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
1
+ 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 getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=getSdk(config);try{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,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{const options={};state?.include&&state.include.length>0&&(options.include=state.include),console.log("includes",options);const order=await sdk.orders.retrieve(id,options);return console.log("order",order),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,"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=getSdk(config);try{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}}catch(error){const errors=getErrors(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}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,console.log(payload);debugger;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}=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;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:!0,bundle_code:bundleCode},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){const{organization}=getOrganizationSlug(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors(error,"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}})},setGiftCardOrCouponCode=async({code,codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},removeGiftCardOrCouponCode=async({codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&dispatch){const attributes={[codeType]:""};return await updateOrder({id:order.id,attributes,config,include,dispatch,state}),dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
@@ -15,7 +15,7 @@ interface TParams<C> {
15
15
  /**
16
16
  * Key of the context to check
17
17
  */
18
- key?: string;
18
+ key: string;
19
19
  }
20
20
  export default function useCustomContext<T>({ context, key, currentComponentName, contextComponentName }: TParams<T>): T;
21
21
  export {};
@@ -1 +1 @@
1
- import{useContext}from"react";export default function useCustomContext({context,key,currentComponentName,contextComponentName}){const currentContext=useContext(context),isProduction=process.env.NODE_ENV==="production",msg=`Cannot use <${currentComponentName}/> outside of <${contextComponentName}/>`;if(key!=null&&key in currentContext||key==null&&currentContext!=null||currentContext!=null)return currentContext;if(isProduction)console.error(msg);else throw new Error(msg);return currentContext}
1
+ import{useContext}from"react";export default function useCustomContext({context,key,currentComponentName,contextComponentName}){const currentContext=useContext(context),isProduction=process.env.NODE_ENV==="production",msg=`Cannot use <${currentComponentName}/> outside of <${contextComponentName}/>`;if(key!=null&&key in currentContext||key==null&&currentContext!=null)return currentContext;if(isProduction)console.error(msg);else throw new Error(msg);return currentContext}