@commercelayer/react-components 4.27.0-beta.0 → 4.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=CustomerContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({customerAddressId}){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({pageNumber,pageSize:pageSize2,sortBy}){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})}),getCustomerSubscriptions:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({pageNumber,pageSize:pageSize2,id}){yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize:pageSize2,id})}),reloadCustomerAddresses:()=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.default=CustomerContainer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=CustomerContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({customerAddressId}){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({pageNumber,pageSize:pageSize2,sortBy}){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})}),getCustomerSubscriptions:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({pageNumber,pageSize:pageSize2,sortBy,id}){yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})}),reloadCustomerAddresses:()=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.default=CustomerContainer;
@@ -1,6 +1,6 @@
1
+ import type { Order, OrderCreate } from "@commercelayer/sdk";
1
2
  import { type JSX } from "react";
2
3
  import type { BaseMetadataObject } from "../../typings/index";
3
- import type { OrderCreate, Order } from "@commercelayer/sdk";
4
4
  import type { DefaultChildrenType } from "../../typings/globals";
5
5
  interface Props {
6
6
  children: DefaultChildrenType;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=OrderContainer;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){var _a,_b,_c;const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=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),getOrder=localOrder=>tslib_1.__awaiter(this,void 0,void 0,function*(){const removeOrderPlaced=!!(persistKey&&clearWhenPlaced);localOrder&&(yield(0,OrderReducer_1.getApiOrder)({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:removeOrderPlaced,deleteLocalOrder,state}))});(0,react_1.useEffect)(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),(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)(()=>{var _a2,_b2;const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>{var _a3;return((_a3=state?.includeLoaded)===null||_a3===void 0?void 0:_a3[key])===!0});return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&((_a2=state.include)===null||_a2===void 0?void 0:_a2.length)===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!(!((_b2=state.include)===null||_b2===void 0)&&_b2.length)&&startRequest.length===0)&&getOrder(localOrder):[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}}),()=>{var _a3,_b3;state.order==null&&state.loading&&state.withoutIncludes===!1&&(((_a3=state.include)===null||_a3===void 0?void 0:_a3.length)===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&((_b3=state.include)===null||_b3===void 0?void 0:_b3.length)>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys((_a=state.includeLoaded)!==null&&_a!==void 0?_a:{}).length,(_b=state.include)===null||_b===void 0?void 0:_b.length,orderId,Object.keys((_c=state?.order)!==null&&_c!==void 0?_c:{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=(0,react_1.useMemo)(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),Object.assign(Object.assign({},state),{manageAdyenGiftCard,paymentSourceRequest:params=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.paymentSourceRequest)(Object.assign(Object.assign({},params),{dispatch,state,config}))}),setOrder:order=>{(0,OrderReducer_1.setOrder)(order,dispatch)},getOrder:id=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.getApiOrder)({id,dispatch,config,state})}),setOrderErrors:errors=>(0,OrderReducer_1.setOrderErrors)({dispatch,errors}),createOrder:()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.createOrder)({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder})}),addToCart:params=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.addToCart)(Object.assign(Object.assign({},params),{persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}))}),saveAddressToCustomerAddressBook:args=>{OrderContext_1.defaultOrderContext.saveAddressToCustomerAddressBook(Object.assign(Object.assign({},args),{dispatch}))},setGiftCardOrCouponCode:_a2=>tslib_1.__awaiter(this,[_a2],void 0,function*({code,codeType}){return yield OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state})}),removeGiftCardOrCouponCode:_a2=>tslib_1.__awaiter(this,[_a2],void 0,function*({codeType}){return yield OrderContext_1.defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state})}),addResourceToInclude:args=>{OrderContext_1.defaultOrderContext.addResourceToInclude(Object.assign(Object.assign({},args),{dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded}))},updateOrder:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield OrderContext_1.defaultOrderContext.updateOrder(Object.assign(Object.assign({},args),{dispatch,config,include:state.include,state}))})})),[state,config.accessToken,persistKey]);return(0,jsx_runtime_1.jsx)(OrderContext_1.default.Provider,{value:orderValue,children})}exports.default=OrderContainer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=OrderContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){var _a,_b,_c;const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=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),getOrder=localOrder=>tslib_1.__awaiter(this,void 0,void 0,function*(){const removeOrderPlaced=!!(persistKey&&clearWhenPlaced);localOrder&&(yield(0,OrderReducer_1.getApiOrder)({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:removeOrderPlaced,deleteLocalOrder,state}))});(0,react_1.useEffect)(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),(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)(()=>{var _a2,_b2;const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>{var _a3;return((_a3=state?.includeLoaded)===null||_a3===void 0?void 0:_a3[key])===!0});return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&((_a2=state.include)===null||_a2===void 0?void 0:_a2.length)===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!(!((_b2=state.include)===null||_b2===void 0)&&_b2.length)&&startRequest.length===0)&&getOrder(localOrder):[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}}),()=>{var _a3,_b3;state.order==null&&state.loading&&state.withoutIncludes===!1&&(((_a3=state.include)===null||_a3===void 0?void 0:_a3.length)===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&((_b3=state.include)===null||_b3===void 0?void 0:_b3.length)>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys((_a=state.includeLoaded)!==null&&_a!==void 0?_a:{}).length,(_b=state.include)===null||_b===void 0?void 0:_b.length,orderId,Object.keys((_c=state?.order)!==null&&_c!==void 0?_c:{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=(0,react_1.useMemo)(()=>(fetchOrder!=null&&state?.order!=null&&(console.log("OrderContainer: triggering fetchOrder callback",state.order),fetchOrder(state.order)),Object.assign(Object.assign({},state),{manageAdyenGiftCard,paymentSourceRequest:params=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.paymentSourceRequest)(Object.assign(Object.assign({},params),{dispatch,state,config}))}),setOrder:order=>{(0,OrderReducer_1.setOrder)(order,dispatch)},getOrder:id=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.getApiOrder)({id,dispatch,config,state})}),setOrderErrors:errors=>(0,OrderReducer_1.setOrderErrors)({dispatch,errors}),createOrder:()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.createOrder)({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder})}),addToCart:params=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,OrderReducer_1.addToCart)(Object.assign(Object.assign({},params),{persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}))}),saveAddressToCustomerAddressBook:args=>{OrderContext_1.defaultOrderContext.saveAddressToCustomerAddressBook(Object.assign(Object.assign({},args),{dispatch}))},setGiftCardOrCouponCode:_a2=>tslib_1.__awaiter(this,[_a2],void 0,function*({code,codeType}){return yield OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state})}),removeGiftCardOrCouponCode:_a2=>tslib_1.__awaiter(this,[_a2],void 0,function*({codeType}){return yield OrderContext_1.defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state})}),addResourceToInclude:args=>{OrderContext_1.defaultOrderContext.addResourceToInclude(Object.assign(Object.assign({},args),{dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded}))},updateOrder:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield OrderContext_1.defaultOrderContext.updateOrder(Object.assign(Object.assign({},args),{dispatch,config,include:state.include,state}))})})),[state,config.accessToken,persistKey]);return(0,jsx_runtime_1.jsx)(OrderContext_1.default.Provider,{value:orderValue,children})}exports.default=OrderContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderList=OrderList;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderListChildrenContext_1=tslib_1.__importDefault(require("../../context/OrderListChildrenContext")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),react_table_1=require("@tanstack/react-table"),icons_1=require("../../utils/icons"),filterChildren_1=tslib_1.__importDefault(require("../../utils/filterChildren")),rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];function OrderList(_a){var _b,_c,_d,_e,_f,{id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName}=_a,p=tslib_1.__rest(_a,["id","type","children","columns","loadingElement","showActions","showPagination","sortBy","pageSize","paginationContainerClassName","actionsComponent","actionsContainerClassName","theadClassName","rowTrClassName"]);const[loading,setLoading]=(0,react_1.useState)(!0),[sorting,setSorting]=(0,react_1.useState)(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=(0,react_1.useState)({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=(0,react_1.useContext)(CustomerContext_1.default),defaultSdkSorting=sortBy.length&&sortBy[0]!=null?{[sortBy[0].id]:sortBy[0].desc?"desc":"asc"}:void 0;(0,react_1.useEffect)(()=>{const sdkSorting=sorting.length&&sorting[0]!=null?{[sorting[0].id]:sorting[0].desc?"desc":"asc"}:defaultSdkSorting;type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,id})},[pageIndex,currentPageSize,sorting,id!=null]);const data=(0,react_1.useMemo)(()=>{var _a2;return type==="orders"?orders??[]:id==null?subscriptions??[]:((_a2=subscriptions?.[0])===null||_a2===void 0?void 0:_a2.type)==="orders"?subscriptions:[]},[orders,subscriptions]),cols=(0,react_1.useMemo)(()=>columns,[columns]),pagination=(0,react_1.useMemo)(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=(_c=(_b=orders?.pageCount)!==null&&_b!==void 0?_b:subscriptions?.pageCount)!==null&&_c!==void 0?_c:-1,table=(0,react_table_1.useReactTable)({data,columns:cols,getSortedRowModel:(0,react_table_1.getSortedRowModel)(),getCoreRowModel:(0,react_table_1.getCoreRowModel)(),getPaginationRowModel:(0,react_table_1.getPaginationRowModel)(),manualPagination:!0,manualSorting:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";(0,react_1.useEffect)(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||(0,jsx_runtime_1.jsx)("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{var _a2,_b2,_c2,_d2;const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return(0,jsx_runtime_1.jsx)(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:(_a2=columns[k])===null||_a2===void 0?void 0:_a2.className,children:(0,jsx_runtime_1.jsxs)("span",{className:`${(_c2=(_b2=columns[k])===null||_b2===void 0?void 0:_b2.titleClassName)!==null&&_c2!==void 0?_c2:""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[(0,react_table_1.flexRender)(header.column.columnDef.header,header.getContext()),(_d2={asc:icons_1.sortAscIcon,desc:icons_1.sortDescIcon}[header.column.getIsSorted()])!==null&&_d2!==void 0?_d2:null]})},header.id)});return(0,jsx_runtime_1.jsx)(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=(0,filterChildren_1.default)({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return(0,jsx_runtime_1.jsx)(TrHtmlElement,{className:rowTrClassName,children:(0,jsx_runtime_1.jsx)(OrderListChildrenContext_1.default.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=(0,filterChildren_1.default)({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?(_d=orders?.meta.recordCount)!==null&&_d!==void 0?_d:0:(_e=subscriptions?.meta.recordCount)!==null&&_e!==void 0?_e:0,Pagination=()=>showPagination?(0,jsx_runtime_1.jsx)(OrderListPaginationContext_1.default.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:LoadingComponent}):((_f=type==="orders"?orders:subscriptions)===null||_f===void 0?void 0:_f.length)===0?(0,jsx_runtime_1.jsxs)(OrderListChildrenContext_1.default.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,(0,jsx_runtime_1.jsx)(Pagination,{})]}):(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,jsx_runtime_1.jsxs)(TableHtmlElement,Object.assign({},p,{children:[(0,jsx_runtime_1.jsx)(TheadHtmlElement,{className:theadClassName,children:headerComponent}),(0,jsx_runtime_1.jsx)(TbodyHtmlElement,{children:components})]})),totalRows<=pageSize?null:(0,jsx_runtime_1.jsx)("div",{className:paginationContainerClassName,children:(0,jsx_runtime_1.jsx)(Pagination,{})})]})}exports.default=OrderList;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderList=OrderList;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderListChildrenContext_1=tslib_1.__importDefault(require("../../context/OrderListChildrenContext")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),react_table_1=require("@tanstack/react-table"),icons_1=require("../../utils/icons"),filterChildren_1=tslib_1.__importDefault(require("../../utils/filterChildren")),rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];function OrderList(_a){var _b,_c,_d,_e,_f,{id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName}=_a,p=tslib_1.__rest(_a,["id","type","children","columns","loadingElement","showActions","showPagination","sortBy","pageSize","paginationContainerClassName","actionsComponent","actionsContainerClassName","theadClassName","rowTrClassName"]);const[loading,setLoading]=(0,react_1.useState)(!0),[sorting,setSorting]=(0,react_1.useState)(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=(0,react_1.useState)({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=(0,react_1.useContext)(CustomerContext_1.default),defaultSdkSorting=sortBy.length&&sortBy[0]!=null?{[sortBy[0].id]:sortBy[0].desc?"desc":"asc"}:void 0;(0,react_1.useEffect)(()=>{const sdkSorting=sorting.length&&sorting[0]!=null?{[sorting[0].id]:sorting[0].desc?"desc":"asc"}:defaultSdkSorting;type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting,id})},[pageIndex,currentPageSize,sorting,id!=null]);const data=(0,react_1.useMemo)(()=>{var _a2;return type==="orders"?orders??[]:id==null?subscriptions??[]:((_a2=subscriptions?.[0])===null||_a2===void 0?void 0:_a2.type)==="orders"?subscriptions:[]},[orders,subscriptions]),cols=(0,react_1.useMemo)(()=>columns,[columns]),pagination=(0,react_1.useMemo)(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=(_c=(_b=orders?.pageCount)!==null&&_b!==void 0?_b:subscriptions?.pageCount)!==null&&_c!==void 0?_c:-1,table=(0,react_table_1.useReactTable)({data,columns:cols,getSortedRowModel:(0,react_table_1.getSortedRowModel)(),getCoreRowModel:(0,react_table_1.getCoreRowModel)(),getPaginationRowModel:(0,react_table_1.getPaginationRowModel)(),manualPagination:!0,manualSorting:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";(0,react_1.useEffect)(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||(0,jsx_runtime_1.jsx)("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{var _a2,_b2,_c2,_d2;const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return(0,jsx_runtime_1.jsx)(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:(_a2=columns[k])===null||_a2===void 0?void 0:_a2.className,children:(0,jsx_runtime_1.jsxs)("span",{className:`${(_c2=(_b2=columns[k])===null||_b2===void 0?void 0:_b2.titleClassName)!==null&&_c2!==void 0?_c2:""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[(0,react_table_1.flexRender)(header.column.columnDef.header,header.getContext()),(_d2={asc:icons_1.sortAscIcon,desc:icons_1.sortDescIcon}[header.column.getIsSorted()])!==null&&_d2!==void 0?_d2:null]})},header.id)});return(0,jsx_runtime_1.jsx)(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=(0,filterChildren_1.default)({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return(0,jsx_runtime_1.jsx)(TrHtmlElement,{className:rowTrClassName,children:(0,jsx_runtime_1.jsx)(OrderListChildrenContext_1.default.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=(0,filterChildren_1.default)({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?(_d=orders?.meta.recordCount)!==null&&_d!==void 0?_d:0:(_e=subscriptions?.meta.recordCount)!==null&&_e!==void 0?_e:0,Pagination=()=>showPagination?(0,jsx_runtime_1.jsx)(OrderListPaginationContext_1.default.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:LoadingComponent}):((_f=type==="orders"?orders:subscriptions)===null||_f===void 0?void 0:_f.length)===0?(0,jsx_runtime_1.jsxs)(OrderListChildrenContext_1.default.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,(0,jsx_runtime_1.jsx)(Pagination,{})]}):(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,jsx_runtime_1.jsxs)(TableHtmlElement,Object.assign({},p,{children:[(0,jsx_runtime_1.jsx)(TheadHtmlElement,{className:theadClassName,children:headerComponent}),(0,jsx_runtime_1.jsx)(TbodyHtmlElement,{children:components})]})),totalRows<=pageSize?null:(0,jsx_runtime_1.jsx)("div",{className:paginationContainerClassName,children:(0,jsx_runtime_1.jsx)(Pagination,{})})]})}exports.default=OrderList;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){var _a,_b,_c,_d,_e,_f,_g;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,((_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit)!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),(0,react_1.useEffect)(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){console.log("Stripe redirect flow");const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e2=options?.adyen)===null||_e2===void 0)&&_e2.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f2=options?.adyen)===null||_f2===void 0?void 0:_f2.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!(!((_g2=options?.adyen)===null||_g2===void 0)&&_g2.redirectResult)&&!((_k=(_j=(_h=order?.payment_source)===null||_h===void 0?void 0:_h.payment_response)===null||_j===void 0?void 0:_j.merchantReference)===null||_k===void 0)&&_k.includes(order?.number)&&handleClick()}},[((_c=options?.adyen)===null||_c===void 0?void 0:_c.redirectResult)!=null,(_e=(_d=order?.payment_source)===null||_d===void 0?void 0:_d.payment_response)===null||_e===void 0?void 0:_e.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(console.log("Checkout.com redirect flow",{order,status}),paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentResponse=(_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.payment_response,paymentStatus=paymentResponse?.status;paymentStatus&&paymentStatus.toLowerCase()==="pending"&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3;const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}),paymentStatus2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})}()}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){console.log("Placing order with Checkout.com express payments");const paymentSourceStatus=(_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_response)===null||_d2===void 0?void 0:_d2.status;console.log("Payment source status:",paymentSourceStatus),paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[(_f=options?.checkoutCom)===null||_f===void 0?void 0:_f.session_id,(_g=order?.payment_source)===null||_g===void 0?void 0:_g.id,status]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k,_l;e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=yield sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e2=checkPaymentSource?.payment_response)===null||_e2===void 0?void 0:_e2.resultCode)==="Authorised"&&(isValid=!0)):!((_f2=currentPaymentMethodRef?.current)===null||_f2===void 0)&&_f2.onsubmit&&(!((_g2=options?.checkoutCom)===null||_g2===void 0)&&_g2.session_id)&&(!((_h=checkPaymentSource?.payment_response)===null||_h===void 0)&&_h.status)&&((_k=(_j=checkPaymentSource?.payment_response)===null||_j===void 0?void 0:_j.status)===null||_k===void 0?void 0:_k.toLowerCase())==="declined"?isValid=yield(_l=currentPaymentMethodRef.current)===null||_l===void 0?void 0:_l.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){var _a,_b,_c,_d,_e,_f,_g;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,((_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit)!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),(0,react_1.useEffect)(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e2=options?.adyen)===null||_e2===void 0)&&_e2.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f2=options?.adyen)===null||_f2===void 0?void 0:_f2.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!(!((_g2=options?.adyen)===null||_g2===void 0)&&_g2.redirectResult)&&!((_k=(_j=(_h=order?.payment_source)===null||_h===void 0?void 0:_h.payment_response)===null||_j===void 0?void 0:_j.merchantReference)===null||_k===void 0)&&_k.includes(order?.number)&&handleClick()}},[((_c=options?.adyen)===null||_c===void 0?void 0:_c.redirectResult)!=null,(_e=(_d=order?.payment_source)===null||_d===void 0?void 0:_d.payment_response)===null||_e===void 0?void 0:_e.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentResponse=(_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.payment_response,paymentStatus=paymentResponse?.status;paymentStatus&&paymentStatus.toLowerCase()==="pending"&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3;const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}),paymentStatus2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})}()}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=(_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_response)===null||_d2===void 0?void 0:_d2.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[(_f=options?.checkoutCom)===null||_f===void 0?void 0:_f.session_id,(_g=order?.payment_source)===null||_g===void 0?void 0:_g.id,status]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h,_j,_k,_l;e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=yield sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e2=checkPaymentSource?.payment_response)===null||_e2===void 0?void 0:_e2.resultCode)==="Authorised"&&(isValid=!0)):!((_f2=currentPaymentMethodRef?.current)===null||_f2===void 0)&&_f2.onsubmit&&(!((_g2=options?.checkoutCom)===null||_g2===void 0)&&_g2.session_id)&&(!((_h=checkPaymentSource?.payment_response)===null||_h===void 0)&&_h.status)&&((_k=(_j=checkPaymentSource?.payment_response)===null||_j===void 0?void 0:_j.status)===null||_k===void 0?void 0:_k.toLowerCase())==="declined"?isValid=yield(_l=currentPaymentMethodRef.current)===null||_l===void 0?void 0:_l.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})))}),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"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),jwt_1=require("../../utils/jwt"),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),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","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=>{ref.current&&component.isValid()&&(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)},onPaymentCompleted:(_component,paymentResponse)=>tslib_1.__awaiter(this,void 0,void 0,function*(){console.log("onPaymentCompleted",{paymentResponse}),paymentResponse.status.toLowerCase()==="approved"&&(yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))})})).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"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),jwt_1=require("../../utils/jwt"),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),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","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=>{ref.current&&component.isValid()&&(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)},onPaymentCompleted:(_component,paymentResponse)=>tslib_1.__awaiter(this,void 0,void 0,function*(){paymentResponse.status.toLowerCase()==="approved"&&(yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))})})).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;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),localStorage_1=require("../../utils/localStorage"),StripeExpressPayment_1=require("./StripeExpressPayment"),defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.useEffect)(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield onSubmit({event:ref.current,stripe,elements})}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=_a=>tslib_1.__awaiter(this,[_a],void 0,function*({event,stripe:stripe2,elements:elements2}){var _b,_c,_d,_e,_f,_g,_h;if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=(_c=(_b=event?.elements)===null||_b===void 0?void 0:_b.save_payment_source_to_customer_wallet)===null||_c===void 0?void 0:_c.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=(_d=order?.customer_email)!==null&&_d!==void 0?_d:"",billingDetails={name:(_e=billingInfo?.full_name)!==null&&_e!==void 0?_e:"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:(_f=billingInfo?.line_2)!==null&&_f!==void 0?_f:"",postal_code:(_g=billingInfo?.zip_code)!==null&&_g!==void 0?_g:"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error,paymentIntent}=yield stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return console.log({paymentIntent}),error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:(_h=error.message)!==null&&_h!==void 0?_h:""}]),!1):!0}return!1});function handleChange(event){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}})}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:Object.assign(Object.assign({},defaultOptions),options),onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment(_a){var{publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount}=_a,p=tslib_1.__rest(_a,["publishableKey","show","options","clientSecret","locale","expressPayments","connectedAccount"]);const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","fonts","appearance"]);(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{tslib_1.__awaiter(this,void 0,void 0,function*(){const options2=Object.assign({locale},connectedAccount?{stripeAccount:connectedAccount}:{}),res=yield loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:Object.assign(Object.assign({},defaultAppearance),appearance),fonts};return isLoaded&&stripe!=null&&clientSecret!=null?(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)(react_stripe_js_1.Elements,{stripe,options:elementsOptions,children:expressPayments?(0,jsx_runtime_1.jsx)(StripeExpressPayment_1.StripeExpressPayment,{clientSecret}):(0,jsx_runtime_1.jsx)(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})})):null}exports.default=StripePayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),localStorage_1=require("../../utils/localStorage"),StripeExpressPayment_1=require("./StripeExpressPayment"),defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.useEffect)(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield onSubmit({event:ref.current,stripe,elements})}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=_a=>tslib_1.__awaiter(this,[_a],void 0,function*({event,stripe:stripe2,elements:elements2}){var _b,_c,_d,_e,_f,_g,_h;if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=(_c=(_b=event?.elements)===null||_b===void 0?void 0:_b.save_payment_source_to_customer_wallet)===null||_c===void 0?void 0:_c.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=(_d=order?.customer_email)!==null&&_d!==void 0?_d:"",billingDetails={name:(_e=billingInfo?.full_name)!==null&&_e!==void 0?_e:"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:(_f=billingInfo?.line_2)!==null&&_f!==void 0?_f:"",postal_code:(_g=billingInfo?.zip_code)!==null&&_g!==void 0?_g:"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=yield stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:(_h=error.message)!==null&&_h!==void 0?_h:""}]),!1):!0}return!1});function handleChange(event){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=yield sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}})}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:Object.assign(Object.assign({},defaultOptions),options),onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment(_a){var{publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount}=_a,p=tslib_1.__rest(_a,["publishableKey","show","options","clientSecret","locale","expressPayments","connectedAccount"]);const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","fonts","appearance"]);(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{tslib_1.__awaiter(this,void 0,void 0,function*(){const options2=Object.assign({locale},connectedAccount?{stripeAccount:connectedAccount}:{}),res=yield loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:Object.assign(Object.assign({},defaultAppearance),appearance),fonts};return isLoaded&&stripe!=null&&clientSecret!=null?(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)(react_stripe_js_1.Elements,{stripe,options:elementsOptions,children:expressPayments?(0,jsx_runtime_1.jsx)(StripeExpressPayment_1.StripeExpressPayment,{clientSecret}):(0,jsx_runtime_1.jsx)(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})})):null}exports.default=StripePayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setCloneAddress=exports.setAddressErrors=exports.addressInitialState=exports.addressFields=void 0,exports.setAddress=setAddress,exports.saveAddresses=saveAddresses;const tslib_1=require("tslib"),camelCase_1=tslib_1.__importDefault(require("lodash/camelCase")),addressesManager_1=require("../utils/addressesManager"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),formCleaner_1=require("../utils/formCleaner"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk"));exports.addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],exports.addressInitialState={errors:[]};const setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};exports.setAddressErrors=setAddressErrors;function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:Object.assign({},(0,formCleaner_1.formCleaner)(values))};dispatch&&dispatch({type:"setAddress",payload})}const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${(0,camelCase_1.default)(resource)}Id`]:id}})};exports.setCloneAddress=setCloneAddress;function saveAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,updateOrder,order,state,customerEmail,customerAddress}){var _b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o;const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=(0,getSdk_1.default)(config),billingAddress=(0,formCleaner_1.formCleaner)(billingAddressForm),shippingAddress=(0,formCleaner_1.formCleaner)(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=yield(0,addressesManager_1.invertedAddressesHandler)({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=(_b=order?.line_items)===null||_b===void 0?void 0:_b.every(lineItem=>{var _a2;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.do_not_ship)===!0}),currentBillingAddressRef=(_c=order?.billing_address)===null||_c===void 0?void 0:_c.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=(_d=order?.billing_address)===null||_d===void 0?void 0:_d.id,orderAttributes._shipping_address_clone_id=(_e=order?.shipping_address)===null||_e===void 0?void 0:_e.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(billingAddress);let address;!((_f=order?.billing_address)===null||_f===void 0)&&_f.id&&((_g=order?.billing_address)===null||_g===void 0?void 0:_g.reference)==null?address=yield sdk.addresses.update(Object.assign({id:order.billing_address.id},billingAddressWithMeta)):(address=yield sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(shippingAddress);let address;!((_h=order?.shipping_address)===null||_h===void 0)&&_h.id&&((_j=order?.shipping_address)===null||_j===void 0?void 0:_j.reference)==null?address=yield sdk.addresses.update(Object.assign({id:order.shipping_address.id},shippingAddressWithMeta)):(address=yield sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder){const orderUpdated=yield updateOrder({id:order.id,attributes:orderAttributes});return(!((_k=order?.billing_address)===null||_k===void 0)&&_k.id&&((_l=order?.billing_address)===null||_l===void 0?void 0:_l.reference)==null||!((_m=order?.shipping_address)===null||_m===void 0)&&_m.id&&((_o=order?.shipping_address)===null||_o===void 0?void 0:_o.reference)==null)&&(yield updateOrder({id:order.id,attributes:{_refresh:!0}})),{success:!0,order:orderUpdated?.order}}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}})}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=addressReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setCloneAddress=exports.setAddressErrors=exports.addressInitialState=exports.addressFields=void 0,exports.setAddress=setAddress,exports.saveAddresses=saveAddresses;const tslib_1=require("tslib"),camelCase_1=tslib_1.__importDefault(require("lodash/camelCase")),addressesManager_1=require("../utils/addressesManager"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),formCleaner_1=require("../utils/formCleaner"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk"));exports.addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],exports.addressInitialState={errors:[]};const setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};exports.setAddressErrors=setAddressErrors;function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:Object.assign({},(0,formCleaner_1.formCleaner)(values))};dispatch&&dispatch({type:"setAddress",payload})}const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${(0,camelCase_1.default)(resource)}Id`]:id}})};exports.setCloneAddress=setCloneAddress;function saveAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,updateOrder,order,state,customerEmail,customerAddress}){var _b,_c,_d,_e,_f,_g,_h,_j;const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=(0,getSdk_1.default)(config),billingAddress=(0,formCleaner_1.formCleaner)(billingAddressForm),shippingAddress=(0,formCleaner_1.formCleaner)(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=yield(0,addressesManager_1.invertedAddressesHandler)({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=(_b=order?.line_items)===null||_b===void 0?void 0:_b.every(lineItem=>{var _a2;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.do_not_ship)===!0}),currentBillingAddressRef=(_c=order?.billing_address)===null||_c===void 0?void 0:_c.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=(_d=order?.billing_address)===null||_d===void 0?void 0:_d.id,orderAttributes._shipping_address_clone_id=(_e=order?.shipping_address)===null||_e===void 0?void 0:_e.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(billingAddress);let address;!((_f=order?.billing_address)===null||_f===void 0)&&_f.id&&((_g=order?.billing_address)===null||_g===void 0?void 0:_g.reference)==null?address=yield sdk.addresses.update(Object.assign({id:order.billing_address.id},billingAddressWithMeta)):(address=yield sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(shippingAddress);let address;!((_h=order?.shipping_address)===null||_h===void 0)&&_h.id&&((_j=order?.shipping_address)===null||_j===void 0?void 0:_j.reference)==null?address=yield sdk.addresses.update(Object.assign({id:order.shipping_address.id},shippingAddressWithMeta)):(address=yield sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder){const orderUpdated=yield updateOrder({id:order.id,attributes:orderAttributes});return{success:!0,order:orderUpdated?.order}}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}})}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=addressReducer;
@@ -104,8 +104,7 @@ export interface GetCustomerPaymentSources {
104
104
  order?: Order;
105
105
  }
106
106
  export declare function getCustomerPaymentSources(params?: GetCustomerPaymentSources): void;
107
- type GetCustomerOrdersResource = Order | OrderSubscription;
108
- interface GetCustomerOrdersProps<T extends GetCustomerOrdersResource> {
107
+ interface GetCustomerOrdersProps {
109
108
  /**
110
109
  * The Commerce Layer config
111
110
  */
@@ -125,14 +124,14 @@ interface GetCustomerOrdersProps<T extends GetCustomerOrdersResource> {
125
124
  /**
126
125
  * The sort order
127
126
  */
128
- sortBy?: QuerySort<T>;
127
+ sortBy?: QuerySort<Order>;
129
128
  /**
130
129
  * Retrieve a specific subscription or order by id
131
130
  */
132
131
  id?: string;
133
132
  }
134
- export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps<Order>): Promise<void>;
135
- export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps<OrderSubscription>): Promise<void>;
133
+ export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps): Promise<void>;
134
+ export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps): Promise<void>;
136
135
  export type TCustomerAddress = AddressCreate & AddressUpdate & Record<string, string | null | undefined>;
137
136
  interface TCreateCustomerAddress {
138
137
  /**
@@ -153,7 +152,7 @@ interface TCreateCustomerAddress {
153
152
  state?: CustomerState;
154
153
  }
155
154
  export declare function createCustomerAddress({ address, config, dispatch, state }: TCreateCustomerAddress): Promise<void>;
156
- interface GetCustomerPaymentsParams extends GetCustomerOrdersProps<Order> {
155
+ interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
157
156
  }
158
157
  export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
159
158
  export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");function saveCustomerUser(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}function getCustomerAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}function deleteCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{yield(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}})}function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}function getCustomerOrders(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}function getCustomerSubscriptions(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(id!=null){const subscriptions=yield sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=yield sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}})}function createCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({address,config,dispatch,state}){var _b,_c,_d;if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),upAddress=yield sdk.addresses.update(addressWithMeta),updatedAddresses=(_b=state?.addresses)===null||_b===void 0?void 0:_b.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),newAddress=yield sdk.addresses.create(addressWithMeta);if(!((_c=state?.customers)===null||_c===void 0)&&_c.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_d=state?.customers)===null||_d===void 0?void 0:_d.id),address:sdk.addresses.relationship(newAddress.id)});yield sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}})}function getCustomerPayments(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const payments=yield sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}})}function getCustomerInfo(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=yield sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}})}function setResourceTrigger(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if((yield(0,triggerAttributeHelper_1.triggerAttributeHelper)(params))!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":yield getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":yield getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}}return!1})}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");function saveCustomerUser(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}function getCustomerAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}function deleteCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{yield(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}})}function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}function getCustomerOrders(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}function getCustomerSubscriptions(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(id!=null){const subscriptions=yield sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=yield sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}})}function createCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({address,config,dispatch,state}){var _b,_c,_d;if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),upAddress=yield sdk.addresses.update(addressWithMeta),updatedAddresses=(_b=state?.addresses)===null||_b===void 0?void 0:_b.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),newAddress=yield sdk.addresses.create(addressWithMeta);if(!((_c=state?.customers)===null||_c===void 0)&&_c.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_d=state?.customers)===null||_d===void 0?void 0:_d.id),address:sdk.addresses.relationship(newAddress.id)});yield sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}})}function getCustomerPayments(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const payments=yield sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}})}function getCustomerInfo(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=yield sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}})}function setResourceTrigger(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if((yield(0,triggerAttributeHelper_1.triggerAttributeHelper)(params))!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":yield getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":yield getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}}return!1})}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&getCustomerPayments({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize:pageSize2,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
@@ -1,6 +1,6 @@
1
+ import type { Order, OrderCreate } from "@commercelayer/sdk";
1
2
  import { type JSX } from "react";
2
3
  import type { BaseMetadataObject } from "../../typings/index";
3
- import type { OrderCreate, Order } from "@commercelayer/sdk";
4
4
  import type { DefaultChildrenType } from "../../typings/globals";
5
5
  interface Props {
6
6
  children: DefaultChildrenType;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- 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,paymentSourceRequest}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,manageAdyenGiftCard}=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),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),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);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[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,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,manageAdyenGiftCard,paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),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,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo,useReducer,useState}from"react";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import orderReducer,{addToCart,createOrder,getApiOrder,orderInitialState,paymentSourceRequest,setOrder,setOrderErrors,updateOrder}from"../../reducers/OrderReducer";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=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),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),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);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[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,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&(console.log("OrderContainer: triggering fetchOrder callback",state.order),fetchOrder(state.order)),{...state,manageAdyenGiftCard,paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),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,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useReactTable,getCoreRowModel,getPaginationRowModel,getSortedRowModel,flexRender}from"@tanstack/react-table";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),[sorting,setSorting]=useState(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=useState({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=useContext(CustomerContext),defaultSdkSorting=sortBy.length&&sortBy[0]!=null?{[sortBy[0].id]:sortBy[0].desc?"desc":"asc"}:void 0;useEffect(()=>{const sdkSorting=sorting.length&&sorting[0]!=null?{[sorting[0].id]:sorting[0].desc?"desc":"asc"}:defaultSdkSorting;type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,id})},[pageIndex,currentPageSize,sorting,id!=null]);const data=useMemo(()=>type==="orders"?orders??[]:id==null?subscriptions??[]:subscriptions?.[0]?.type==="orders"?subscriptions:[],[orders,subscriptions]),cols=useMemo(()=>columns,[columns]),pagination=useMemo(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=orders?.pageCount??subscriptions?.pageCount??-1,table=useReactTable({data,columns:cols,getSortedRowModel:getSortedRowModel(),getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),manualPagination:!0,manualSorting:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";useEffect(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:columns[k]?.className,children:_jsxs("span",{className:`${columns[k]?.titleClassName??""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[flexRender(header.column.columnDef.header,header.getContext()),{asc:sortAscIcon,desc:sortDescIcon}[header.column.getIsSorted()]??null]})},header.id)});return _jsx(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return _jsx(TrHtmlElement,{className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?orders?.meta.recordCount??0:subscriptions?.meta.recordCount??0,Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?_jsx(_Fragment,{children:LoadingComponent}):(type==="orders"?orders:subscriptions)?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{children:components})]}),totalRows<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
2
+ import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useReactTable,getCoreRowModel,getPaginationRowModel,getSortedRowModel,flexRender}from"@tanstack/react-table";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),[sorting,setSorting]=useState(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=useState({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=useContext(CustomerContext),defaultSdkSorting=sortBy.length&&sortBy[0]!=null?{[sortBy[0].id]:sortBy[0].desc?"desc":"asc"}:void 0;useEffect(()=>{const sdkSorting=sorting.length&&sorting[0]!=null?{[sorting[0].id]:sorting[0].desc?"desc":"asc"}:defaultSdkSorting;type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,sortBy:sdkSorting,id})},[pageIndex,currentPageSize,sorting,id!=null]);const data=useMemo(()=>type==="orders"?orders??[]:id==null?subscriptions??[]:subscriptions?.[0]?.type==="orders"?subscriptions:[],[orders,subscriptions]),cols=useMemo(()=>columns,[columns]),pagination=useMemo(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=orders?.pageCount??subscriptions?.pageCount??-1,table=useReactTable({data,columns:cols,getSortedRowModel:getSortedRowModel(),getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),manualPagination:!0,manualSorting:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";useEffect(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:columns[k]?.className,children:_jsxs("span",{className:`${columns[k]?.titleClassName??""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[flexRender(header.column.columnDef.header,header.getContext()),{asc:sortAscIcon,desc:sortDescIcon}[header.column.getIsSorted()]??null]})},header.id)});return _jsx(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return _jsx(TrHtmlElement,{className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?orders?.meta.recordCount??0:subscriptions?.meta.recordCount??0,Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?_jsx(_Fragment,{children:LoadingComponent}):(type==="orders"?orders:subscriptions)?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{children:components})]}),totalRows<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){console.log("Stripe redirect flow");const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(console.log("Checkout.com redirect flow",{order,status}),paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){console.log("Placing order with Checkout.com express payments");const paymentSourceStatus=order?.payment_source?.payment_response?.status;console.log("Payment source status:",paymentSourceStatus),paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null&&(placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;if(!(paymentType==="stripe_payments")){const{status:status2}=await sdk.orders.retrieve(order?.id,{fields:["status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);let isValid=!0;const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null&&(placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})))},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 Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";import{jwt}from"../../utils/jwt";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),{setPlaceOrderStatus}=useContext(PlaceOrderContext),{containerClassName,templateCustomerSaveToWallet,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=>{ref.current&&component.isValid()&&(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)},onPaymentCompleted:async(_component,paymentResponse)=>{console.log("onPaymentCompleted",{paymentResponse}),paymentResponse.status.toLowerCase()==="approved"&&(await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))}})).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 Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";import{jwt}from"../../utils/jwt";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),{setPlaceOrderStatus}=useContext(PlaceOrderContext),{containerClassName,templateCustomerSaveToWallet,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=>{ref.current&&component.isValid()&&(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)},onPaymentCompleted:async(_component,paymentResponse)=>{paymentResponse.status.toLowerCase()==="approved"&&(await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}}),setPlaceOrderStatus?.({status:"placing"}))}})).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;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error,paymentIntent}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return console.log({paymentIntent}),error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message??""}]),!1):!0}return!1};async function handleChange(event){if(console.debug("StripePaymentElement onChange event",{event}),selectedPaymentMethodType=event.value.type,event.complete&&["apple_pay","google_pay"].includes(event.value.type)){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import baseReducer from"../utils/baseReducer";import{formCleaner}from"../utils/formCleaner";import getSdk from"../utils/getSdk";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config),billingAddress=formCleaner(billingAddressForm),shippingAddress=formCleaner(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=sanitizeMetadataFields(shippingAddress);let address;order?.shipping_address?.id&&order?.shipping_address?.reference==null?address=await sdk.addresses.update({id:order.shipping_address.id,...shippingAddressWithMeta}):(address=await sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder){const orderUpdated=await updateOrder({id:order.id,attributes:orderAttributes});return(order?.billing_address?.id&&order?.billing_address?.reference==null||order?.shipping_address?.id&&order?.shipping_address?.reference==null)&&await updateOrder({id:order.id,attributes:{_refresh:!0}}),{success:!0,order:orderUpdated?.order}}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default addressReducer;
2
+ import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import baseReducer from"../utils/baseReducer";import{formCleaner}from"../utils/formCleaner";import getSdk from"../utils/getSdk";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config),billingAddress=formCleaner(billingAddressForm),shippingAddress=formCleaner(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=sanitizeMetadataFields(shippingAddress);let address;order?.shipping_address?.id&&order?.shipping_address?.reference==null?address=await sdk.addresses.update({id:order.shipping_address.id,...shippingAddressWithMeta}):(address=await sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder)return{success:!0,order:(await updateOrder({id:order.id,attributes:orderAttributes}))?.order}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default addressReducer;
@@ -104,8 +104,7 @@ export interface GetCustomerPaymentSources {
104
104
  order?: Order;
105
105
  }
106
106
  export declare function getCustomerPaymentSources(params?: GetCustomerPaymentSources): void;
107
- type GetCustomerOrdersResource = Order | OrderSubscription;
108
- interface GetCustomerOrdersProps<T extends GetCustomerOrdersResource> {
107
+ interface GetCustomerOrdersProps {
109
108
  /**
110
109
  * The Commerce Layer config
111
110
  */
@@ -125,14 +124,14 @@ interface GetCustomerOrdersProps<T extends GetCustomerOrdersResource> {
125
124
  /**
126
125
  * The sort order
127
126
  */
128
- sortBy?: QuerySort<T>;
127
+ sortBy?: QuerySort<Order>;
129
128
  /**
130
129
  * Retrieve a specific subscription or order by id
131
130
  */
132
131
  id?: string;
133
132
  }
134
- export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps<Order>): Promise<void>;
135
- export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps<OrderSubscription>): Promise<void>;
133
+ export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps): Promise<void>;
134
+ export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber, sortBy }: GetCustomerOrdersProps): Promise<void>;
136
135
  export type TCustomerAddress = AddressCreate & AddressUpdate & Record<string, string | null | undefined>;
137
136
  interface TCreateCustomerAddress {
138
137
  /**
@@ -153,7 +152,7 @@ interface TCreateCustomerAddress {
153
152
  state?: CustomerState;
154
153
  }
155
154
  export declare function createCustomerAddress({ address, config, dispatch, state }: TCreateCustomerAddress): Promise<void>;
156
- interface GetCustomerPaymentsParams extends GetCustomerOrdersProps<Order> {
155
+ interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
157
156
  }
158
157
  export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
159
158
  export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
2
+ import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.27.0-beta.0",
3
+ "version": "4.27.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",