@commercelayer/react-components 3.14.0-beta.1 → 3.14.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
- /// <reference types="react" />
1
+ import { MouseEvent, ReactNode } from 'react';
2
2
  import { FunctionChildren } from '../typings/index';
3
3
  declare type TChildren = FunctionChildren<Omit<Props, 'children'> & {
4
4
  href: string;
5
+ handleClick?: (e: MouseEvent<HTMLAnchorElement>) => Promise<void>;
5
6
  }>;
6
7
  declare type Props = {
7
8
  children?: TChildren;
8
- label?: string;
9
+ label?: string | ReactNode;
9
10
  } & JSX.IntrinsicElements['a'];
10
11
  export default function CartLink(props: Props): JSX.Element | null;
11
12
  export {};
@@ -1 +1 @@
1
- import{__rest}from"tslib";import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../context/OrderContext";import Parent from"./utils/Parent";import CommerceLayerContext from"../context/CommerceLayerContext";import getCartLink from"../utils/getCartLink";export default function CartLink(props){const{label,children}=props,p=__rest(props,["label","children"]),{order,createOrder}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext),[slug]=endpoint.split(".commercelayer"),href=slug&&(order==null?void 0:order.id)?getCartLink({slug,orderId:order==null?void 0:order.id,accessToken}):"",handleClick=async event=>{if(event.preventDefault(),order==null?void 0:order.id)location.href=href;else{const orderId=await createOrder();slug&&(location.href=getCartLink({slug,orderId,accessToken}))}},parentProps=Object.assign({label,href},p);return accessToken?children?_jsx(Parent,Object.assign({},parentProps,{children})):_jsx("a",Object.assign({href},p,{onClick:handleClick},{children:label})):null}
1
+ import{__rest}from"tslib";import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../context/OrderContext";import Parent from"./utils/Parent";import CommerceLayerContext from"../context/CommerceLayerContext";import getCartLink from"../utils/getCartLink";export default function CartLink(props){const{label,children}=props,p=__rest(props,["label","children"]),{order,createOrder}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext),[slug]=endpoint.split(".commercelayer"),href=slug&&(order==null?void 0:order.id)?getCartLink({slug,orderId:order==null?void 0:order.id,accessToken}):"",handleClick=async event=>{if(event.preventDefault(),order==null?void 0:order.id)location.href=href;else{const orderId=await createOrder();slug&&(location.href=getCartLink({slug,orderId,accessToken}))}},parentProps=Object.assign({handleClick,label,href},p);return accessToken?children?_jsx(Parent,Object.assign({},parentProps,{children})):_jsx("a",Object.assign({href},p,{onClick:handleClick},{children:typeof label=="function"?label():label})):null}
@@ -1,6 +1,6 @@
1
1
  import { ReactNode } from 'react';
2
2
  import { BaseMetadataObject } from '../typings/index';
3
- import { OrderCreate, Order } from '@commercelayer/sdk';
3
+ import type { OrderCreate, Order } from '@commercelayer/sdk';
4
4
  declare type OrderContainerProps = {
5
5
  children: ReactNode;
6
6
  metadata?: BaseMetadataObject;
@@ -1 +1 @@
1
- import{__rest}from"tslib";import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useState,useEffect}from"react";import Parent from"./utils/Parent";import{isEmpty,has}from"lodash";import getCurrentItemKey from"../utils/getCurrentItemKey";import ItemContext from"../context/ItemContext";import components from"../config/components";import SkuListsContext from"../context/SkuListsContext";import SkuChildrenContext from"../context/SkuChildrenContext";const propTypes=components.QuantitySelector.propTypes,defaultProps=components.QuantitySelector.defaultProps,displayName=components.QuantitySelector.displayName,QuantitySelector=props=>{var _a,_b,_c;const{skuCode,skuListId,children,min=1,max}=props,p=__rest(props,["skuCode","skuListId","children","min","max"]),{item,setQuantity,items,quantity,prices,skuCode:itemSkuCode}=useContext(ItemContext),{sku}=useContext(SkuChildrenContext),{skuLists,listIds}=useContext(SkuListsContext),[value,setValue]=useState(min),[disabled,setDisabled]=useState(!!p.disabled),sCode=!isEmpty(items)&&skuCode?(_a=items[skuCode])===null||_a===void 0?void 0:_a.code:(sku==null?void 0:sku.code)||skuCode||getCurrentItemKey(item)||itemSkuCode,inventory=isEmpty(item)?50:(_c=(_b=item[sCode])===null||_b===void 0?void 0:_b.inventory)===null||_c===void 0?void 0:_c.quantity,maxInv=max||inventory;useEffect(()=>{if(setValue(min),(!prices[sCode]||!sCode)&&setDisabled(!0),skuListId&&setDisabled(!1),sCode){const qty=Number(min);setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${sCode}`]:qty})),!isEmpty(prices)&&has(prices,sCode)&&setDisabled(!1)}return()=>{setValue(min)}},[item,listIds,prices]);const handleChange=e=>{const qty=Number(e.target.value),valid=Number(qty)>=Number(min)&&Number(qty)<=Number(maxInv);setValue(qty),!isEmpty(skuLists)&&skuListId&&valid?setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${skuListId}`]:Number(qty)})):sCode&&valid&&setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${sCode}`]:Number(qty)}))},handleBlur=e=>{const qty=e.target.value;if(!(Number(qty)>=Number(min)&&Number(qty)<=Number(maxInv))){const resetVal=Number(qty)<Number(min)?min:maxInv;resetVal&&setValue(resetVal),!isEmpty(skuLists)&&skuListId?setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${skuListId}`]:Number(resetVal)})):setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${sCode}`]:Number(resetVal)}))}},parentProps=Object.assign({min,max:maxInv,disabled,handleChange,handleBlur,value},props);return children?_jsx(Parent,Object.assign({},parentProps,{children})):_jsx("input",Object.assign({type:"number",max:maxInv,min,value:value||"",disabled,onChange:handleChange,onBlur:handleBlur},p))};QuantitySelector.propTypes=propTypes,QuantitySelector.defaultProps=defaultProps,QuantitySelector.displayName=displayName;export default QuantitySelector;
1
+ import{__rest}from"tslib";import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useState,useEffect}from"react";import Parent from"./utils/Parent";import has from"lodash/has";import isEmpty from"lodash/isEmpty";import getCurrentItemKey from"../utils/getCurrentItemKey";import ItemContext from"../context/ItemContext";import components from"../config/components";import SkuListsContext from"../context/SkuListsContext";import SkuChildrenContext from"../context/SkuChildrenContext";const propTypes=components.QuantitySelector.propTypes,defaultProps=components.QuantitySelector.defaultProps,displayName=components.QuantitySelector.displayName,QuantitySelector=props=>{var _a,_b,_c;const{skuCode,skuListId,children,min=1,max}=props,p=__rest(props,["skuCode","skuListId","children","min","max"]),{item,setQuantity,items,quantity,prices,skuCode:itemSkuCode}=useContext(ItemContext),{sku}=useContext(SkuChildrenContext),{skuLists,listIds}=useContext(SkuListsContext),[value,setValue]=useState((p==null?void 0:p.value)||min),[disabled,setDisabled]=useState(!!p.disabled),sCode=!isEmpty(items)&&skuCode?(_a=items[skuCode])===null||_a===void 0?void 0:_a.code:(sku==null?void 0:sku.code)||skuCode||getCurrentItemKey(item)||itemSkuCode,inventory=isEmpty(item)?50:(_c=(_b=item[sCode])===null||_b===void 0?void 0:_b.inventory)===null||_c===void 0?void 0:_c.quantity,maxInv=max||inventory;useEffect(()=>{if(setValue(min),(!prices[sCode]||!sCode)&&setDisabled(!0),skuListId&&setDisabled(!1),sCode){const qty=Number(min);setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${sCode}`]:qty})),!isEmpty(prices)&&has(prices,sCode)&&setDisabled(!1)}return()=>{setValue(min)}},[item,listIds,prices]);const handleChange=e=>{const qty=Number(e.target.value),valid=Number(qty)>=Number(min)&&Number(qty)<=Number(maxInv);setValue(qty),!isEmpty(skuLists)&&skuListId&&valid?setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${skuListId}`]:Number(qty)})):sCode&&valid&&setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${sCode}`]:Number(qty)}))},handleBlur=e=>{const qty=e.target.value;if(!(Number(qty)>=Number(min)&&Number(qty)<=Number(maxInv))){const resetVal=Number(qty)<Number(min)?min:maxInv;resetVal&&setValue(resetVal),!isEmpty(skuLists)&&skuListId?setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${skuListId}`]:Number(resetVal)})):setQuantity&&setQuantity(Object.assign(Object.assign({},quantity),{[`${sCode}`]:Number(resetVal)}))}},parentProps=Object.assign({min,max:maxInv,disabled,handleChange,handleBlur,value},props);return children?_jsx(Parent,Object.assign({},parentProps,{children})):_jsx("input",Object.assign({type:"number",max:maxInv,min,value:value||"",disabled,onChange:handleChange,onBlur:handleBlur},p))};QuantitySelector.propTypes=propTypes,QuantitySelector.defaultProps=defaultProps,QuantitySelector.displayName=displayName;export default QuantitySelector;
@@ -1,7 +1,7 @@
1
1
  /// <reference types="react" />
2
2
  import { ConditionalElement } from '../typings/index';
3
- import { TResources } from './utils/GenericFieldComponent';
4
- declare type SkuFieldChildrenProps = Omit<Props, 'children' | 'attribute' | 'element'>;
3
+ import { TGenericChildrenProps, TResources } from './utils/GenericFieldComponent';
4
+ declare type SkuFieldChildrenProps = TGenericChildrenProps<TResources['Sku']>;
5
5
  declare type TCondition = ConditionalElement<Exclude<TResources['Sku'], 'resource'>>;
6
6
  declare type Props = {
7
7
  children?: (props: SkuFieldChildrenProps) => JSX.Element;
@@ -1,7 +1,7 @@
1
1
  /// <reference types="react" />
2
2
  import { ConditionalElement } from '../typings/index';
3
- import { TResources } from './utils/GenericFieldComponent';
4
- declare type StockTransferFieldChildrenProps = Omit<Props, 'children' | 'attribute' | 'element'>;
3
+ import { TGenericChildrenProps, TResources } from './utils/GenericFieldComponent';
4
+ declare type StockTransferFieldChildrenProps = TGenericChildrenProps<TResources['StockTransfer']>;
5
5
  declare type TCondition = ConditionalElement<Exclude<TResources['StockTransfer'], 'resource'>>;
6
6
  declare type Props = {
7
7
  children?: (props: StockTransferFieldChildrenProps) => JSX.Element;
@@ -1,6 +1,6 @@
1
1
  import { InitialSkuContext } from '../../context/SkuChildrenContext';
2
2
  import { InitialStockTransferContext } from '../../context/StockTransferChildrenContext';
3
- import { LineItem, Sku } from '@commercelayer/sdk';
3
+ import type { LineItem, Sku } from '@commercelayer/sdk';
4
4
  import { InitialLineItemContext } from '../../context/LineItemChildrenContext';
5
5
  import { Context } from 'react';
6
6
  export declare type TResources = {
@@ -17,8 +17,8 @@ export declare type TResources = {
17
17
  export declare type TResourceKey = {
18
18
  [K in keyof TResources]: K;
19
19
  };
20
- declare type ChildrenProps<E extends TResources[keyof TResources]> = Omit<Props<E>, 'children' | 'attribute'> & {
21
- element: E[keyof E];
20
+ export declare type TGenericChildrenProps<E extends TResources[keyof TResources]> = Omit<Props<E>, 'children' | 'attribute' | 'context' | 'tagElement'> & {
21
+ attributeValue: E[keyof E];
22
22
  };
23
23
  declare type ResourceContext = {
24
24
  stock_transfers: InitialStockTransferContext;
@@ -27,7 +27,7 @@ declare type ResourceContext = {
27
27
  };
28
28
  declare type GenericContext<K extends keyof ResourceContext> = Context<ResourceContext[K]>;
29
29
  declare type Props<E extends TResources[keyof TResources]> = {
30
- children?: (props: ChildrenProps<E>) => JSX.Element;
30
+ children?: (props: TGenericChildrenProps<E>) => JSX.Element;
31
31
  resource: E['resource'];
32
32
  attribute: keyof E;
33
33
  tagElement: keyof JSX.IntrinsicElements;
@@ -1 +1 @@
1
- import{__rest}from"tslib";import{jsx as _jsx}from"react/jsx-runtime";import Parent from"./Parent";import{useContext}from"react";import{defaultImgUrl}from"../../utils/placeholderImages";export default function GenericFieldComponent(props){const{children,tagElement,attribute,context}=props,p=__rest(props,["children","tagElement","attribute","context"]),resourceContext=useContext(context);let element;for(const key in resourceContext)Object.prototype.hasOwnProperty.call(resourceContext,key)&&(element=resourceContext[key][attribute]);const Tag=tagElement||"span";if(Tag==="img"&&!children)return _jsx("img",Object.assign({alt:"",src:element||defaultImgUrl},p));const parentProps=Object.assign({element,tagElement},p);return children?_jsx(Parent,Object.assign({},parentProps,{children})):_jsx(Tag,Object.assign({},p,{children:element}))}
1
+ import{__rest}from"tslib";import{jsx as _jsx}from"react/jsx-runtime";import Parent from"./Parent";import{useContext}from"react";import{defaultImgUrl}from"../../utils/placeholderImages";export default function GenericFieldComponent(props){const{children,tagElement,attribute,context}=props,p=__rest(props,["children","tagElement","attribute","context"]),resourceContext=useContext(context);let attributeValue;for(const key in resourceContext)Object.prototype.hasOwnProperty.call(resourceContext,key)&&(attributeValue=resourceContext[key][attribute]);const Tag=tagElement||"span";if(Tag==="img"&&!children)return _jsx("img",Object.assign({alt:"",src:attributeValue||defaultImgUrl},p));const parentProps=Object.assign({attributeValue,tagElement},p);return children?_jsx(Parent,Object.assign({},parentProps,{children})):_jsx(Tag,Object.assign({},p,{children:attributeValue}))}
@@ -5,7 +5,7 @@ import { ItemOption, CustomLineItem } from './ItemReducer';
5
5
  import { BaseMetadataObject } from '../typings/index';
6
6
  import { BaseError } from '../typings/errors';
7
7
  import { AddressResource } from './AddressReducer';
8
- import { Order, OrderUpdate } from '@commercelayer/sdk';
8
+ import type { Order, OrderUpdate } from '@commercelayer/sdk';
9
9
  export declare type GetOrderParams = Partial<{
10
10
  clearWhenPlaced: boolean;
11
11
  config: CommerceLayerConfig;
@@ -1 +1 @@
1
- import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import size from"lodash/size";import map from"lodash/map";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state==null?void 0:state.orderId)return state.orderId;const sdk=getSdk(config);try{const o=await(sdk==null?void 0:sdk.orders.create(Object.assign({metadata},orderAttributes)));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o==null?void 0:o.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors(error,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state==null?void 0:state.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{const options={};(state==null?void 0:state.include)&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id,options);return clearWhenPlaced&&order.status==="placed"||order.status==="approved"||order.status==="cancelled"?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors(error,"orders");console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state==null?void 0:state.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=getSdk(config);try{const resource=Object.assign(Object.assign({},attributes),{id});await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0}}catch(error){const errors=getErrors(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...resourcesIncluded,...resources],resources.forEach(resource=>{payload.includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0})})}else delete payload.include;payload.includeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded),dispatch&&dispatch({type:"setIncludesResource",payload})}export const addToCart=async params=>{const{skuCode,bundleCode,skuId,quantity,option,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl}=params;try{if(!config)throw{errors:[{code:"INVALID_RESOURCE",resource:"orders",title:"Markup error",message:"You are trying to place an order outside the OrderContainer component"}]};const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem==null?void 0:lineItem.name,imageUrl=lineItem==null?void 0:lineItem.imageUrl,attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity||1,_update_quantity:!0,bundle_code:bundleCode};skuId&&(attrs.item=sdk.skus.relationship(skuId));const newLineItem=await sdk.line_items.create(attrs);if(isEmpty(option))await getApiOrder(Object.assign(Object.assign({id},params),{state}));else{let c=0;map(option,async opt=>{const{options,skuOptionId}=opt,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),c+=1,c===size(option)&&await getApiOrder(Object.assign({id},params))})}if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=getOrganizationSlug(config.endpoint),params2=`${id}?accessToken=${config.accessToken}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}return{success:!1,orderId:void 0}}catch(error){const errors2=getErrors(error,"orders");return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state==null?void 0:state.errors,newErrors:errors2,dispatch}),{success:!1,orderId:void 0}}},unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})},setGiftCardOrCouponCode=async({code,codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},removeGiftCardOrCouponCode=async({codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&dispatch){const attributes={[codeType]:""};return await updateOrder({id:order.id,attributes,config,include,dispatch,state}),dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:[]};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
1
+ import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import size from"lodash/size";import map from"lodash/map";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state==null?void 0:state.orderId)return state.orderId;const sdk=getSdk(config);try{const o=await(sdk==null?void 0:sdk.orders.create(Object.assign({metadata},orderAttributes)));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o==null?void 0:o.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors(error,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state==null?void 0:state.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{const options={};(state==null?void 0:state.include)&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id,options);return clearWhenPlaced&&order.status==="placed"||order.status==="approved"||order.status==="cancelled"?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors(error,"orders");console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state==null?void 0:state.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=getSdk(config);try{const resource=Object.assign(Object.assign({},attributes),{id});await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0}}catch(error){const errors=getErrors(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...resourcesIncluded,...resources],resources.forEach(resource=>{payload.includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0})})}else delete payload.include;payload.includeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded),dispatch&&dispatch({type:"setIncludesResource",payload})}export const addToCart=async params=>{var _a,_b,_c;const{skuCode,bundleCode,skuId,quantity,option,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl}=params;try{if(!config)throw{errors:[{code:"INVALID_RESOURCE",resource:"orders",title:"Markup error",message:"You are trying to place an order outside the OrderContainer component"}]};const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem==null?void 0:lineItem.name,imageUrl=lineItem==null?void 0:lineItem.imageUrl;buyNowMode&&((_a=state==null?void 0:state.order)===null||_a===void 0?void 0:_a.line_items)&&((_b=state==null?void 0:state.order)===null||_b===void 0?void 0:_b.line_items.length)>0&&await Promise.all((_c=state==null?void 0:state.order)===null||_c===void 0?void 0:_c.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity||1,_update_quantity:!0,bundle_code:bundleCode};skuId&&(attrs.item=sdk.skus.relationship(skuId));const newLineItem=await sdk.line_items.create(attrs);if(isEmpty(option))await getApiOrder(Object.assign(Object.assign({id},params),{state}));else{let c=0;map(option,async opt=>{const{options,skuOptionId}=opt,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),c+=1,c===size(option)&&await getApiOrder(Object.assign({id},params))})}if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=getOrganizationSlug(config.endpoint),params2=`${id}?accessToken=${config.accessToken}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}return{success:!1,orderId:void 0}}catch(error){const errors2=getErrors(error,"orders");return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state==null?void 0:state.errors,newErrors:errors2,dispatch}),{success:!1,orderId:void 0}}},unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})},setGiftCardOrCouponCode=async({code,codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},removeGiftCardOrCouponCode=async({codeType,dispatch,config,order,include,state})=>{try{if(config&&order&&dispatch){const attributes={[codeType]:""};return await updateOrder({id:order.id,attributes,config,include,dispatch,state}),dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0}}return{success:!1}}catch(error){const errors=getErrors(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}},orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:[]};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
@@ -1 +1 @@
1
- export default function compareObjAttribute({attributes,object}){const returnObj={};return Object.keys(object).forEach(v=>{const element=attributes[v],compare=object[v];element&&element!==compare&&(returnObj[v]=element)}),returnObj}
1
+ export default function compareObjAttribute({attributes,object}){const returnObj={};return Object.keys(object).forEach(v=>{const element=attributes[v],compare=object[v];typeof element=="object"&&element&&JSON.stringify(element)!==JSON.stringify(compare)&&(returnObj[v]=element),typeof element!="object"&&element&&element!==compare&&(returnObj[v]=element)}),returnObj}
@@ -1,12 +1,10 @@
1
- import { LineItem } from '@commercelayer/sdk';
1
+ import type { LineItem } from '@commercelayer/sdk';
2
2
  import { LineItemType } from '../typings/index';
3
- export interface GetLineItemsCountInterface {
4
- (args: {
5
- lineItems: LineItem[];
6
- quantity?: number;
7
- typeAccepted?: TypeAccepted[];
8
- }): number;
9
- }
10
3
  export declare type TypeAccepted = Extract<LineItemType, 'skus' | 'gift_cards' | 'bundles' | 'adjustments'>;
11
- declare const getLineItemsCount: GetLineItemsCountInterface;
12
- export default getLineItemsCount;
4
+ declare type Args = {
5
+ lineItems: LineItem[];
6
+ quantity?: number;
7
+ typeAccepted?: TypeAccepted[];
8
+ };
9
+ export default function getLineItemsCount({ lineItems, quantity, typeAccepted, }: Args): number;
10
+ export {};
@@ -1 +1 @@
1
- const getLineItemsCount=({lineItems,quantity=0,typeAccepted=["skus","gift_cards","bundles","adjustments"]})=>(lineItems.filter(l=>l.item_type&&typeAccepted.includes(l.item_type)&&(l==null?void 0:l.total_amount_cents)&&l.total_amount_cents>=0).forEach(l=>{l.quantity&&(quantity+=l.quantity)}),quantity);export default getLineItemsCount;
1
+ export default function getLineItemsCount({lineItems,quantity=0,typeAccepted=["skus","gift_cards","bundles","adjustments"]}){return lineItems.filter(l=>typeAccepted.includes(l.item_type)&&(l==null?void 0:l.total_amount_cents)!==void 0&&l.total_amount_cents>=0).forEach(l=>{l.quantity&&(quantity+=l.quantity)}),quantity}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "3.14.0-beta.1",
3
+ "version": "3.14.0-beta.4",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "module": "lib/index.js",
6
6
  "types": "lib/index.d.ts",