@commercelayer/react-components 4.8.6 → 4.9.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.
- package/lib/cjs/components/customers/CustomerContainer.js +1 -1
- package/lib/cjs/components/payment_methods/PaymentMethodsContainer.js +1 -1
- package/lib/cjs/context/CustomerContext.d.ts +3 -1
- package/lib/cjs/hooks/useCustomerContainer.d.ts +5 -2
- package/lib/cjs/hooks/useCustomerContainer.js +1 -1
- package/lib/cjs/reducers/CustomerReducer.d.ts +23 -0
- package/lib/cjs/reducers/CustomerReducer.js +1 -1
- package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
- package/lib/cjs/utils/triggerAttributeHelper.d.ts +31 -0
- package/lib/cjs/utils/triggerAttributeHelper.js +2 -0
- package/lib/esm/components/customers/CustomerContainer.js +1 -1
- package/lib/esm/components/payment_methods/PaymentMethodsContainer.js +1 -1
- package/lib/esm/context/CustomerContext.d.ts +3 -1
- package/lib/esm/hooks/useCustomerContainer.d.ts +5 -2
- package/lib/esm/hooks/useCustomerContainer.js +1 -1
- package/lib/esm/reducers/CustomerReducer.d.ts +23 -0
- package/lib/esm/reducers/CustomerReducer.js +1 -1
- package/lib/esm/reducers/PlaceOrderReducer.js +1 -1
- package/lib/esm/utils/triggerAttributeHelper.d.ts +31 -0
- package/lib/esm/utils/triggerAttributeHelper.js +2 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:({customerAddressId})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:({pageNumber,pageSize})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.CustomerContainer=CustomerContainer,exports.default=CustomerContainer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:({customerAddressId})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:({pageNumber,pageSize})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.CustomerContainer=CustomerContainer,exports.default=CustomerContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethodsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importStar(require("../../context/PaymentMethodContext")),react_1=require("react"),PaymentMethodReducer_1=tslib_1.__importStar(require("../../reducers/PaymentMethodReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty");function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=(0,react_1.useReducer)(PaymentMethodReducer_1.default,PaymentMethodReducer_1.paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=(0,react_1.useContext)(CommerceLayerContext_1.default);function getPayMethods(){return tslib_1.__awaiter(this,void 0,void 0,function*(){order&&(yield(0,PaymentMethodReducer_1.getPaymentMethods)({order,dispatch}))})}(0,react_1.useEffect)(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&(0,isEmpty_1.isEmpty)(state.config)&&(0,PaymentMethodReducer_1.setPaymentMethodConfig)(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({},state),{setLoading:({loading})=>{PaymentMethodContext_1.defaultPaymentMethodContext.setLoading({loading,dispatch})},setPaymentRef:({ref})=>{(0,PaymentMethodReducer_1.setPaymentRef)({ref,dispatch})},setPaymentMethodErrors:errors=>{PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch)},setPaymentMethod:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethod(Object.assign(Object.assign({},args),{config:credentials,updateOrder,order,dispatch,setOrderErrors}))}),setPaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentSource(Object.assign(Object.assign(Object.assign({},state),args),{config:credentials,dispatch,getOrder,updateOrder,order}))}),updatePaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield PaymentMethodContext_1.defaultPaymentMethodContext.updatePaymentSource(Object.assign(Object.assign({},args),{config:credentials,dispatch}))}),destroyPaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield PaymentMethodContext_1.defaultPaymentMethodContext.destroyPaymentSource(Object.assign(Object.assign({},args),{dispatch,config:credentials,updateOrder,orderId:order?.id}))})}),[state]);return(0,jsx_runtime_1.jsx)(PaymentMethodContext_1.default.Provider,{value:contextValue,children})}exports.PaymentMethodsContainer=PaymentMethodsContainer,exports.default=PaymentMethodsContainer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethodsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importStar(require("../../context/PaymentMethodContext")),react_1=require("react"),PaymentMethodReducer_1=tslib_1.__importStar(require("../../reducers/PaymentMethodReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),isEmpty_1=require("../../utils/isEmpty"),localStorage_1=require("../../utils/localStorage");function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=(0,react_1.useReducer)(PaymentMethodReducer_1.default,PaymentMethodReducer_1.paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=(0,react_1.useContext)(CommerceLayerContext_1.default);function getPayMethods(){return tslib_1.__awaiter(this,void 0,void 0,function*(){order&&(yield(0,PaymentMethodReducer_1.getPaymentMethods)({order,dispatch}))})}(0,react_1.useEffect)(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&(0,isEmpty_1.isEmpty)(state.config)&&(0,PaymentMethodReducer_1.setPaymentMethodConfig)(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&((0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}}))},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({},state),{setLoading:({loading})=>{PaymentMethodContext_1.defaultPaymentMethodContext.setLoading({loading,dispatch})},setPaymentRef:({ref})=>{(0,PaymentMethodReducer_1.setPaymentRef)({ref,dispatch})},setPaymentMethodErrors:errors=>{PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch)},setPaymentMethod:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentMethod(Object.assign(Object.assign({},args),{config:credentials,updateOrder,order,dispatch,setOrderErrors}))}),setPaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield PaymentMethodContext_1.defaultPaymentMethodContext.setPaymentSource(Object.assign(Object.assign(Object.assign({},state),args),{config:credentials,dispatch,getOrder,updateOrder,order}))}),updatePaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield PaymentMethodContext_1.defaultPaymentMethodContext.updatePaymentSource(Object.assign(Object.assign({},args),{config:credentials,dispatch}))}),destroyPaymentSource:args=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield PaymentMethodContext_1.defaultPaymentMethodContext.destroyPaymentSource(Object.assign(Object.assign({},args),{dispatch,config:credentials,updateOrder,orderId:order?.id}))})}),[state]);return(0,jsx_runtime_1.jsx)(PaymentMethodContext_1.default.Provider,{value:contextValue,children})}exports.PaymentMethodsContainer=PaymentMethodsContainer,exports.default=PaymentMethodsContainer;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses, type getCustomerOrders, type getCustomerSubscriptions } from '../reducers/CustomerReducer';
|
|
2
|
+
import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses, type getCustomerOrders, type getCustomerSubscriptions, type setResourceTrigger } from '../reducers/CustomerReducer';
|
|
3
3
|
export type InitialCustomerContext = Partial<{
|
|
4
4
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
5
5
|
setCustomerErrors: SetCustomerErrors;
|
|
@@ -8,6 +8,7 @@ export type InitialCustomerContext = Partial<{
|
|
|
8
8
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
9
9
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
10
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
11
|
+
setResourceTrigger: typeof setResourceTrigger;
|
|
11
12
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
12
13
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
13
14
|
} & CustomerState>;
|
|
@@ -20,6 +21,7 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
20
21
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
21
22
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
22
23
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
24
|
+
setResourceTrigger: typeof setResourceTrigger;
|
|
23
25
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
24
26
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
25
27
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import { type CustomerState } from '../reducers/CustomerReducer';
|
|
2
|
-
|
|
1
|
+
import { type setResourceTrigger, type CustomerState } from '../reducers/CustomerReducer';
|
|
2
|
+
type TCustomer = Omit<CustomerState, 'errors' | 'isGuest'> & {
|
|
3
|
+
setResourceTrigger?: typeof setResourceTrigger;
|
|
4
|
+
};
|
|
5
|
+
interface TReturnCustomer extends Omit<TCustomer, 'errors' | 'isGuest'> {
|
|
3
6
|
}
|
|
4
7
|
/**
|
|
5
8
|
* React Hook that provides access to the order context stored in the `<CustomerContainer>` component.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useCustomerContainer=void 0;const tslib_1=require("tslib"),CustomerContext_1=tslib_1.__importDefault(require("../context/CustomerContext")),react_1=require("react");function useCustomerContainer(){const ctx=(0,react_1.useContext)(CustomerContext_1.default);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}exports.useCustomerContainer=useCustomerContainer,exports.default=useCustomerContainer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useCustomerContainer=void 0;const tslib_1=require("tslib"),CustomerContext_1=tslib_1.__importDefault(require("../context/CustomerContext")),react_1=require("react");function useCustomerContainer(){const ctx=(0,react_1.useContext)(CustomerContext_1.default);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers,setResourceTrigger:ctx.setResourceTrigger};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}exports.useCustomerContainer=useCustomerContainer,exports.default=useCustomerContainer;
|
|
@@ -4,6 +4,7 @@ import type { Address, AddressCreate, AddressUpdate, Customer, CustomerPaymentSo
|
|
|
4
4
|
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
5
5
|
import { type updateOrder } from './OrderReducer';
|
|
6
6
|
import { type ListResponse } from '@commercelayer/sdk/lib/cjs/resource';
|
|
7
|
+
import { type TriggerAttributeHelper } from '../utils/triggerAttributeHelper';
|
|
7
8
|
export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders' | 'setSubscriptions' | 'setCustomers';
|
|
8
9
|
export interface CustomerActionPayload {
|
|
9
10
|
addresses: Address[] | null;
|
|
@@ -143,6 +144,28 @@ interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
|
|
|
143
144
|
}
|
|
144
145
|
export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
|
|
145
146
|
export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
|
|
147
|
+
export type SetResourceTriggerParams = {
|
|
148
|
+
/**
|
|
149
|
+
* The CommerceLayer config
|
|
150
|
+
*/
|
|
151
|
+
config?: CommerceLayerConfig;
|
|
152
|
+
/**
|
|
153
|
+
* The dispatch function
|
|
154
|
+
*/
|
|
155
|
+
dispatch?: Dispatch<CustomerAction>;
|
|
156
|
+
/**
|
|
157
|
+
* The page size
|
|
158
|
+
*/
|
|
159
|
+
pageSize?: number;
|
|
160
|
+
/**
|
|
161
|
+
* The page number
|
|
162
|
+
*/
|
|
163
|
+
pageNumber?: number;
|
|
164
|
+
} & TriggerAttributeHelper;
|
|
165
|
+
/**
|
|
166
|
+
* Helper to trigger and activate an attribute on a resource
|
|
167
|
+
*/
|
|
168
|
+
export declare function setResourceTrigger({ config, dispatch, resource, attribute, id, pageSize, pageNumber }: SetResourceTriggerParams): Promise<boolean>;
|
|
146
169
|
export declare const customerInitialState: CustomerState;
|
|
147
170
|
declare const customerReducer: (state: CustomerState, reducer: CustomerAction) => CustomerState;
|
|
148
171
|
export default customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=exports.getCustomerInfo=exports.getCustomerPayments=exports.createCustomerAddress=exports.getCustomerSubscriptions=exports.getCustomerOrders=exports.getCustomerPaymentSources=exports.deleteCustomerAddress=exports.getCustomerAddresses=exports.setCustomerEmail=exports.setCustomerErrors=exports.saveCustomerUser=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=tslib_1.__importDefault(require("../utils/jwt")),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken");function saveCustomerUser({customerEmail,order,updateOrder}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}exports.saveCustomerUser=saveCustomerUser;function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setCustomerErrors=setCustomerErrors;function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}exports.setCustomerEmail=setCustomerEmail;function getCustomerAddresses({config,dispatch,isOrderAvailable}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}exports.getCustomerAddresses=getCustomerAddresses;function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config&&addresses&&dispatch&&config)try{yield(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}})}exports.deleteCustomerAddress=deleteCustomerAddress;function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}exports.getCustomerPaymentSources=getCustomerPaymentSources;function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}exports.getCustomerOrders=getCustomerOrders;function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const subscriptions=yield(0,getSdk_1.default)(config).customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}})}exports.getCustomerSubscriptions=getCustomerSubscriptions;function createCustomerAddress({address,config,dispatch,state}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const upAddress=yield sdk.addresses.update(address),updatedAddresses=(_a=state?.addresses)===null||_a===void 0?void 0:_a.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=yield sdk.addresses.create(address);if(!((_b=state?.customers)===null||_b===void 0)&&_b.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_c=state?.customers)===null||_c===void 0?void 0:_c.id),address:sdk.addresses.relationship(newAddress.id)});yield sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}})}exports.createCustomerAddress=createCustomerAddress;function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const payments=yield sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}})}exports.getCustomerPayments=getCustomerPayments;function getCustomerInfo({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=yield sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}})}exports.getCustomerInfo=getCustomerInfo,exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=exports.setResourceTrigger=exports.getCustomerInfo=exports.getCustomerPayments=exports.createCustomerAddress=exports.getCustomerSubscriptions=exports.getCustomerOrders=exports.getCustomerPaymentSources=exports.deleteCustomerAddress=exports.getCustomerAddresses=exports.setCustomerEmail=exports.setCustomerErrors=exports.saveCustomerUser=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=tslib_1.__importDefault(require("../utils/jwt")),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper");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,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.default)(config.accessToken);if(owner?.id){const payments=yield sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}})}exports.getCustomerPayments=getCustomerPayments;function getCustomerInfo({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=yield sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}})}exports.getCustomerInfo=getCustomerInfo;function setResourceTrigger({config,dispatch,resource,attribute,id,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 params={config,resource,attribute,id};if((yield(0,triggerAttributeHelper_1.triggerAttributeHelper)(params))!=null&&dispatch!=null){switch(resource){case"orders":yield getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":yield getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}}return!1})}exports.setResourceTrigger=setResourceTrigger,exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"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")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage");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,currentCustomerPaymentSourceId}){var _a,_b,_c,_d,_e,_f;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};if((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==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_e=ps?.options)===null||_e===void 0?void 0:_e.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((((_f=order.line_items)===null||_f===void 0?void 0:_f.some(item=>{var _a2;return item.frequency&&((_a2=item.frequency)===null||_a2===void 0?void 0:_a2.length)>0}))||order?.subscription_created_at!=null||!1)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&¤tCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),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)()&&
|
|
2
|
+
"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")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage");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,currentCustomerPaymentSourceId}){var _a,_b,_c,_d,_e,_f;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};if((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==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_e=ps?.options)===null||_e===void 0?void 0:_e.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((((_f=order.line_items)===null||_f===void 0?void 0:_f.some(item=>{var _a2;return item.frequency&&((_a2=item.frequency)===null||_a2===void 0?void 0:_a2.length)>0}))||order?.subscription_created_at!=null||!1)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&¤tCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),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)()&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)}),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;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
2
|
+
import { type Order, type OrderSubscription } from '@commercelayer/sdk';
|
|
3
|
+
export type HelperRequestResource = 'orders' | 'order_subscriptions';
|
|
4
|
+
export type TriggerAttributeHelper = {
|
|
5
|
+
/**
|
|
6
|
+
* CommerceLayer config
|
|
7
|
+
*/
|
|
8
|
+
config: CommerceLayerConfig;
|
|
9
|
+
/**
|
|
10
|
+
* The resource id
|
|
11
|
+
*/
|
|
12
|
+
id: string;
|
|
13
|
+
} & ({
|
|
14
|
+
/**
|
|
15
|
+
* The resource name
|
|
16
|
+
*/
|
|
17
|
+
resource: 'orders';
|
|
18
|
+
/**
|
|
19
|
+
* The attribute to trigger
|
|
20
|
+
*/
|
|
21
|
+
attribute: '_place' | '_refresh' | '_create_subscriptions';
|
|
22
|
+
} | {
|
|
23
|
+
resource: 'order_subscriptions';
|
|
24
|
+
attribute: '_active' | '_deactivate' | '_cancel';
|
|
25
|
+
});
|
|
26
|
+
type TriggerAttributeHelperResponse = Promise<Order | OrderSubscription>;
|
|
27
|
+
/**
|
|
28
|
+
* Helper to trigger an attribute on a resource
|
|
29
|
+
*/
|
|
30
|
+
export declare function triggerAttributeHelper({ config, id, attribute, resource }: TriggerAttributeHelper): TriggerAttributeHelperResponse;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.triggerAttributeHelper=void 0;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk"));function triggerAttributeHelper({config,id,attribute,resource}){return tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,getSdk_1.default)(config)[resource].update({id,[attribute]:!0})})}exports.triggerAttributeHelper=triggerAttributeHelper;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},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;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext,{defaultPaymentMethodContext}from"../../context/PaymentMethodContext";import{useContext,useEffect,useReducer,useMemo}from"react";import paymentMethodReducer,{paymentMethodInitialState,getPaymentMethods,setPaymentMethodConfig,setPaymentRef}from"../../reducers/PaymentMethodReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";export function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=useReducer(paymentMethodReducer,paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=useContext(CommerceLayerContext);async function getPayMethods(){order&&await getPaymentMethods({order,dispatch})}useEffect(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&isEmpty(state.config)&&setPaymentMethodConfig(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=useMemo(()=>({...state,setLoading:({loading})=>{defaultPaymentMethodContext.setLoading({loading,dispatch})},setPaymentRef:({ref})=>{setPaymentRef({ref,dispatch})},setPaymentMethodErrors:errors=>{defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch)},setPaymentMethod:async args=>await defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>{await defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch})},destroyPaymentSource:async args=>{await defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}}),[state]);return _jsx(PaymentMethodContext.Provider,{value:contextValue,children})}export default PaymentMethodsContainer;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext,{defaultPaymentMethodContext}from"../../context/PaymentMethodContext";import{useContext,useEffect,useReducer,useMemo}from"react";import paymentMethodReducer,{paymentMethodInitialState,getPaymentMethods,setPaymentMethodConfig,setPaymentRef}from"../../reducers/PaymentMethodReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{isEmpty}from"../../utils/isEmpty";import{setCustomerOrderParam}from"../../utils/localStorage";export function PaymentMethodsContainer(props){const{children,config}=props,[state,dispatch]=useReducer(paymentMethodReducer,paymentMethodInitialState),{order,getOrder,setOrderErrors,include,addResourceToInclude,updateOrder,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PaymentMethodsContainer",key:"order"}),credentials=useContext(CommerceLayerContext);async function getPayMethods(){order&&await getPaymentMethods({order,dispatch})}useEffect(()=>{include?.includes("available_payment_methods")?includeLoaded?.available_payment_methods||addResourceToInclude({newResourceLoaded:{available_payment_methods:!0,payment_source:!0,payment_method:!0,"line_items.line_item_options.sku_option":!0,"line_items.item":!0}}):addResourceToInclude({newResource:["available_payment_methods","payment_source","payment_method","line_items.line_item_options.sku_option","line_items.item"]}),config&&isEmpty(state.config)&&setPaymentMethodConfig(config,dispatch),credentials&&order&&!state.paymentMethods&&getPayMethods(),order?.payment_source&&dispatch({type:"setPaymentSource",payload:{paymentSource:order?.payment_source}}),order?.payment_source===null&&(setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}}))},[order,credentials,include?.length,Object.keys(includeLoaded??[]).length]);const contextValue=useMemo(()=>({...state,setLoading:({loading})=>{defaultPaymentMethodContext.setLoading({loading,dispatch})},setPaymentRef:({ref})=>{setPaymentRef({ref,dispatch})},setPaymentMethodErrors:errors=>{defaultPaymentMethodContext.setPaymentMethodErrors(errors,dispatch)},setPaymentMethod:async args=>await defaultPaymentMethodContext.setPaymentMethod({...args,config:credentials,updateOrder,order,dispatch,setOrderErrors}),setPaymentSource:async args=>await defaultPaymentMethodContext.setPaymentSource({...state,...args,config:credentials,dispatch,getOrder,updateOrder,order}),updatePaymentSource:async args=>{await defaultPaymentMethodContext.updatePaymentSource({...args,config:credentials,dispatch})},destroyPaymentSource:async args=>{await defaultPaymentMethodContext.destroyPaymentSource({...args,dispatch,config:credentials,updateOrder,orderId:order?.id})}}),[state]);return _jsx(PaymentMethodContext.Provider,{value:contextValue,children})}export default PaymentMethodsContainer;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses, type getCustomerOrders, type getCustomerSubscriptions } from '../reducers/CustomerReducer';
|
|
2
|
+
import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses, type getCustomerOrders, type getCustomerSubscriptions, type setResourceTrigger } from '../reducers/CustomerReducer';
|
|
3
3
|
export type InitialCustomerContext = Partial<{
|
|
4
4
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
5
5
|
setCustomerErrors: SetCustomerErrors;
|
|
@@ -8,6 +8,7 @@ export type InitialCustomerContext = Partial<{
|
|
|
8
8
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
9
9
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
10
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
11
|
+
setResourceTrigger: typeof setResourceTrigger;
|
|
11
12
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
12
13
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
13
14
|
} & CustomerState>;
|
|
@@ -20,6 +21,7 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
20
21
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
21
22
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
22
23
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
24
|
+
setResourceTrigger: typeof setResourceTrigger;
|
|
23
25
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
24
26
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
25
27
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import { type CustomerState } from '../reducers/CustomerReducer';
|
|
2
|
-
|
|
1
|
+
import { type setResourceTrigger, type CustomerState } from '../reducers/CustomerReducer';
|
|
2
|
+
type TCustomer = Omit<CustomerState, 'errors' | 'isGuest'> & {
|
|
3
|
+
setResourceTrigger?: typeof setResourceTrigger;
|
|
4
|
+
};
|
|
5
|
+
interface TReturnCustomer extends Omit<TCustomer, 'errors' | 'isGuest'> {
|
|
3
6
|
}
|
|
4
7
|
/**
|
|
5
8
|
* React Hook that provides access to the order context stored in the `<CustomerContainer>` component.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import CustomerContext from"../context/CustomerContext";import{useContext}from"react";export function useCustomerContainer(){const ctx=useContext(CustomerContext);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}export default useCustomerContainer;
|
|
2
|
+
import CustomerContext from"../context/CustomerContext";import{useContext}from"react";export function useCustomerContainer(){const ctx=useContext(CustomerContext);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers,setResourceTrigger:ctx.setResourceTrigger};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}export default useCustomerContainer;
|
|
@@ -4,6 +4,7 @@ import type { Address, AddressCreate, AddressUpdate, Customer, CustomerPaymentSo
|
|
|
4
4
|
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
5
5
|
import { type updateOrder } from './OrderReducer';
|
|
6
6
|
import { type ListResponse } from '@commercelayer/sdk/lib/cjs/resource';
|
|
7
|
+
import { type TriggerAttributeHelper } from '../utils/triggerAttributeHelper';
|
|
7
8
|
export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders' | 'setSubscriptions' | 'setCustomers';
|
|
8
9
|
export interface CustomerActionPayload {
|
|
9
10
|
addresses: Address[] | null;
|
|
@@ -143,6 +144,28 @@ interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
|
|
|
143
144
|
}
|
|
144
145
|
export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
|
|
145
146
|
export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
|
|
147
|
+
export type SetResourceTriggerParams = {
|
|
148
|
+
/**
|
|
149
|
+
* The CommerceLayer config
|
|
150
|
+
*/
|
|
151
|
+
config?: CommerceLayerConfig;
|
|
152
|
+
/**
|
|
153
|
+
* The dispatch function
|
|
154
|
+
*/
|
|
155
|
+
dispatch?: Dispatch<CustomerAction>;
|
|
156
|
+
/**
|
|
157
|
+
* The page size
|
|
158
|
+
*/
|
|
159
|
+
pageSize?: number;
|
|
160
|
+
/**
|
|
161
|
+
* The page number
|
|
162
|
+
*/
|
|
163
|
+
pageNumber?: number;
|
|
164
|
+
} & TriggerAttributeHelper;
|
|
165
|
+
/**
|
|
166
|
+
* Helper to trigger and activate an attribute on a resource
|
|
167
|
+
*/
|
|
168
|
+
export declare function setResourceTrigger({ config, dispatch, resource, attribute, id, pageSize, pageNumber }: SetResourceTriggerParams): Promise<boolean>;
|
|
146
169
|
export declare const customerInitialState: CustomerState;
|
|
147
170
|
declare const customerReducer: (state: CustomerState, reducer: CustomerAction) => CustomerState;
|
|
148
171
|
export default customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import jwtDecode from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const subscriptions=await getSdk(config).customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwtDecode(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import jwtDecode from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const subscriptions=await getSdk(config).customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwtDecode(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){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=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){const sdk=getSdk(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;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.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};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch((order.line_items?.some(item=>item.frequency&&item.frequency?.length>0)||order?.subscription_created_at!=null||!1)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&¤tCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{saveToWallet()&&await sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0});const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),saveToWallet()&&
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){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=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){const sdk=getSdk(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;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.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};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch((order.line_items?.some(item=>item.frequency&&item.frequency?.length>0)||order?.subscription_created_at!=null||!1)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&¤tCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{saveToWallet()&&await sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0});const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),saveToWallet()&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)}),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}const type=["setErrors","setPlaceOrderPermitted","setButtonRef"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
2
|
+
import { type Order, type OrderSubscription } from '@commercelayer/sdk';
|
|
3
|
+
export type HelperRequestResource = 'orders' | 'order_subscriptions';
|
|
4
|
+
export type TriggerAttributeHelper = {
|
|
5
|
+
/**
|
|
6
|
+
* CommerceLayer config
|
|
7
|
+
*/
|
|
8
|
+
config: CommerceLayerConfig;
|
|
9
|
+
/**
|
|
10
|
+
* The resource id
|
|
11
|
+
*/
|
|
12
|
+
id: string;
|
|
13
|
+
} & ({
|
|
14
|
+
/**
|
|
15
|
+
* The resource name
|
|
16
|
+
*/
|
|
17
|
+
resource: 'orders';
|
|
18
|
+
/**
|
|
19
|
+
* The attribute to trigger
|
|
20
|
+
*/
|
|
21
|
+
attribute: '_place' | '_refresh' | '_create_subscriptions';
|
|
22
|
+
} | {
|
|
23
|
+
resource: 'order_subscriptions';
|
|
24
|
+
attribute: '_active' | '_deactivate' | '_cancel';
|
|
25
|
+
});
|
|
26
|
+
type TriggerAttributeHelperResponse = Promise<Order | OrderSubscription>;
|
|
27
|
+
/**
|
|
28
|
+
* Helper to trigger an attribute on a resource
|
|
29
|
+
*/
|
|
30
|
+
export declare function triggerAttributeHelper({ config, id, attribute, resource }: TriggerAttributeHelper): TriggerAttributeHelperResponse;
|
|
31
|
+
export {};
|