@commercelayer/react-components 4.2.2 → 4.2.3-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.d.ts +2 -2
- package/lib/cjs/components/customers/CustomerContainer.js +1 -1
- package/lib/cjs/components/customers/CustomerPaymentSource.d.ts +10 -0
- package/lib/cjs/components/customers/CustomerPaymentSource.js +1 -0
- package/lib/cjs/components/customers/CustomerPaymentSourceEmpty.d.ts +13 -0
- package/lib/cjs/components/customers/CustomerPaymentSourceEmpty.js +1 -0
- package/lib/cjs/components/orders/PlaceOrderContainer.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceBrandIcon.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceBrandName.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceDetail.d.ts +4 -1
- package/lib/cjs/components/payment_source/PaymentSourceDetail.js +1 -1
- package/lib/cjs/components/shipments/Shipment.js +1 -1
- package/lib/cjs/components/shipments/ShipmentsContainer.js +1 -1
- package/lib/cjs/components/skus/AvailabilityContainer.js +1 -1
- package/lib/cjs/components/skus/AvailabilityTemplate.js +1 -1
- package/lib/cjs/components/utils/GenericFieldComponent.js +1 -1
- package/lib/cjs/context/CustomerContext.d.ts +5 -5
- package/lib/cjs/context/CustomerPaymentSourceContext.d.ts +11 -0
- package/lib/cjs/context/CustomerPaymentSourceContext.js +1 -0
- package/lib/cjs/context/PaymentSourceContext.d.ts +2 -2
- package/lib/cjs/reducers/AvailabilityReducer.d.ts +1 -0
- package/lib/cjs/reducers/AvailabilityReducer.js +1 -1
- package/lib/cjs/reducers/CustomerReducer.d.ts +7 -4
- package/lib/cjs/reducers/CustomerReducer.js +1 -1
- package/lib/cjs/reducers/OrderReducer.d.ts +2 -1
- package/lib/cjs/reducers/OrderReducer.js +1 -1
- package/lib/cjs/utils/getCardDetails.d.ts +5 -5
- package/lib/esm/components/customers/CustomerContainer.d.ts +2 -2
- package/lib/esm/components/customers/CustomerContainer.js +1 -1
- package/lib/esm/components/customers/CustomerPaymentSource.d.ts +10 -0
- package/lib/esm/components/customers/CustomerPaymentSource.js +1 -0
- package/lib/esm/components/customers/CustomerPaymentSourceEmpty.d.ts +13 -0
- package/lib/esm/components/customers/CustomerPaymentSourceEmpty.js +1 -0
- package/lib/esm/components/orders/PlaceOrderContainer.js +1 -1
- package/lib/esm/components/payment_source/PaymentSourceBrandIcon.js +1 -1
- package/lib/esm/components/payment_source/PaymentSourceBrandName.js +1 -1
- package/lib/esm/components/payment_source/PaymentSourceDetail.d.ts +4 -1
- package/lib/esm/components/payment_source/PaymentSourceDetail.js +1 -1
- package/lib/esm/components/shipments/Shipment.js +1 -1
- package/lib/esm/components/shipments/ShipmentsContainer.js +1 -1
- package/lib/esm/components/skus/AvailabilityContainer.js +1 -1
- package/lib/esm/components/skus/AvailabilityTemplate.js +1 -1
- package/lib/esm/components/utils/GenericFieldComponent.js +1 -1
- package/lib/esm/context/CustomerContext.d.ts +5 -5
- package/lib/esm/context/CustomerPaymentSourceContext.d.ts +11 -0
- package/lib/esm/context/CustomerPaymentSourceContext.js +1 -0
- package/lib/esm/context/PaymentSourceContext.d.ts +2 -2
- package/lib/esm/reducers/AvailabilityReducer.d.ts +1 -0
- package/lib/esm/reducers/AvailabilityReducer.js +1 -1
- package/lib/esm/reducers/CustomerReducer.d.ts +7 -4
- package/lib/esm/reducers/CustomerReducer.js +1 -1
- package/lib/esm/reducers/OrderReducer.d.ts +2 -1
- package/lib/esm/reducers/OrderReducer.js +1 -1
- package/lib/esm/utils/getCardDetails.d.ts +5 -5
- package/lib/tsconfig.prod.esm.tsbuildinfo +1 -1
- package/lib/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import AvailabilityContext from"../../context/AvailabilityContext";import Parent from"../utils/Parent";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityTemplate(props){const{timeFormat,showShippingMethodName,showShippingMethodPrice,children,...p}=props,{min,max,shipping_method:shippingMethod,quantity}=useCustomContext({context:AvailabilityContext,contextComponentName:"AvailabilityContainer",currentComponentName:"AvailabilityTemplate",key:"parent"}),text=[],mn=min!=null&&timeFormat!=null?min?.[timeFormat]:"",mx=max!=null&&timeFormat!=null?max?.[timeFormat]:"",shippingMethodPrice=showShippingMethodPrice&&shippingMethod?.formatted_price_amount?`(${shippingMethod?.formatted_price_amount})`:"",name=showShippingMethodName&&shippingMethod?`with ${shippingMethod.name}`:"";quantity&&quantity>0?(text.push("Available"),mn&&mx&&timeFormat&&text.push(`in ${mn} - ${mx} ${timeFormat} ${name} ${shippingMethodPrice}`)):quantity===0&&text.push("Out of stock");const parentProps={min,max,shipping_method:shippingMethod,quantity,text:text.join(" "),...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("span",{
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import AvailabilityContext from"../../context/AvailabilityContext";import Parent from"../utils/Parent";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityTemplate(props){const{timeFormat,showShippingMethodName,showShippingMethodPrice,children,...p}=props,{min,max,shipping_method:shippingMethod,quantity,skuCode}=useCustomContext({context:AvailabilityContext,contextComponentName:"AvailabilityContainer",currentComponentName:"AvailabilityTemplate",key:"parent"}),text=[],mn=min!=null&&timeFormat!=null?min?.[timeFormat]:"",mx=max!=null&&timeFormat!=null?max?.[timeFormat]:"",shippingMethodPrice=showShippingMethodPrice&&shippingMethod?.formatted_price_amount?`(${shippingMethod?.formatted_price_amount})`:"",name=showShippingMethodName&&shippingMethod?`with ${shippingMethod.name}`:"";quantity&&quantity>0?(text.push("Available"),mn&&mx&&timeFormat&&text.push(`in ${mn} - ${mx} ${timeFormat} ${name} ${shippingMethodPrice}`)):quantity===0&&text.push("Out of stock");const parentProps={min,max,shipping_method:shippingMethod,quantity,text:text.join(" "),...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("span",{"data-testid":skuCode?`availability-${skuCode}`:"",...p,children:text.join(" ")})}export default AvailabilityTemplate;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import Parent from"./Parent";import{useContext}from"react";import{defaultImgUrl}from"../../utils/placeholderImages";export default function GenericFieldComponent(props){const{children,tagElement,attribute,context,...p}=props,resourceContext=useContext(context);let attributeValue="";const keysContext=Object.keys(resourceContext).filter(key=>key===
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import Parent from"./Parent";import{useContext}from"react";import{defaultImgUrl}from"../../utils/placeholderImages";export default function GenericFieldComponent(props){const{children,tagElement,attribute,context,resource,...p}=props,resourceContext=useContext(context);let attributeValue="";const keysContext=Object.keys(resourceContext).filter(key=>key===resource);if(keysContext.length===1){const[keyResource]=keysContext;keyResource&&attribute&&(attributeValue=resourceContext[keyResource][attribute])}const Tag=tagElement||"span";if(Tag==="img"&&!children)return _jsx("img",{alt:"",src:attributeValue||defaultImgUrl,...p});const parentProps={attributeValue,tagElement,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx(Tag,{"data-testid":attributeValue,...p,children:attributeValue},attributeValue)}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { SetCustomerErrors, deleteCustomerAddress, CustomerState,
|
|
2
|
+
import { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses } from '../reducers/CustomerReducer';
|
|
3
3
|
export type InitialCustomerContext = Partial<{
|
|
4
4
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
5
5
|
setCustomerErrors: SetCustomerErrors;
|
|
6
6
|
setCustomerEmail: typeof setCustomerEmail;
|
|
7
7
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
8
|
-
deleteCustomerAddress: typeof deleteCustomerAddress
|
|
9
|
-
getCustomerAddresses:
|
|
8
|
+
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
9
|
+
getCustomerAddresses: typeof getCustomerAddresses;
|
|
10
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
11
11
|
} & CustomerState>;
|
|
12
12
|
export declare const defaultCustomerContext: {};
|
|
@@ -15,8 +15,8 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
15
15
|
setCustomerErrors: SetCustomerErrors;
|
|
16
16
|
setCustomerEmail: typeof setCustomerEmail;
|
|
17
17
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
18
|
-
deleteCustomerAddress: typeof deleteCustomerAddress
|
|
19
|
-
getCustomerAddresses:
|
|
18
|
+
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
19
|
+
getCustomerAddresses: typeof getCustomerAddresses;
|
|
20
20
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
21
21
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
22
22
|
export default CustomerContext;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import { IconBrand } from './PaymentSourceContext';
|
|
3
|
+
interface DefaultContext {
|
|
4
|
+
brand?: IconBrand | string;
|
|
5
|
+
exp_month?: number | string;
|
|
6
|
+
exp_year?: number | string;
|
|
7
|
+
last4?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare const defaultCustomerPaymentSourceContext: {};
|
|
10
|
+
declare const CustomerPaymentSourceContext: import("react").Context<DefaultContext>;
|
|
11
|
+
export default CustomerPaymentSourceContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createContext}from"react";export const defaultCustomerPaymentSourceContext={};const CustomerPaymentSourceContext=createContext(defaultCustomerPaymentSourceContext);export default CustomerPaymentSourceContext;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
2
|
export type IconBrand = 'visa' | 'credit-card' | 'amex' | 'mastercard' | 'jcb' | 'wire-transfer' | 'maestro' | 'cirrus' | 'paypal';
|
|
3
|
-
|
|
3
|
+
interface DefaultContext {
|
|
4
4
|
brand?: IconBrand | string;
|
|
5
5
|
exp_month?: number | string;
|
|
6
6
|
exp_year?: number | string;
|
|
@@ -8,7 +8,7 @@ type DefaultContext = {
|
|
|
8
8
|
showCard?: boolean;
|
|
9
9
|
readonly?: boolean;
|
|
10
10
|
handleEditClick?: (e: MouseEvent) => void;
|
|
11
|
-
}
|
|
11
|
+
}
|
|
12
12
|
export declare const defaultPaymentSourceContext: {};
|
|
13
13
|
declare const PaymentSourceContext: import("react").Context<DefaultContext>;
|
|
14
14
|
export default PaymentSourceContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const availabilityInitialState={};export async function getAvailability({skuCode,dispatch,config}){const sdk=getSdk(config);try{const[sku]=await sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=await sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=skuInventory.inventory?.levels||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:{...delivery,quantity:skuInventory.inventory.quantity}})}}catch(error){console.error("Get SKU availability",error)}}const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>baseReducer(state,reducer,typeAction);export default availabilityReducer;
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const availabilityInitialState={};export async function getAvailability({skuCode,dispatch,config}){const sdk=getSdk(config);try{const[sku]=await sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=await sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=skuInventory.inventory?.levels||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:{...delivery,quantity:skuInventory.inventory.quantity,skuCode}})}}catch(error){console.error("Get SKU availability",error)}}const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>baseReducer(state,reducer,typeAction);export default availabilityReducer;
|
|
@@ -6,7 +6,7 @@ import { updateOrder } from './OrderReducer';
|
|
|
6
6
|
export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders';
|
|
7
7
|
export interface CustomerActionPayload {
|
|
8
8
|
addresses: Address[] | null;
|
|
9
|
-
payments: CustomerPaymentSource[];
|
|
9
|
+
payments: CustomerPaymentSource[] | null;
|
|
10
10
|
customerEmail: string;
|
|
11
11
|
errors: BaseError[];
|
|
12
12
|
orders: Order[];
|
|
@@ -93,7 +93,7 @@ export interface GetCustomerPaymentSources {
|
|
|
93
93
|
order?: Order;
|
|
94
94
|
}
|
|
95
95
|
export declare function getCustomerPaymentSources(params?: GetCustomerPaymentSources): void;
|
|
96
|
-
|
|
96
|
+
interface GetCustomerOrdersProps {
|
|
97
97
|
/**
|
|
98
98
|
* The Commerce Layer config
|
|
99
99
|
*/
|
|
@@ -102,8 +102,8 @@ export type GetCustomerOrders = (params: {
|
|
|
102
102
|
* The Customer dispatch function
|
|
103
103
|
*/
|
|
104
104
|
dispatch: Dispatch<CustomerAction>;
|
|
105
|
-
}
|
|
106
|
-
export declare
|
|
105
|
+
}
|
|
106
|
+
export declare function getCustomerOrders({ config, dispatch }: GetCustomerOrdersProps): Promise<void>;
|
|
107
107
|
export type TCustomerAddress = AddressCreate & AddressUpdate;
|
|
108
108
|
interface TCreateCustomerAddress {
|
|
109
109
|
/**
|
|
@@ -124,6 +124,9 @@ interface TCreateCustomerAddress {
|
|
|
124
124
|
state?: CustomerState;
|
|
125
125
|
}
|
|
126
126
|
export declare function createCustomerAddress({ address, config, dispatch, state }: TCreateCustomerAddress): Promise<void>;
|
|
127
|
+
interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
|
|
128
|
+
}
|
|
129
|
+
export declare function getCustomerPayments({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
|
|
127
130
|
export declare const customerInitialState: CustomerState;
|
|
128
131
|
declare const customerReducer: (state: CustomerState, reducer: CustomerAction) => CustomerState;
|
|
129
132
|
export default customerReducer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import jwtDecode from"../utils/jwt";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}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&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,"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
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import jwtDecode from"../utils/jwt";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}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&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,"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}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const customers=await getSdk(config).customers.retrieve(owner.id,{include:["orders"]}),orders=customers.orders?.filter(order=>order.status!=="pending"&&order.status!=="draft");dispatch({type:"setOrders",payload:{orders,customers}})}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch}){if(config!=null&&dispatch!=null){const payments=await getSdk(config).customer_payment_sources.list({include:["payment_source"]});dispatch({type:"setPayments",payload:{payments}})}}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
@@ -26,7 +26,7 @@ export type AddToCartReturn = Promise<{
|
|
|
26
26
|
}>;
|
|
27
27
|
export type AddToCartImport = (params: AddToCartImportParams) => AddToCartReturn;
|
|
28
28
|
export type UnsetOrderState = (dispatch: Dispatch<OrderActions>) => void;
|
|
29
|
-
export type ResourceIncluded = 'billing_address' | 'shipping_address' | 'line_items.line_item_options.sku_option' | 'line_items.item' | 'available_customer_payment_sources.payment_source' | 'shipments.available_shipping_methods' | 'shipments.stock_transfers' | 'shipments.stock_transfers.line_item' | 'shipments.
|
|
29
|
+
export type ResourceIncluded = 'billing_address' | 'shipping_address' | 'line_items.line_item_options.sku_option' | 'line_items.item' | 'available_customer_payment_sources.payment_source' | 'shipments.available_shipping_methods' | 'shipments.stock_transfers' | 'shipments.stock_transfers.line_item' | 'shipments.stock_line_items.line_item' | 'shipments.shipping_method' | 'shipments.stock_location' | 'shipments.parcels' | 'shipments.parcels.parcel_line_items' | 'payment_source' | 'available_payment_methods' | 'payment_method';
|
|
30
30
|
type ResourceIncludedLoaded = Partial<Record<ResourceIncluded, boolean>>;
|
|
31
31
|
export interface OrderPayload {
|
|
32
32
|
loading?: boolean;
|
|
@@ -83,6 +83,7 @@ export interface LineItemOption {
|
|
|
83
83
|
export interface CustomLineItem {
|
|
84
84
|
name?: string;
|
|
85
85
|
imageUrl?: string | null;
|
|
86
|
+
metadata?: Record<string, string>;
|
|
86
87
|
}
|
|
87
88
|
export type AddToCartParams = Partial<{
|
|
88
89
|
bundleCode: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=getSdk(config);try{const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors(error,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=await 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=getErrors(error,"orders");console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=getSdk(config);try{const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:!0,bundle_code:bundleCode},newLineItem=await 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};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=getOrganizationSlug(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors(error,"orders");return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await 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=getErrors(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await 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=getErrors(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
|
|
1
|
+
import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=getSdk(config);try{const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors(error,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=await 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=getErrors(error,"orders");console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=getSdk(config);try{const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors(error,"orders");return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:!0,bundle_code:bundleCode,metadata},newLineItem=await 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};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=getOrganizationSlug(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors(error,"orders");return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await 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=getErrors(error,"orders",codeType);return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await 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=getErrors(error,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { IconBrand } from '../context/PaymentSourceContext';
|
|
2
2
|
import { PaymentResource } from '../reducers/PaymentMethodReducer';
|
|
3
3
|
import { CustomerPaymentSource } from '@commercelayer/sdk';
|
|
4
|
-
|
|
4
|
+
interface CardDetails {
|
|
5
5
|
brand: IconBrand | string;
|
|
6
6
|
last4: string;
|
|
7
7
|
exp_month: number | string;
|
|
8
8
|
exp_year: number | string;
|
|
9
|
-
}
|
|
10
|
-
|
|
9
|
+
}
|
|
10
|
+
interface Args {
|
|
11
11
|
paymentType: PaymentResource;
|
|
12
12
|
customerPayment: Partial<CustomerPaymentSource>;
|
|
13
|
-
}
|
|
14
|
-
export default function getCardDetails({ paymentType, customerPayment
|
|
13
|
+
}
|
|
14
|
+
export default function getCardDetails({ paymentType, customerPayment }: Args): CardDetails;
|
|
15
15
|
export {};
|