@commercelayer/react-components 4.7.4 → 4.7.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MyIdentityLink=void 0;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")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain");function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain}=props,p=tslib_1.__rest(props,["label","children","type","clientId","scope","returnUrl","customDomain"]),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,customDomain}),parentProps=Object.assign({label,href,clientId,scope},p);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({href},p,{children:label}))}exports.MyIdentityLink=MyIdentityLink,exports.default=MyIdentityLink;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MyIdentityLink=void 0;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")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain");function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain}=props,p=tslib_1.__rest(props,["label","children","type","clientId","scope","returnUrl","customDomain"]),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default),[href,setHref]=(0,react_1.useState)(void 0);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint);(0,react_1.useEffect)(()=>{const link=(0,getApplicationLink_1.getApplicationLink)({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,customDomain});return setHref(link),()=>{setHref(void 0)}},[]);const parentProps=Object.assign({label,href,clientId,scope},p);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({href},p,{children:label}))}exports.MyIdentityLink=MyIdentityLink,exports.default=MyIdentityLink;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){var _a,_b,_c;const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=(0,react_1.useReducer)(OrderReducer_1.default,OrderReducer_1.orderInitialState),[lock,setLock]=(0,react_1.useState)(!1),[lockOrder,setLockOrder]=(0,react_1.useState)(!0),config=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=(0,react_1.useContext)(OrderStorageContext_1.default),localOrder=persistKey?getLocalOrder(persistKey):orderId,getOrder=()=>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)(()=>{state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder():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 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():[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),{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:({code,codeType})=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state})}),removeGiftCardOrCouponCode:({codeType})=>tslib_1.__awaiter(this,void 0,void 0,function*(){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.OrderContainer=OrderContainer,exports.default=OrderContainer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){var _a,_b,_c;const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=(0,react_1.useReducer)(OrderReducer_1.default,OrderReducer_1.orderInitialState),[lock,setLock]=(0,react_1.useState)(!1),[lockOrder,setLockOrder]=(0,react_1.useState)(!0),config=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=(0,react_1.useContext)(OrderStorageContext_1.default),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),{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:({code,codeType})=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state})}),removeGiftCardOrCouponCode:({codeType})=>tslib_1.__awaiter(this,void 0,void 0,function*(){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.OrderContainer=OrderContainer,exports.default=OrderContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderList=void 0;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,{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,["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);(0,react_1.useEffect)(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex,pageSize:currentPageSize})},[pageIndex,currentPageSize]);const data=(0,react_1.useMemo)(()=>type==="subscriptions"?subscriptions??[]:orders??[],[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,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=(_e=(_d=orders?.meta.recordCount)!==null&&_d!==void 0?_d: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.OrderList=OrderList,exports.default=OrderList;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderList=void 0;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,{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,["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);(0,react_1.useEffect)(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize})},[pageIndex,currentPageSize]);const data=(0,react_1.useMemo)(()=>type==="subscriptions"?subscriptions??[]:orders??[],[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,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=(_e=(_d=orders?.meta.recordCount)!==null&&_d!==void 0?_d: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.OrderList=OrderList,exports.default=OrderList;
@@ -1,8 +1,21 @@
1
1
  import { type ReactNode } from 'react';
2
2
  interface Props {
3
+ /**
4
+ * The children component
5
+ */
3
6
  children: ReactNode;
7
+ /**
8
+ * The sku code
9
+ */
4
10
  skuCode?: string;
11
+ /**
12
+ * The sku id. If you use this prop, the skuCode will be ignored and the sku will be fetched by id improving the performance
13
+ */
14
+ skuId?: string;
15
+ /**
16
+ * Callback called when the quantity is updated
17
+ */
5
18
  getQuantity?: (quantity: number) => void;
6
19
  }
7
- export declare function AvailabilityContainer({ children, skuCode, getQuantity }: Props): JSX.Element;
20
+ export declare function AvailabilityContainer({ children, skuCode, skuId, getQuantity }: Props): JSX.Element;
8
21
  export default AvailabilityContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AvailabilityContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),AvailabilityReducer_1=tslib_1.__importStar(require("../../reducers/AvailabilityReducer")),AvailabilityContext_1=tslib_1.__importDefault(require("../../context/AvailabilityContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),LineItemChildrenContext_1=tslib_1.__importDefault(require("../../context/LineItemChildrenContext")),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function AvailabilityContainer({children,skuCode,getQuantity}){const{lineItem}=(0,react_1.useContext)(LineItemChildrenContext_1.default),{sku}=(0,react_1.useContext)(SkuChildrenContext_1.default),{accessToken,endpoint}=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"AvailabilityContainer",key:"accessToken"}),[state,dispatch]=(0,react_1.useReducer)(AvailabilityReducer_1.default,AvailabilityReducer_1.availabilityInitialState),sCode=skuCode||lineItem?.sku_code||sku?.code;(0,react_1.useEffect)(()=>{if(accessToken!=null&&accessToken!==""){const config={accessToken,endpoint};sCode&&(0,AvailabilityReducer_1.getAvailability)({skuCode:sCode,config,dispatch})}return()=>{dispatch({type:"setAvailability",payload:{}})}},[accessToken,sCode]),(0,react_1.useEffect)(()=>{getQuantity!=null&&state?.quantity!=null&&getQuantity(state?.quantity)},[state.quantity]);const memoized=(0,react_1.useMemo)(()=>Object.assign(Object.assign({},state),{parent:!0}),[state]);return(0,jsx_runtime_1.jsx)(AvailabilityContext_1.default.Provider,{value:memoized,children})}exports.AvailabilityContainer=AvailabilityContainer,exports.default=AvailabilityContainer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AvailabilityContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),AvailabilityReducer_1=tslib_1.__importStar(require("../../reducers/AvailabilityReducer")),AvailabilityContext_1=tslib_1.__importDefault(require("../../context/AvailabilityContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),LineItemChildrenContext_1=tslib_1.__importDefault(require("../../context/LineItemChildrenContext")),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function AvailabilityContainer({children,skuCode,skuId,getQuantity}){const{lineItem}=(0,react_1.useContext)(LineItemChildrenContext_1.default),{sku}=(0,react_1.useContext)(SkuChildrenContext_1.default),{accessToken,endpoint}=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"AvailabilityContainer",key:"accessToken"}),[state,dispatch]=(0,react_1.useReducer)(AvailabilityReducer_1.default,AvailabilityReducer_1.availabilityInitialState),sCode=skuCode||lineItem?.sku_code||sku?.code;(0,react_1.useEffect)(()=>{if(accessToken!=null&&accessToken!==""){const config={accessToken,endpoint};sCode&&(0,AvailabilityReducer_1.getAvailability)({skuCode:sCode,skuId,config,dispatch})}return()=>{dispatch({type:"setAvailability",payload:{}})}},[accessToken,sCode,skuId]),(0,react_1.useEffect)(()=>{getQuantity!=null&&state?.quantity!=null&&getQuantity(state?.quantity)},[state.quantity]);const memoized=(0,react_1.useMemo)(()=>Object.assign(Object.assign({},state),{parent:!0}),[state]);return(0,jsx_runtime_1.jsx)(AvailabilityContext_1.default.Provider,{value:memoized,children})}exports.AvailabilityContainer=AvailabilityContainer,exports.default=AvailabilityContainer;
@@ -42,8 +42,9 @@ export interface AvailabilityAction {
42
42
  payload: AvailabilityPayload;
43
43
  }
44
44
  export declare const availabilityInitialState: AvailabilityState;
45
- export declare function getAvailability({ skuCode, dispatch, config }: {
45
+ export declare function getAvailability({ skuCode, skuId, dispatch, config }: {
46
46
  skuCode: string;
47
+ skuId?: string;
47
48
  dispatch: Dispatch<AvailabilityAction>;
48
49
  config: CommerceLayerConfig;
49
50
  }): Promise<void>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailability=exports.availabilityInitialState=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk"));exports.availabilityInitialState={};function getAvailability({skuCode,dispatch,config}){var _a;return tslib_1.__awaiter(this,void 0,void 0,function*(){const sdk=(0,getSdk_1.default)(config);try{const[sku]=yield sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=yield sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=((_a=skuInventory.inventory)===null||_a===void 0?void 0:_a.levels)||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:Object.assign(Object.assign({},delivery),{quantity:skuInventory.inventory.quantity,skuCode})})}}catch(error){console.error("Get SKU availability",error)}})}exports.getAvailability=getAvailability;const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,typeAction);exports.default=availabilityReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailability=exports.availabilityInitialState=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk"));exports.availabilityInitialState={};function getAvailability({skuCode,skuId,dispatch,config}){var _a;return tslib_1.__awaiter(this,void 0,void 0,function*(){const sdk=(0,getSdk_1.default)(config);try{const[sku]=skuId!=null?[{id:skuId}]:yield sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=yield sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=((_a=skuInventory.inventory)===null||_a===void 0?void 0:_a.levels)||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:Object.assign(Object.assign({},delivery),{quantity:skuInventory.inventory.quantity,skuCode})})}}catch(error){console.error("Get SKU availability",error)}})}exports.getAvailability=getAvailability;const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,typeAction);exports.default=availabilityReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=exports.getCustomerInfo=exports.getCustomerPayments=exports.createCustomerAddress=exports.getCustomerSubscriptions=exports.getCustomerOrders=exports.getCustomerPaymentSources=exports.deleteCustomerAddress=exports.getCustomerAddresses=exports.setCustomerEmail=exports.setCustomerErrors=exports.saveCustomerUser=void 0;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=tslib_1.__importDefault(require("../utils/jwt")),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken");function saveCustomerUser({customerEmail,order,updateOrder}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}exports.saveCustomerUser=saveCustomerUser;function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setCustomerErrors=setCustomerErrors;function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}exports.setCustomerEmail=setCustomerEmail;function getCustomerAddresses({config,dispatch,isOrderAvailable}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(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}})}})}exports.getCustomerAddresses=getCustomerAddresses;function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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")}})}exports.deleteCustomerAddress=deleteCustomerAddress;function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}exports.getCustomerPaymentSources=getCustomerPaymentSources;function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}exports.getCustomerOrders=getCustomerOrders;function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const subscriptions=yield(0,getSdk_1.default)(config).customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}})}exports.getCustomerSubscriptions=getCustomerSubscriptions;function createCustomerAddress({address,config,dispatch,state}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const upAddress=yield sdk.addresses.update(address),updatedAddresses=(_a=state?.addresses)===null||_a===void 0?void 0:_a.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=yield sdk.addresses.create(address);if(!((_b=state?.customers)===null||_b===void 0)&&_b.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_c=state?.customers)===null||_c===void 0?void 0:_c.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")}}})}exports.createCustomerAddress=createCustomerAddress;function getCustomerPayments({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config!=null&&dispatch!=null){const payments=yield(0,getSdk_1.default)(config).customer_payment_sources.list({include:["payment_source"]});dispatch({type:"setPayments",payload:{payments}})}})}exports.getCustomerPayments=getCustomerPayments;function getCustomerInfo({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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);dispatch({type:"setCustomers",payload:{customers}})}}})}exports.getCustomerInfo=getCustomerInfo,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=exports.getCustomerInfo=exports.getCustomerPayments=exports.createCustomerAddress=exports.getCustomerSubscriptions=exports.getCustomerOrders=exports.getCustomerPaymentSources=exports.deleteCustomerAddress=exports.getCustomerAddresses=exports.setCustomerEmail=exports.setCustomerErrors=exports.saveCustomerUser=void 0;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=tslib_1.__importDefault(require("../utils/jwt")),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken");function saveCustomerUser({customerEmail,order,updateOrder}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}exports.saveCustomerUser=saveCustomerUser;function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setCustomerErrors=setCustomerErrors;function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}exports.setCustomerEmail=setCustomerEmail;function getCustomerAddresses({config,dispatch,isOrderAvailable}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(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}})}})}exports.getCustomerAddresses=getCustomerAddresses;function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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")}})}exports.deleteCustomerAddress=deleteCustomerAddress;function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}exports.getCustomerPaymentSources=getCustomerPaymentSources;function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}exports.getCustomerOrders=getCustomerOrders;function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const subscriptions=yield(0,getSdk_1.default)(config).customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}})}exports.getCustomerSubscriptions=getCustomerSubscriptions;function createCustomerAddress({address,config,dispatch,state}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const upAddress=yield sdk.addresses.update(address),updatedAddresses=(_a=state?.addresses)===null||_a===void 0?void 0:_a.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=yield sdk.addresses.create(address);if(!((_b=state?.customers)===null||_b===void 0)&&_b.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_c=state?.customers)===null||_c===void 0?void 0:_c.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")}}})}exports.createCustomerAddress=createCustomerAddress;function getCustomerPayments({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config!=null&&dispatch!=null){const payments=yield(0,getSdk_1.default)(config).customer_payment_sources.list({include:["payment_source"]});dispatch({type:"setPayments",payload:{payments}})}})}exports.getCustomerPayments=getCustomerPayments;function getCustomerInfo({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerInfo=getCustomerInfo,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}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";export function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain,...p}=props,{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint),href=getApplicationLink({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,customDomain}),parentProps={label,href,clientId,scope,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,...p,children:label})}export default MyIdentityLink;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";export function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain,...p}=props,{accessToken,endpoint}=useContext(CommerceLayerContext),[href,setHref]=useState(void 0);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint);useEffect(()=>{const link=getApplicationLink({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,customDomain});return setHref(link),()=>{setHref(void 0)}},[]);const parentProps={label,href,clientId,scope,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,...p,children:label})}export default MyIdentityLink;
@@ -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}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),localOrder=persistKey?getLocalOrder(persistKey):orderId,getOrder=async()=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder():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 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():[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,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{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),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,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({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);useEffect(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex,pageSize:currentPageSize})},[pageIndex,currentPageSize]);const data=useMemo(()=>type==="subscriptions"?subscriptions??[]:orders??[],[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,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=orders?.meta.recordCount??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({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);useEffect(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize})},[pageIndex,currentPageSize]);const data=useMemo(()=>type==="subscriptions"?subscriptions??[]:orders??[],[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,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=orders?.meta.recordCount??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,8 +1,21 @@
1
1
  import { type ReactNode } from 'react';
2
2
  interface Props {
3
+ /**
4
+ * The children component
5
+ */
3
6
  children: ReactNode;
7
+ /**
8
+ * The sku code
9
+ */
4
10
  skuCode?: string;
11
+ /**
12
+ * The sku id. If you use this prop, the skuCode will be ignored and the sku will be fetched by id improving the performance
13
+ */
14
+ skuId?: string;
15
+ /**
16
+ * Callback called when the quantity is updated
17
+ */
5
18
  getQuantity?: (quantity: number) => void;
6
19
  }
7
- export declare function AvailabilityContainer({ children, skuCode, getQuantity }: Props): JSX.Element;
20
+ export declare function AvailabilityContainer({ children, skuCode, skuId, getQuantity }: Props): JSX.Element;
8
21
  export default AvailabilityContainer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useReducer,useEffect,useMemo}from"react";import availabilityReducer,{availabilityInitialState,getAvailability}from"../../reducers/AvailabilityReducer";import AvailabilityContext from"../../context/AvailabilityContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import LineItemChildrenContext from"../../context/LineItemChildrenContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityContainer({children,skuCode,getQuantity}){const{lineItem}=useContext(LineItemChildrenContext),{sku}=useContext(SkuChildrenContext),{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AvailabilityContainer",key:"accessToken"}),[state,dispatch]=useReducer(availabilityReducer,availabilityInitialState),sCode=skuCode||lineItem?.sku_code||sku?.code;useEffect(()=>(accessToken!=null&&accessToken!==""&&sCode&&getAvailability({skuCode:sCode,config:{accessToken,endpoint},dispatch}),()=>{dispatch({type:"setAvailability",payload:{}})}),[accessToken,sCode]),useEffect(()=>{getQuantity!=null&&state?.quantity!=null&&getQuantity(state?.quantity)},[state.quantity]);const memoized=useMemo(()=>({...state,parent:!0}),[state]);return _jsx(AvailabilityContext.Provider,{value:memoized,children})}export default AvailabilityContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useReducer,useEffect,useMemo}from"react";import availabilityReducer,{availabilityInitialState,getAvailability}from"../../reducers/AvailabilityReducer";import AvailabilityContext from"../../context/AvailabilityContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import LineItemChildrenContext from"../../context/LineItemChildrenContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityContainer({children,skuCode,skuId,getQuantity}){const{lineItem}=useContext(LineItemChildrenContext),{sku}=useContext(SkuChildrenContext),{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AvailabilityContainer",key:"accessToken"}),[state,dispatch]=useReducer(availabilityReducer,availabilityInitialState),sCode=skuCode||lineItem?.sku_code||sku?.code;useEffect(()=>(accessToken!=null&&accessToken!==""&&sCode&&getAvailability({skuCode:sCode,skuId,config:{accessToken,endpoint},dispatch}),()=>{dispatch({type:"setAvailability",payload:{}})}),[accessToken,sCode,skuId]),useEffect(()=>{getQuantity!=null&&state?.quantity!=null&&getQuantity(state?.quantity)},[state.quantity]);const memoized=useMemo(()=>({...state,parent:!0}),[state]);return _jsx(AvailabilityContext.Provider,{value:memoized,children})}export default AvailabilityContainer;
@@ -42,8 +42,9 @@ export interface AvailabilityAction {
42
42
  payload: AvailabilityPayload;
43
43
  }
44
44
  export declare const availabilityInitialState: AvailabilityState;
45
- export declare function getAvailability({ skuCode, dispatch, config }: {
45
+ export declare function getAvailability({ skuCode, skuId, dispatch, config }: {
46
46
  skuCode: string;
47
+ skuId?: string;
47
48
  dispatch: Dispatch<AvailabilityAction>;
48
49
  config: CommerceLayerConfig;
49
50
  }): Promise<void>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const availabilityInitialState={};export async function getAvailability({skuCode,dispatch,config}){const sdk=getSdk(config);try{const[sku]=await sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=await sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=skuInventory.inventory?.levels||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:{...delivery,quantity:skuInventory.inventory.quantity,skuCode}})}}catch(error){console.error("Get SKU availability",error)}}const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>baseReducer(state,reducer,typeAction);export default availabilityReducer;
2
+ import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const availabilityInitialState={};export async function getAvailability({skuCode,skuId,dispatch,config}){const sdk=getSdk(config);try{const[sku]=skuId!=null?[{id:skuId}]:await sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=await sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=skuInventory.inventory?.levels||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:{...delivery,quantity:skuInventory.inventory.quantity,skuCode}})}}catch(error){console.error("Get SKU availability",error)}}const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>baseReducer(state,reducer,typeAction);export default availabilityReducer;
@@ -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 jwtDecode from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";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}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(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;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const subscriptions=await getSdk(config).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 upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);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}){if(config!=null&&dispatch!=null){const payments=await getSdk(config).customer_payment_sources.list({include:["payment_source"]});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);dispatch({type:"setCustomers",payload:{customers}})}}}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 jwtDecode from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";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}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(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;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const subscriptions=await getSdk(config).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 upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);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}){if(config!=null&&dispatch!=null){const payments=await getSdk(config).customer_payment_sources.list({include:["payment_source"]});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 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.7.4",
3
+ "version": "4.7.5-beta.1",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",