@commercelayer/react-components 4.4.4 → 4.5.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/lib/cjs/components/ExternalFunction.js +1 -1
  2. package/lib/cjs/components/addresses/Address.js +1 -1
  3. package/lib/cjs/components/addresses/AddressField.js +1 -1
  4. package/lib/cjs/components/addresses/AddressesContainer.js +1 -1
  5. package/lib/cjs/components/addresses/BillingAddressContainer.js +1 -1
  6. package/lib/cjs/components/addresses/BillingAddressForm.js +1 -1
  7. package/lib/cjs/components/addresses/ShippingAddressContainer.js +1 -1
  8. package/lib/cjs/components/addresses/ShippingAddressForm.js +1 -1
  9. package/lib/cjs/components/auth/CommerceLayer.js +1 -1
  10. package/lib/cjs/components/customers/CustomerAddressForm.js +1 -1
  11. package/lib/cjs/components/customers/CustomerContainer.js +1 -1
  12. package/lib/cjs/components/customers/CustomerPaymentSource.js +1 -1
  13. package/lib/cjs/components/gift_cards/GiftCard.js +1 -1
  14. package/lib/cjs/components/gift_cards/GiftCardContainer.js +1 -1
  15. package/lib/cjs/components/gift_cards/GiftCardOrCouponForm.js +1 -1
  16. package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionsContainer.js +1 -1
  17. package/lib/cjs/components/line_items/LineItem.js +1 -1
  18. package/lib/cjs/components/line_items/LineItemOption.js +1 -1
  19. package/lib/cjs/components/line_items/LineItemOptions.js +1 -1
  20. package/lib/cjs/components/line_items/LineItemQuantity.js +1 -1
  21. package/lib/cjs/components/line_items/LineItemRemoveLink.js +1 -1
  22. package/lib/cjs/components/line_items/LineItemsContainer.js +1 -1
  23. package/lib/cjs/components/orders/AddToCartButton.js +1 -1
  24. package/lib/cjs/components/orders/CartLink.js +1 -1
  25. package/lib/cjs/components/orders/OrderContainer.js +1 -1
  26. package/lib/cjs/components/orders/OrderList.d.ts +20 -38
  27. package/lib/cjs/components/orders/OrderList.js +1 -1
  28. package/lib/cjs/components/orders/OrderListPaginationButtons.js +1 -1
  29. package/lib/cjs/components/orders/OrderListPaginationInfo.js +1 -1
  30. package/lib/cjs/components/orders/OrderListRow.d.ts +6 -14
  31. package/lib/cjs/components/orders/OrderListRow.js +1 -1
  32. package/lib/cjs/components/orders/OrderStorage.js +1 -1
  33. package/lib/cjs/components/orders/PlaceOrderContainer.js +1 -1
  34. package/lib/cjs/components/parcels/ParcelLineItem.js +1 -1
  35. package/lib/cjs/components/parcels/Parcels.js +1 -1
  36. package/lib/cjs/components/payment_gateways/AdyenGateway.js +1 -1
  37. package/lib/cjs/components/payment_gateways/BraintreeGateway.js +1 -1
  38. package/lib/cjs/components/payment_gateways/CheckoutComGateway.js +1 -1
  39. package/lib/cjs/components/payment_gateways/ExternalGateway.js +1 -1
  40. package/lib/cjs/components/payment_gateways/KlarnaGateway.js +1 -1
  41. package/lib/cjs/components/payment_gateways/PaypalGateway.js +1 -1
  42. package/lib/cjs/components/payment_gateways/StripeGateway.js +1 -1
  43. package/lib/cjs/components/payment_gateways/WireTransferGateway.js +1 -1
  44. package/lib/cjs/components/payment_methods/PaymentMethod.js +1 -1
  45. package/lib/cjs/components/payment_methods/PaymentMethodsContainer.js +1 -1
  46. package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
  47. package/lib/cjs/components/payment_source/BraintreePayment.js +1 -1
  48. package/lib/cjs/components/payment_source/CheckoutComPayment.js +1 -1
  49. package/lib/cjs/components/payment_source/ExternalPayment.js +1 -1
  50. package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
  51. package/lib/cjs/components/payment_source/PaymentSourceEditButton.js +1 -1
  52. package/lib/cjs/components/payment_source/PaypalPayment.js +1 -1
  53. package/lib/cjs/components/payment_source/StripePayment.js +1 -1
  54. package/lib/cjs/components/payment_source/WireTransferPayment.js +1 -1
  55. package/lib/cjs/components/prices/PricesContainer.js +1 -1
  56. package/lib/cjs/components/shipments/Shipment.js +1 -1
  57. package/lib/cjs/components/shipments/ShipmentsContainer.js +1 -1
  58. package/lib/cjs/components/shipping_methods/ShippingMethod.js +1 -1
  59. package/lib/cjs/components/skus/AvailabilityContainer.js +1 -1
  60. package/lib/cjs/components/skus/SkuListsContainer.js +1 -1
  61. package/lib/cjs/components/skus/Skus.js +1 -1
  62. package/lib/cjs/components/skus/SkusContainer.js +1 -1
  63. package/lib/cjs/components/stock_transfers/StockTransfer.js +1 -1
  64. package/lib/cjs/context/CustomerContext.d.ts +5 -1
  65. package/lib/cjs/context/OrderListChildrenContext.d.ts +15 -10
  66. package/lib/cjs/context/OrderListPaginationContext.d.ts +0 -3
  67. package/lib/cjs/reducers/CustomerReducer.d.ts +15 -4
  68. package/lib/cjs/reducers/CustomerReducer.js +1 -1
  69. package/lib/cjs/reducers/OrderReducer.d.ts +1 -0
  70. package/lib/cjs/reducers/OrderReducer.js +1 -1
  71. package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
  72. package/lib/cjs/typings/globals.d.ts +3 -0
  73. package/lib/cjs/utils/filterChildren.d.ts +3 -0
  74. package/lib/cjs/utils/hasSubscriptions.d.ts +7 -0
  75. package/lib/cjs/utils/hasSubscriptions.js +1 -0
  76. package/lib/cjs/utils/icons.js +1 -1
  77. package/lib/esm/components/customers/CustomerContainer.js +1 -1
  78. package/lib/esm/components/orders/OrderContainer.js +1 -1
  79. package/lib/esm/components/orders/OrderList.d.ts +20 -38
  80. package/lib/esm/components/orders/OrderList.js +1 -1
  81. package/lib/esm/components/orders/OrderListPaginationButtons.js +1 -1
  82. package/lib/esm/components/orders/OrderListPaginationInfo.js +1 -1
  83. package/lib/esm/components/orders/OrderListRow.d.ts +6 -14
  84. package/lib/esm/components/orders/OrderListRow.js +1 -1
  85. package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
  86. package/lib/esm/components/payment_source/StripePayment.js +1 -1
  87. package/lib/esm/context/CustomerContext.d.ts +5 -1
  88. package/lib/esm/context/OrderListChildrenContext.d.ts +15 -10
  89. package/lib/esm/context/OrderListPaginationContext.d.ts +0 -3
  90. package/lib/esm/reducers/CustomerReducer.d.ts +15 -4
  91. package/lib/esm/reducers/CustomerReducer.js +1 -1
  92. package/lib/esm/reducers/OrderReducer.d.ts +1 -0
  93. package/lib/esm/reducers/OrderReducer.js +1 -1
  94. package/lib/esm/reducers/PlaceOrderReducer.js +1 -1
  95. package/lib/esm/typings/globals.d.ts +3 -0
  96. package/lib/esm/utils/filterChildren.d.ts +3 -0
  97. package/lib/esm/utils/hasSubscriptions.d.ts +7 -0
  98. package/lib/esm/utils/hasSubscriptions.js +1 -0
  99. package/package.json +19 -21
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SkuListsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),SkuListsContext_1=tslib_1.__importDefault(require("../../context/SkuListsContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),SkuListsReducer_1=tslib_1.__importStar(require("../../reducers/SkuListsReducer"));function SkuListsContainer(props){const{children}=props,[state,dispatch]=(0,react_1.useReducer)(SkuListsReducer_1.default,SkuListsReducer_1.skuListsInitialState),config=(0,react_1.useContext)(CommerceLayerContext_1.default);return(0,react_1.useEffect)(()=>{state.listIds&&state.listIds.length>0&&config.accessToken&&(0,SkuListsReducer_1.getSkuList)({listIds:state.listIds,dispatch,config,state})},[config.accessToken]),(0,jsx_runtime_1.jsx)(SkuListsContext_1.default.Provider,Object.assign({value:state},{children}))}exports.SkuListsContainer=SkuListsContainer,exports.default=SkuListsContainer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SkuListsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),SkuListsContext_1=tslib_1.__importDefault(require("../../context/SkuListsContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),SkuListsReducer_1=tslib_1.__importStar(require("../../reducers/SkuListsReducer"));function SkuListsContainer(props){const{children}=props,[state,dispatch]=(0,react_1.useReducer)(SkuListsReducer_1.default,SkuListsReducer_1.skuListsInitialState),config=(0,react_1.useContext)(CommerceLayerContext_1.default);return(0,react_1.useEffect)(()=>{state.listIds&&state.listIds.length>0&&config.accessToken&&(0,SkuListsReducer_1.getSkuList)({listIds:state.listIds,dispatch,config,state})},[config.accessToken]),(0,jsx_runtime_1.jsx)(SkuListsContext_1.default.Provider,{value:state,children})}exports.SkuListsContainer=SkuListsContainer,exports.default=SkuListsContainer;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Skus=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),SkuContext_1=tslib_1.__importDefault(require("../../context/SkuContext")),react_1=require("react");function Skus({children}){const{skus}=(0,react_1.useContext)(SkuContext_1.default),components=skus?.map((sku,key)=>{const value={sku};return(0,jsx_runtime_1.jsx)(SkuChildrenContext_1.default.Provider,Object.assign({value},{children}),key)});return(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.Skus=Skus,exports.default=Skus;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Skus=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),SkuContext_1=tslib_1.__importDefault(require("../../context/SkuContext")),react_1=require("react");function Skus({children}){const{skus}=(0,react_1.useContext)(SkuContext_1.default),components=skus?.map((sku,key)=>{const value={sku};return(0,jsx_runtime_1.jsx)(SkuChildrenContext_1.default.Provider,{value,children},key)});return(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.Skus=Skus,exports.default=Skus;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SkusContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),SkuContext_1=tslib_1.__importDefault(require("../../context/SkuContext")),SkuReducer_1=tslib_1.__importStar(require("../../reducers/SkuReducer")),react_1=require("react");function SkusContainer(props){const{skus,children,queryParams}=props,[state,dispatch]=(0,react_1.useReducer)(SkuReducer_1.default,SkuReducer_1.skuInitialState),config=(0,react_1.useContext)(CommerceLayerContext_1.default),loadSkus=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,SkuReducer_1.getSku)({config,dispatch,skus,queryParams})});(0,react_1.useEffect)(()=>(config.accessToken&&state?.skus&&state?.skus.length===0&&loadSkus(),()=>{dispatch({type:"setLoading",payload:{loading:!0}})}),[config,skus]);const contextValue=(0,react_1.useMemo)(()=>state,[state]);return(0,jsx_runtime_1.jsx)(SkuContext_1.default.Provider,Object.assign({value:contextValue},{children}))}exports.SkusContainer=SkusContainer,exports.default=SkusContainer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SkusContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),SkuContext_1=tslib_1.__importDefault(require("../../context/SkuContext")),SkuReducer_1=tslib_1.__importStar(require("../../reducers/SkuReducer")),react_1=require("react");function SkusContainer(props){const{skus,children,queryParams}=props,[state,dispatch]=(0,react_1.useReducer)(SkuReducer_1.default,SkuReducer_1.skuInitialState),config=(0,react_1.useContext)(CommerceLayerContext_1.default),loadSkus=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,SkuReducer_1.getSku)({config,dispatch,skus,queryParams})});(0,react_1.useEffect)(()=>(config.accessToken&&state?.skus&&state?.skus.length===0&&loadSkus(),()=>{dispatch({type:"setLoading",payload:{loading:!0}})}),[config,skus]);const contextValue=(0,react_1.useMemo)(()=>state,[state]);return(0,jsx_runtime_1.jsx)(SkuContext_1.default.Provider,{value:contextValue,children})}exports.SkusContainer=SkusContainer,exports.default=SkusContainer;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StockTransfer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),ShipmentChildrenContext_1=tslib_1.__importDefault(require("../../context/ShipmentChildrenContext")),StockTransferChildrenContext_1=tslib_1.__importDefault(require("../../context/StockTransferChildrenContext"));function StockTransfer(props){const{children}=props,{stockTransfers,lineItems}=(0,react_1.useContext)(ShipmentChildrenContext_1.default),components=stockTransfers?.filter(st=>!!lineItems?.find(l=>l?.sku_code!==st?.sku_code)).map((stockTransfer,k)=>{const stockTransferProps={stockTransfer:stockTransfer.type==="line_items"?stockTransfer:stockTransfer?.line_item};return(0,jsx_runtime_1.jsx)(StockTransferChildrenContext_1.default.Provider,Object.assign({value:stockTransferProps},{children}),k)});return(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.StockTransfer=StockTransfer,exports.default=StockTransfer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StockTransfer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),ShipmentChildrenContext_1=tslib_1.__importDefault(require("../../context/ShipmentChildrenContext")),StockTransferChildrenContext_1=tslib_1.__importDefault(require("../../context/StockTransferChildrenContext"));function StockTransfer(props){const{children}=props,{stockTransfers,lineItems}=(0,react_1.useContext)(ShipmentChildrenContext_1.default),components=stockTransfers?.filter(st=>!!lineItems?.find(l=>l?.sku_code!==st?.sku_code)).map((stockTransfer,k)=>{const stockTransferProps={stockTransfer:stockTransfer.type==="line_items"?stockTransfer:stockTransfer?.line_item};return(0,jsx_runtime_1.jsx)(StockTransferChildrenContext_1.default.Provider,{value:stockTransferProps,children},k)});return(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.StockTransfer=StockTransfer,exports.default=StockTransfer;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="react" />
2
- import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses } from '../reducers/CustomerReducer';
2
+ import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses, type getCustomerOrders, type getCustomerSubscriptions } from '../reducers/CustomerReducer';
3
3
  export type InitialCustomerContext = Partial<{
4
4
  saveCustomerUser: (customerEmail: string) => Promise<void>;
5
5
  setCustomerErrors: SetCustomerErrors;
@@ -8,6 +8,8 @@ export type InitialCustomerContext = Partial<{
8
8
  deleteCustomerAddress: typeof deleteCustomerAddress;
9
9
  getCustomerAddresses: typeof getCustomerAddresses;
10
10
  createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
11
+ getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
12
+ getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
11
13
  } & CustomerState>;
12
14
  export declare const defaultCustomerContext: {};
13
15
  declare const CustomerContext: import("react").Context<Partial<{
@@ -18,5 +20,7 @@ declare const CustomerContext: import("react").Context<Partial<{
18
20
  deleteCustomerAddress: typeof deleteCustomerAddress;
19
21
  getCustomerAddresses: typeof getCustomerAddresses;
20
22
  createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
23
+ getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
24
+ getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
21
25
  } & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
22
26
  export default CustomerContext;
@@ -1,19 +1,23 @@
1
1
  /// <reference types="react" />
2
- import type { Order } from '@commercelayer/sdk';
3
- import { type Row } from 'react-table';
2
+ import type { Order, OrderSubscription } from '@commercelayer/sdk';
3
+ import { type Row } from '@tanstack/react-table';
4
+ export type TOrderList = 'orders' | 'subscriptions';
5
+ export type TableAccessor<T extends TOrderList> = T extends 'orders' ? keyof Order : keyof OrderSubscription;
6
+ export type OrderListContent<T extends TOrderList> = T extends 'orders' ? Order : OrderSubscription;
4
7
  export type InitialOrderListContext = Partial<{
8
+ type: TOrderList;
5
9
  /**
6
10
  * The current order
7
11
  */
8
- order: Order | null;
12
+ order: OrderListContent<TOrderList> | null;
9
13
  /**
10
14
  * The list of orders
11
15
  */
12
- orders: Order[] | null;
16
+ orders: Array<OrderListContent<TOrderList>> | null | undefined;
13
17
  /**
14
18
  * The current row
15
19
  */
16
- row: Row<Order>;
20
+ row: Row<OrderListContent<TOrderList>>;
17
21
  /**
18
22
  * Show the row actions
19
23
  */
@@ -22,7 +26,7 @@ export type InitialOrderListContext = Partial<{
22
26
  * Function to assign as custom row renderer
23
27
  */
24
28
  actionsComponent: (props: {
25
- order: Order;
29
+ order: OrderListContent<TOrderList>;
26
30
  }) => JSX.Element;
27
31
  /**
28
32
  * Class name to assign as custom row renderer
@@ -34,18 +38,19 @@ export type InitialOrderListContext = Partial<{
34
38
  infiniteScroll: boolean;
35
39
  }>;
36
40
  declare const OrderListChildrenContext: import("react").Context<Partial<{
41
+ type: TOrderList;
37
42
  /**
38
43
  * The current order
39
44
  */
40
- order: Order | null;
45
+ order: OrderListContent<TOrderList> | null;
41
46
  /**
42
47
  * The list of orders
43
48
  */
44
- orders: Order[] | null;
49
+ orders: Array<OrderListContent<TOrderList>> | null | undefined;
45
50
  /**
46
51
  * The current row
47
52
  */
48
- row: Row<Order>;
53
+ row: Row<OrderListContent<TOrderList>>;
49
54
  /**
50
55
  * Show the row actions
51
56
  */
@@ -54,7 +59,7 @@ declare const OrderListChildrenContext: import("react").Context<Partial<{
54
59
  * Function to assign as custom row renderer
55
60
  */
56
61
  actionsComponent: (props: {
57
- order: Order;
62
+ order: OrderListContent<TOrderList>;
58
63
  }) => JSX.Element;
59
64
  /**
60
65
  * Class name to assign as custom row renderer
@@ -1,14 +1,11 @@
1
1
  /// <reference types="react" />
2
- import { type Row } from 'react-table';
3
2
  export interface OrderListPaginationContext {
4
3
  canNextPage: boolean;
5
4
  canPreviousPage: boolean;
6
5
  gotoPage: (page: number) => void;
7
6
  nextPage: () => void;
8
- page: Row[];
9
7
  pageCount: number;
10
8
  pageIndex: number;
11
- pageNumber: number;
12
9
  pageOptions: number[];
13
10
  pageSize: number;
14
11
  previousPage: () => void;
@@ -1,15 +1,17 @@
1
1
  import { type Dispatch } from 'react';
2
2
  import { type BaseError } from '../typings/errors';
3
- import type { Address, AddressCreate, AddressUpdate, Customer, CustomerPaymentSource, Order } from '@commercelayer/sdk';
3
+ import type { Address, AddressCreate, AddressUpdate, Customer, CustomerPaymentSource, Order, OrderSubscription } from '@commercelayer/sdk';
4
4
  import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
5
5
  import { type updateOrder } from './OrderReducer';
6
- export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders';
6
+ import { type ListResponse } from '@commercelayer/sdk/lib/cjs/resource';
7
+ export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders' | 'setSubscriptions';
7
8
  export interface CustomerActionPayload {
8
9
  addresses: Address[] | null;
9
10
  payments: CustomerPaymentSource[] | null;
10
11
  customerEmail: string;
11
12
  errors: BaseError[];
12
- orders: Order[];
13
+ orders: ListResponse<Order>;
14
+ subscriptions: ListResponse<OrderSubscription> | null;
13
15
  isGuest: boolean;
14
16
  customers: Customer;
15
17
  }
@@ -106,8 +108,17 @@ interface GetCustomerOrdersProps {
106
108
  * The Customer dispatch function
107
109
  */
108
110
  dispatch: Dispatch<CustomerAction>;
111
+ /**
112
+ * The page size
113
+ */
114
+ pageSize?: number;
115
+ /**
116
+ * The page number
117
+ */
118
+ pageNumber?: number;
109
119
  }
110
- export declare function getCustomerOrders({ config, dispatch }: GetCustomerOrdersProps): Promise<void>;
120
+ export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
121
+ export declare function getCustomerSubscriptions({ config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
111
122
  export type TCustomerAddress = AddressCreate & AddressUpdate;
112
123
  interface TCreateCustomerAddress {
113
124
  /**
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=exports.getCustomerPayments=exports.createCustomerAddress=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"));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}){var _a;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 customers=yield(0,getSdk_1.default)(config).customers.retrieve(owner.id,{include:["orders"]}),orders=(_a=customers.orders)===null||_a===void 0?void 0:_a.filter(order=>order.status!=="pending"&&order.status!=="draft");dispatch({type:"setOrders",payload:{orders,customers}})}}})}exports.getCustomerOrders=getCustomerOrders;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,exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=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"));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,exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
@@ -84,6 +84,7 @@ export interface CustomLineItem {
84
84
  name?: string;
85
85
  imageUrl?: string | null;
86
86
  metadata?: Record<string, string>;
87
+ frequency?: 'hourly' | 'daily' | 'weekly' | 'monthly' | 'two-month' | 'three-month' | 'four-month' | 'six-month' | 'yearly';
87
88
  }
88
89
  export type AddToCartParams = Partial<{
89
90
  bundleCode: string;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.removeGiftCardOrCouponCode=exports.setGiftCardOrCouponCode=exports.saveAddressToCustomerAddressBook=exports.setOrderErrors=exports.unsetOrderState=exports.addToCart=exports.addResourceToInclude=exports.setOrder=exports.updateOrder=exports.getApiOrder=exports.createOrder=void 0;const tslib_1=require("tslib"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=tslib_1.__importDefault(require("../utils/organization")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"],createOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=(0,getSdk_1.default)(config);try{const o=yield sdk?.orders.create(Object.assign({metadata},orderAttributes));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""});exports.createOrder=createOrder;const getApiOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=(0,getSdk_1.default)(config);try{const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield sdk.orders.retrieve(id,options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}});exports.getApiOrder=getApiOrder;function updateOrder({id,attributes,dispatch,config,include,state}){return tslib_1.__awaiter(this,void 0,void 0,function*(){const sdk=(0,getSdk_1.default)(config);try{const resource=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}exports.updateOrder=updateOrder;const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}exports.addResourceToInclude=addResourceToInclude;function addToCart(params){var _a,_b,_c,_d;return tslib_1.__awaiter(this,void 0,void 0,function*(){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=yield(0,exports.createOrder)(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata;if(buyNowMode)if(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:!0,bundle_code:bundleCode,metadata},newLineItem=yield sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({id},params),{state}));if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=(0,organization_1.default)((_c=config.endpoint)!==null&&_c!==void 0?_c:""),params2=`${id}?accessToken=${(_d=config.accessToken)!==null&&_d!==void 0?_d:""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}})}exports.addToCart=addToCart;const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}exports.setOrderErrors=setOrderErrors;const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode;function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode,exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.removeGiftCardOrCouponCode=exports.setGiftCardOrCouponCode=exports.saveAddressToCustomerAddressBook=exports.setOrderErrors=exports.unsetOrderState=exports.addToCart=exports.addResourceToInclude=exports.setOrder=exports.updateOrder=exports.getApiOrder=exports.createOrder=void 0;const tslib_1=require("tslib"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=tslib_1.__importDefault(require("../utils/organization")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"],createOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=(0,getSdk_1.default)(config);try{const o=yield sdk?.orders.create(Object.assign({metadata},orderAttributes));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""});exports.createOrder=createOrder;const getApiOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=(0,getSdk_1.default)(config);try{const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield sdk.orders.retrieve(id,options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}});exports.getApiOrder=getApiOrder;function updateOrder({id,attributes,dispatch,config,include,state}){return tslib_1.__awaiter(this,void 0,void 0,function*(){const sdk=(0,getSdk_1.default)(config);try{const resource=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}exports.updateOrder=updateOrder;const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}exports.addResourceToInclude=addResourceToInclude;function addToCart(params){var _a,_b,_c,_d;return tslib_1.__awaiter(this,void 0,void 0,function*(){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=yield(0,exports.createOrder)(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency;if(buyNowMode)if(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:!0,bundle_code:bundleCode,metadata,frequency},newLineItem=yield sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({id},params),{state}));if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=(0,organization_1.default)((_c=config.endpoint)!==null&&_c!==void 0?_c:""),params2=`${id}?accessToken=${(_d=config.accessToken)!==null&&_d!==void 0?_d:""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}})}exports.addToCart=addToCart;const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}exports.setOrderErrors=setOrderErrors;const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode;function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode,exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPlaceOrder=exports.placeOrderPermitted=exports.setPlaceOrderErrors=exports.placeOrderInitialState=exports.setButtonRef=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors"));function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.setButtonRef=setButtonRef,exports.placeOrderInitialState={errors:[],isPermitted:!1};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setPlaceOrderErrors=setPlaceOrderErrors;function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}exports.placeOrderPermitted=placeOrderPermitted;function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include}){var _a,_b,_c,_d;return tslib_1.__awaiter(this,void 0,void 0,function*(){const response={placed:!1};if(state&&config&&order){const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_a=options?.checkoutCom)===null||_a===void 0)&&_a.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:(_b=options?.checkoutCom)===null||_b===void 0?void 0:_b.session_id});if(((_c=payment?.payment_response)===null||_c===void 0?void 0:_c.status)!=="Authorized"){const[action]=((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};switch((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType){case"braintree_payments":{(0,customerOrderOptions_1.saveToWallet)()&&(yield sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}));const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),(0,customerOrderOptions_1.saveToWallet)()&&(yield sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}exports.setPlaceOrder=setPlaceOrder;const type=["setErrors","setPlaceOrderPermitted","setButtonRef"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPlaceOrder=exports.placeOrderPermitted=exports.setPlaceOrderErrors=exports.placeOrderInitialState=exports.setButtonRef=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),hasSubscriptions_1=require("../utils/hasSubscriptions");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.setButtonRef=setButtonRef,exports.placeOrderInitialState={errors:[],isPermitted:!1};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setPlaceOrderErrors=setPlaceOrderErrors;function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}exports.placeOrderPermitted=placeOrderPermitted;function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include}){var _a,_b,_c,_d;return tslib_1.__awaiter(this,void 0,void 0,function*(){const response={placed:!1};if(state&&config&&order){const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_a=options?.checkoutCom)===null||_a===void 0)&&_a.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:(_b=options?.checkoutCom)===null||_b===void 0?void 0:_b.session_id});if(((_c=payment?.payment_response)===null||_c===void 0?void 0:_c.status)!=="Authorized"){const[action]=((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};switch((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType){case"braintree_payments":{(0,customerOrderOptions_1.saveToWallet)()&&(yield sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}));const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,hasSubscriptions_1.hasSubscriptions)(orderUpdated)&&(yield sdk.orders.update({id:order.id,_create_subscriptions:!0})),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),(0,customerOrderOptions_1.saveToWallet)()&&(yield sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})),setOrderErrors&&setOrderErrors([]),(0,hasSubscriptions_1.hasSubscriptions)(orderUpdated)&&(yield sdk.orders.update({id:order.id,_create_subscriptions:!0})),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}exports.setPlaceOrder=setPlaceOrder;const type=["setErrors","setPlaceOrderPermitted","setButtonRef"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
@@ -1 +1,4 @@
1
1
  export type DefaultChildrenType = JSX.Element[] | JSX.Element | null;
2
+ type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N ? Acc[number] : Enumerate<N, [...Acc, Acc['length']]>;
3
+ export type TRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
4
+ export {};
@@ -4,5 +4,8 @@ interface Props<T> {
4
4
  filterBy: T[];
5
5
  componentName: string;
6
6
  }
7
+ /**
8
+ * Filter children by component display name
9
+ */
7
10
  export default function filterChildren<T = string>({ children, filterBy, componentName }: Props<T>): JSX.Element | JSX.Element[] | null;
8
11
  export {};
@@ -0,0 +1,7 @@
1
+ import { type Order } from '@commercelayer/sdk';
2
+ /**
3
+ * Check if the order has subscriptions reading the frequency attribute of the line items
4
+ * @param order Order
5
+ * @returns boolean
6
+ */
7
+ export declare function hasSubscriptions(order: Order): boolean;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.hasSubscriptions=void 0;function hasSubscriptions(order){var _a;return((_a=order?.line_items)===null||_a===void 0?void 0:_a.some(li=>li.frequency!=null))!=null}exports.hasSubscriptions=hasSubscriptions;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.sortAscIcon=exports.sortDescIcon=void 0;const jsx_runtime_1=require("react/jsx-runtime");exports.sortDescIcon=(0,jsx_runtime_1.jsx)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",width:20,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},{children:(0,jsx_runtime_1.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4"})})),exports.sortAscIcon=(0,jsx_runtime_1.jsx)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",width:20,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},{children:(0,jsx_runtime_1.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"})}));
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.sortAscIcon=exports.sortDescIcon=void 0;const jsx_runtime_1=require("react/jsx-runtime");exports.sortDescIcon=(0,jsx_runtime_1.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,jsx_runtime_1.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4"})}),exports.sortAscIcon=(0,jsx_runtime_1.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,jsx_runtime_1.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"})});
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";export function CustomerContainer(props){const{children,isGuest=!1}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{!include?.includes("available_customer_payment_sources.payment_source")&&!isGuest?addResourceToInclude({newResource:"available_customer_payment_sources.payment_source"}):!includeLoaded?.["available_customer_payment_sources.payment_source"]&&!isGuest&&addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0}})},[include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{config.accessToken&&state.addresses==null&&!isGuest&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&!isGuest&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&!isGuest&&(getCustomerOrders({config,dispatch}),getCustomerPayments({config,dispatch}))},[config.accessToken,order,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
1
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";export function CustomerContainer(props){const{children,isGuest=!1}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{!include?.includes("available_customer_payment_sources.payment_source")&&!isGuest?addResourceToInclude({newResource:"available_customer_payment_sources.payment_source"}):!includeLoaded?.["available_customer_payment_sources.payment_source"]&&!isGuest&&addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0}})},[include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken&&state.addresses==null&&!isGuest&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&!isGuest&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&!isGuest){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}},[config.accessToken,order,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",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&&(console.log("localOrder",localOrder),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;
1
+ import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),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;
@@ -1,28 +1,20 @@
1
- import { type InitialOrderListContext } from '../../context/OrderListChildrenContext';
2
- import { type Column } from 'react-table';
3
- import type { Order } from '@commercelayer/sdk';
4
- import type { DefaultChildrenType } from '../../typings/globals';
5
- export type OrderListColumn = Column & {
6
- Header: string;
7
- accessor: keyof Order;
1
+ import { type TOrderList, type InitialOrderListContext, type OrderListContent } from '../../context/OrderListChildrenContext';
2
+ import { type ColumnDef, type SortingState } from '@tanstack/react-table';
3
+ import type { DefaultChildrenType, TRange } from '../../typings/globals';
4
+ type OrderListColumn<T extends TOrderList = 'orders'> = ColumnDef<OrderListContent<T>> & {
8
5
  className?: string;
9
6
  titleClassName?: string;
10
7
  };
11
- type SortBy = {
12
- id: keyof Order;
13
- } & ({
14
- desc: true;
15
- asc?: never;
16
- } | {
17
- desc?: never;
18
- asc: true;
19
- });
8
+ export type TOrderListColumn<T extends TOrderList = 'orders'> = OrderListColumn<T>;
20
9
  type PaginationProps = {
21
10
  /**
22
11
  * Show table pagination. Default is false.
23
12
  */
24
13
  showPagination: true;
25
- pageSize?: number;
14
+ /**
15
+ * Number of rows per page. Default is 10. Max is 25.
16
+ */
17
+ pageSize?: TRange<1, 26>;
26
18
  } | {
27
19
  /**
28
20
  * Show table pagination. Default is false.
@@ -31,11 +23,18 @@ type PaginationProps = {
31
23
  pageSize?: never;
32
24
  };
33
25
  type Props = {
26
+ /**
27
+ * Type of list to render
28
+ */
29
+ type?: TOrderList;
30
+ /**
31
+ * Children components to render
32
+ */
34
33
  children: DefaultChildrenType;
35
34
  /**
36
35
  * Columns to show
37
36
  */
38
- columns: OrderListColumn[];
37
+ columns: Array<OrderListColumn<TOrderList>>;
39
38
  /**
40
39
  * Custom loader component
41
40
  */
@@ -55,7 +54,7 @@ type Props = {
55
54
  /**
56
55
  * Sort by column. Default is `number` column descending.
57
56
  */
58
- sortBy?: SortBy[];
57
+ sortBy?: SortingState;
59
58
  /**
60
59
  * Class name to assign to pagination container.
61
60
  */
@@ -68,23 +67,6 @@ type Props = {
68
67
  * Class name to assign to the table row.
69
68
  */
70
69
  rowTrClassName?: string;
71
- } & Omit<JSX.IntrinsicElements['table'], 'children'> & ({
72
- /**
73
- * Activate infinity scroll
74
- */
75
- infiniteScroll: true;
76
- /**
77
- * The window options to use for the infinite scroll
78
- */
79
- windowOptions?: {
80
- height?: number;
81
- itemSize?: number;
82
- width?: number;
83
- column?: number;
84
- };
85
- } | {
86
- infiniteScroll?: false;
87
- windowOptions?: never;
88
- }) & PaginationProps;
89
- export declare function OrderList({ children, columns, loadingElement, showActions, showPagination, sortBy, pageSize, paginationContainerClassName, actionsComponent, actionsContainerClassName, infiniteScroll, windowOptions, theadClassName, rowTrClassName, ...p }: Props): JSX.Element;
70
+ } & Omit<JSX.IntrinsicElements['table'], 'children'> & PaginationProps;
71
+ export declare function OrderList({ type, children, columns, loadingElement, showActions, showPagination, sortBy, pageSize, paginationContainerClassName, actionsComponent, actionsContainerClassName, theadClassName, rowTrClassName, ...p }: Props): JSX.Element;
90
72
  export default OrderList;
@@ -1 +1 @@
1
- import{createElement as _createElement}from"react";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect,useCallback}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useTable,useSortBy,useBlockLayout,usePagination}from"react-table";import{FixedSizeList}from"react-window";import scrollbarWidth from"../../utils/scrollbarWidth";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,infiniteScroll,windowOptions,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),{orders}=useContext(CustomerContext),data=useMemo(()=>orders??[],[orders]),cols=useMemo(()=>columns,[columns]),tablePlugins=[useSortBy];infiniteScroll&&tablePlugins.push(useBlockLayout),showPagination&&tablePlugins.push(usePagination);const defaultColumn=useMemo(()=>({width:windowOptions?.column||150}),[windowOptions?.column]),initialState=useMemo(()=>({...showPagination&&{pageSize},sortBy}),[showPagination,pageSize]),table=useTable({data,columns:cols,...infiniteScroll&&{defaultColumn},initialState},...tablePlugins),TableHtmlElement=infiniteScroll?"div":"table",TheadHtmlElement=infiniteScroll?"div":"thead",TbodyHtmlElement=infiniteScroll?"div":"tbody",ThHtmlElement=infiniteScroll?"div":"th",TrHtmlElement=infiniteScroll?"div":"tr";useEffect(()=>(orders!==void 0&&setLoading(!1),()=>{setLoading(!0)}),[orders]);const scrollBarSize=infiniteScroll?useMemo(()=>scrollbarWidth(),[]):0,LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.headerGroups.map((headerGroup,i)=>{const columns2=headerGroup.headers.map((column,k)=>{const sortLabel=column.isSorted?column.isSortedDesc?"desc":"asc":"";return _createElement(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel}`,className:column?.className,...column.getHeaderProps(column?.getSortByToggleProps&&column?.getSortByToggleProps()),key:k},_jsxs("span",{className:column?.titleClassName,children:[column.render("Header"),column.isSorted?column.isSortedDesc?sortDescIcon:sortAscIcon:""]}))});return _createElement(TrHtmlElement,{...headerGroup.getHeaderGroupProps(),key:i},columns2)}),rows=showPagination?table.page:table.rows,rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=infiniteScroll?useCallback(({index,style})=>{const row=rows[index];row&&table.prepareRow(row);const childProps={orders,order:row?.original,row,showActions,actionsComponent,actionsContainerClassName,infiniteScroll};return _jsx(TrHtmlElement,{...row?.getRowProps({style}),className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})})},[table.prepareRow,table.rows]):rows.map((row,i)=>{table.prepareRow(row);const childProps={orders,order:row.original,row,showActions,actionsComponent,actionsContainerClassName,infiniteScroll};return _createElement(TrHtmlElement,{...row.getRowProps(),className:rowTrClassName,key:i},_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents}))}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.canNextPage,canPreviousPage:table.canPreviousPage,gotoPage:table.gotoPage,nextPage:table.nextPage,page:table.page,pageCount:table.pageCount,pageIndex:table.state.pageIndex,pageNumber:table.pageNumber,pageOptions:table.pageOptions,pageSize:table.state.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows:orders?.length??0},children:pagComponents}):null;return loading&&orders==null?_jsx(_Fragment,{children:LoadingComponent}):orders?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,...table.getTableProps(),children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{...table.getTableBodyProps(),children:infiniteScroll?_jsx(FixedSizeList,{height:windowOptions?.height||400,itemCount:table.rows.length,itemSize:windowOptions?.itemSize||100,width:windowOptions?.width||table.totalColumnsWidth+scrollBarSize,children:components}):components})]}),table.rows.length<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
1
+ 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 columns2=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,children:_jsxs("span",{className: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:columns2},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}):orders?.length===0||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 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";import omit from"../../utils/omit";export function OrderListPaginationButtons({previousPageButton,nextPageButton,navigationButtons,children,...props}){const{...prevButton}={show:!0,...previousPageButton},{...nextButton}={show:!0,...nextPageButton},{...navButton}={show:!0,...navigationButtons},ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationButtons",key:"page"}),PrevButton=prevButton.show?prevButton.hideWhenDisabled===!0&&ctx?.canPreviousPage===!1?null:_jsx("button",{"data-testid":"prev-button",...omit(prevButton,["show","hideWhenDisabled"]),disabled:ctx?.canPreviousPage===!1,onClick:()=>ctx?.previousPage(),children:previousPageButton?.label??"<"}):null,NextButton=nextButton.show?nextButton.hideWhenDisabled===!0&&ctx?.canNextPage===!1?null:_jsx("button",{"data-testid":"next-button",...omit(nextButton,["show","hideWhenDisabled"]),disabled:ctx?.canNextPage===!1,onClick:()=>ctx?.nextPage(),children:nextButton?.label??">"}):null,pagesToShow=ctx?.canPreviousPage===!1?ctx?.pageOptions.slice(0,3).map(v=>v+1):ctx?.canNextPage===!1?ctx?.pageOptions.slice(ctx?.pageOptions.length-3,ctx?.pageOptions.length).map(v=>v+1):ctx?.pageOptions.slice(ctx?.pageIndex-1,ctx?.pageIndex+2).map(v=>v+1),NavButtons=navButton.show?pagesToShow?.map(v=>{const className=(ctx?.pageIndex!=null?ctx?.pageIndex+1:1)===v?`${navButton?.className??""} ${navButton?.activeClassName??""}`:navButton?.className;return _jsx("button",{"data-testid":`page-${v}`,...omit(navButton,["show","activeClassName","className"]),className,onClick:()=>ctx?.gotoPage(v-1),children:v},`page-${v}`)}):null,parentProps={navigationButtons,prevButton,nextButton,...ctx,...props};return children==null?ctx?.totalRows===0?null:_jsxs("div",{...props,children:[PrevButton,NavButtons,NextButton]}):_jsx(Parent,{...parentProps,children})}OrderListPaginationButtons.displayName="OrderListPaginationButtons";export default OrderListPaginationButtons;
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";import omit from"../../utils/omit";export function OrderListPaginationButtons({previousPageButton,nextPageButton,navigationButtons,children,...props}){const{...prevButton}={show:!0,...previousPageButton},{...nextButton}={show:!0,...nextPageButton},{...navButton}={show:!0,...navigationButtons},ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationButtons",key:"totalRows"}),PrevButton=prevButton.show?prevButton.hideWhenDisabled===!0&&ctx?.canPreviousPage===!1?null:_jsx("button",{"data-testid":"prev-button",...omit(prevButton,["show","hideWhenDisabled"]),disabled:ctx?.canPreviousPage===!1,onClick:()=>ctx?.previousPage(),children:previousPageButton?.label??"<"}):null,NextButton=nextButton.show?nextButton.hideWhenDisabled===!0&&ctx?.canNextPage===!1?null:_jsx("button",{"data-testid":"next-button",...omit(nextButton,["show","hideWhenDisabled"]),disabled:ctx?.canNextPage===!1,onClick:()=>ctx?.nextPage(),children:nextButton?.label??">"}):null,pagesToShow=ctx?.canPreviousPage===!1?ctx?.pageOptions.slice(0,3).map(v=>v+1):ctx?.canNextPage===!1?ctx?.pageOptions.slice(ctx?.pageOptions.length-3,ctx?.pageOptions.length).map(v=>v+1):ctx?.pageOptions.slice(ctx?.pageIndex-1,ctx?.pageIndex+2).map(v=>v+1),NavButtons=navButton.show?pagesToShow?.map(v=>{const className=(ctx?.pageIndex!=null?ctx?.pageIndex+1:1)===v?`${navButton?.className??""} ${navButton?.activeClassName??""}`:navButton?.className;return _jsx("button",{"data-testid":`page-${v}`,...omit(navButton,["show","activeClassName","className"]),className,onClick:()=>ctx?.gotoPage(v-1),children:v},`page-${v}`)}):null,parentProps={navigationButtons,prevButton,nextButton,...ctx,...props};return children==null?ctx?.totalRows===0?null:_jsxs("div",{...props,children:[PrevButton,NavButtons,NextButton]}):_jsx(Parent,{...parentProps,children})}OrderListPaginationButtons.displayName="OrderListPaginationButtons";export default OrderListPaginationButtons;
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderListPaginationInfo({as="span",children,...props}){const ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationInfo",key:"page"}),TagElement=as,totRows=ctx?.totalRows??0,pageIndex=ctx?.pageIndex??0,pageSize=ctx?.pageSize??10;let firstRow=pageIndex===0?pageIndex+1:pageIndex,lastRow=firstRow*pageSize;ctx?.canPreviousPage===!0&&(firstRow=Math.floor(firstRow*pageSize)+1,lastRow=Math.floor(firstRow+pageSize-1)),ctx?.canNextPage===!1&&(lastRow=totRows);const parentProps={...props,as,firstRow,lastRow,totRows};return children==null?totRows===0?null:_jsx(TagElement,{...props,children:`${firstRow} - ${lastRow} of ${totRows}`}):_jsx(Parent,{...parentProps,children})}OrderListPaginationInfo.displayName="OrderListPaginationInfo";export default OrderListPaginationInfo;
1
+ import{jsx as _jsx}from"react/jsx-runtime";import Parent from"../utils/Parent";import OrderListPaginationContext from"../../context/OrderListPaginationContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderListPaginationInfo({as="span",children,...props}){const ctx=useCustomContext({context:OrderListPaginationContext,contextComponentName:"OrderList",currentComponentName:"OrderListPaginationInfo",key:"totalRows"}),TagElement=as,totRows=ctx?.totalRows??0,pageIndex=ctx?.pageIndex??0,pageSize=ctx?.pageSize??10;let firstRow=pageIndex===0?pageIndex+1:pageIndex,lastRow=firstRow*pageSize;ctx?.canPreviousPage===!0&&(firstRow=Math.floor(firstRow*pageSize)+1,lastRow=Math.floor(firstRow+pageSize-1)),ctx?.canNextPage===!1&&(lastRow=totRows);const parentProps={...props,as,firstRow,lastRow,totRows};return children==null?totRows===0?null:_jsx(TagElement,{...props,children:`${firstRow} - ${lastRow} of ${totRows}`}):_jsx(Parent,{...parentProps,children})}OrderListPaginationInfo.displayName="OrderListPaginationInfo";export default OrderListPaginationInfo;
@@ -1,33 +1,25 @@
1
- import type { Cell, Row } from 'react-table';
2
- import type { Order } from '@commercelayer/sdk';
1
+ import { type TOrderList, type OrderListContent, type TableAccessor } from '../../context/OrderListChildrenContext';
2
+ import { type Row } from '@tanstack/react-table';
3
3
  interface ChildrenProps extends Omit<Props, 'children'> {
4
4
  /**
5
5
  * The order resource
6
6
  */
7
- order: Order;
7
+ order: OrderListContent<TOrderList>;
8
8
  /**
9
9
  * The current row
10
10
  */
11
- row: Row;
11
+ row: Row<OrderListContent<TOrderList>>;
12
12
  /**
13
13
  * The current cell
14
14
  */
15
- cell: Cell[];
16
- /**
17
- * All table cells
18
- */
19
- cells: Cell[];
20
- /**
21
- * Infinite scroll enabled
22
- */
23
- infiniteScroll: boolean;
15
+ cell: Array<ReturnType<Row<OrderListContent<TOrderList>>['getVisibleCells']>[number]>;
24
16
  }
25
17
  interface Props extends Omit<JSX.IntrinsicElements['td'], 'children'> {
26
18
  children?: (props: ChildrenProps) => JSX.Element;
27
19
  /**
28
20
  * The order field to show
29
21
  */
30
- field: keyof Order;
22
+ field: TableAccessor<TOrderList>;
31
23
  }
32
24
  export declare function OrderListRow({ field, children, ...p }: Props): JSX.Element;
33
25
  export declare namespace OrderListRow {
@@ -1 +1 @@
1
- import{createElement as _createElement}from"react";import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import isDate from"../../utils/isDate";import last from"lodash/last";export function OrderListRow({field,children,...p}){const{order,row,showActions,actionsComponent,actionsContainerClassName,infiniteScroll}=useContext(OrderListChildrenContext),cell=row?.cells.filter(cell2=>cell2.column.id===field),isLastRow=last(row?.cells)?.column.id===field,As=infiniteScroll?"div":"td",ActionRow=()=>showActions&&isLastRow&&actionsComponent&&_jsx(As,{"data-testid":"action-cell",...p,className:actionsContainerClassName,children:_jsx(Parent,{...parentProps,children:actionsComponent})})||null,parentProps={...p,field,order,row,cell,infiniteScroll};return children?_jsxs(_Fragment,{children:[_jsx(Parent,{...parentProps,children}),_jsx(ActionRow,{})]}):_jsxs(_Fragment,{children:[cell?.map((cell2,k)=>{const cellValue=cell2.value,value=isDate(cellValue)?new Date(Date.parse(cellValue)).toLocaleString():cell2.render("Cell");return _createElement(As,{"data-testid":`cell-${k}`,...p,...cell2.getCellProps(),key:k},value)}),_jsx(ActionRow,{})]})}OrderListRow.displayName="OrderListRow";export default OrderListRow;
1
+ import{createElement as _createElement}from"react";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import isDate from"../../utils/isDate";import last from"lodash/last";import{flexRender}from"@tanstack/react-table";export function OrderListRow({field,children,...p}){const{order,row,showActions,actionsComponent,actionsContainerClassName}=useContext(OrderListChildrenContext),cell=row?.getVisibleCells().filter(cell2=>cell2.column.id===field),isLastRow=last(row?.getVisibleCells())?.column.id===field,As="td",ActionRow=()=>showActions&&isLastRow&&actionsComponent&&_jsx(As,{"data-testid":"action-cell",...p,className:actionsContainerClassName,children:_jsx(Parent,{...parentProps,children:actionsComponent})})||null,parentProps={...p,field,order,row,cell};return children?_jsxs(As,{children:[_jsx(Parent,{...parentProps,children}),_jsx(ActionRow,{})]}):_jsxs(_Fragment,{children:[cell?.map((cell2,k)=>{const cellValue=cell2.getValue(),value=isDate(cellValue)?new Date(Date.parse(cellValue)).toLocaleString():flexRender(cell2.column.columnDef.cell,cell2.getContext());return _createElement(As,{"data-testid":`cell-${k}`,...p,key:cell2.id},value)}),_jsx(ActionRow,{})]})}OrderListRow.displayName="OrderListRow";export default OrderListRow;