@commercelayer/react-components 4.19.0 → 4.20.1-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/gift_cards/GiftCardOrCouponCode.d.ts +5 -5
- package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.js +1 -1
- package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +6 -6
- package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
- package/lib/cjs/components/orders/AddToCartButton.d.ts +6 -6
- package/lib/cjs/components/orders/AddToCartButton.js +1 -1
- package/lib/cjs/components/orders/GiftCardAmount.d.ts +3 -3
- package/lib/cjs/components/orders/GiftCardAmount.js +1 -1
- package/lib/cjs/components/orders/OrderContainer.d.ts +8 -4
- package/lib/cjs/components/orders/OrderContainer.js +1 -1
- package/lib/cjs/components/orders/PlaceOrderButton.d.ts +6 -6
- package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
- package/lib/cjs/components/orders/TotalAmount.d.ts +3 -3
- package/lib/cjs/components/orders/TotalAmount.js +1 -1
- package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
- package/lib/cjs/components/payment_source/KlarnaPayment.d.ts +4 -4
- package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
- package/lib/cjs/components/payment_source/StripeExpressPayment.d.ts +2 -2
- package/lib/cjs/components/payment_source/StripeExpressPayment.js +1 -1
- package/lib/cjs/context/OrderContext.d.ts +5 -3
- package/lib/cjs/context/OrderContext.js +1 -1
- package/lib/cjs/reducers/OrderReducer.d.ts +34 -20
- package/lib/cjs/reducers/OrderReducer.js +1 -1
- package/lib/cjs/reducers/PaymentMethodReducer.d.ts +26 -26
- package/lib/cjs/reducers/PlaceOrderReducer.d.ts +11 -11
- package/lib/cjs/utils/adyen/manageGiftCard.d.ts +16 -0
- package/lib/cjs/utils/adyen/manageGiftCard.js +2 -0
- package/lib/cjs/utils/expressPaymentHelper.d.ts +8 -8
- package/lib/cjs/utils/expressPaymentHelper.js +1 -1
- package/lib/esm/components/gift_cards/GiftCardOrCouponCode.d.ts +5 -5
- package/lib/esm/components/gift_cards/GiftCardOrCouponCode.js +1 -1
- package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +6 -6
- package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
- package/lib/esm/components/orders/AddToCartButton.d.ts +6 -6
- package/lib/esm/components/orders/AddToCartButton.js +1 -1
- package/lib/esm/components/orders/GiftCardAmount.d.ts +3 -3
- package/lib/esm/components/orders/GiftCardAmount.js +1 -1
- package/lib/esm/components/orders/OrderContainer.d.ts +8 -4
- package/lib/esm/components/orders/OrderContainer.js +1 -1
- package/lib/esm/components/orders/PlaceOrderButton.d.ts +6 -6
- package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
- package/lib/esm/components/orders/TotalAmount.d.ts +3 -3
- package/lib/esm/components/orders/TotalAmount.js +1 -1
- package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
- package/lib/esm/components/payment_source/KlarnaPayment.d.ts +4 -4
- package/lib/esm/components/payment_source/KlarnaPayment.js +1 -1
- package/lib/esm/components/payment_source/StripeExpressPayment.d.ts +2 -2
- package/lib/esm/components/payment_source/StripeExpressPayment.js +1 -1
- package/lib/esm/context/OrderContext.d.ts +5 -3
- package/lib/esm/context/OrderContext.js +1 -1
- package/lib/esm/reducers/OrderReducer.d.ts +34 -20
- package/lib/esm/reducers/OrderReducer.js +1 -1
- package/lib/esm/reducers/PaymentMethodReducer.d.ts +26 -26
- package/lib/esm/reducers/PlaceOrderReducer.d.ts +11 -11
- package/lib/esm/utils/adyen/manageGiftCard.d.ts +16 -0
- package/lib/esm/utils/adyen/manageGiftCard.js +2 -0
- package/lib/esm/utils/expressPaymentHelper.d.ts +8 -8
- package/lib/esm/utils/expressPaymentHelper.js +1 -1
- package/lib/tsconfig.prod.esm.tsbuildinfo +1 -1
- package/lib/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +19 -19
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type { Dispatch } from
|
|
2
|
-
import { type SetLocalOrder, type DeleteLocalOrder } from
|
|
3
|
-
import type { CommerceLayerConfig } from
|
|
4
|
-
import type { BaseMetadataObject } from
|
|
5
|
-
import type { BaseError } from
|
|
6
|
-
import type { AddressResource } from
|
|
7
|
-
import type { Order, OrderUpdate } from
|
|
8
|
-
import type { LooseAutocomplete } from
|
|
1
|
+
import type { Dispatch } from "react";
|
|
2
|
+
import { type SetLocalOrder, type DeleteLocalOrder } from "../utils/localStorage";
|
|
3
|
+
import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
|
|
4
|
+
import type { BaseMetadataObject } from "../typings/index";
|
|
5
|
+
import type { BaseError } from "../typings/errors";
|
|
6
|
+
import type { AddressResource } from "./AddressReducer";
|
|
7
|
+
import type { Order, OrderUpdate, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
|
|
8
|
+
import type { LooseAutocomplete } from "../typings/globals";
|
|
9
9
|
export type GetOrderParams = Partial<{
|
|
10
10
|
clearWhenPlaced: boolean;
|
|
11
11
|
config: CommerceLayerConfig;
|
|
@@ -16,8 +16,8 @@ export type GetOrderParams = Partial<{
|
|
|
16
16
|
state: OrderState;
|
|
17
17
|
}>;
|
|
18
18
|
export type GetOrder = (params: GetOrderParams) => Promise<undefined | Order>;
|
|
19
|
-
type CreateOrderParams = Pick<AddToCartParams,
|
|
20
|
-
export interface AddToCartImportParams extends Omit<AddToCartParams,
|
|
19
|
+
type CreateOrderParams = Pick<AddToCartParams, "config" | "dispatch" | "persistKey" | "state" | "orderMetadata" | "orderAttributes" | "setLocalOrder">;
|
|
20
|
+
export interface AddToCartImportParams extends Omit<AddToCartParams, "skuCode" | "skuId" | "quantity" | "option" | "lineItem"> {
|
|
21
21
|
lineItems: CustomLineItem[];
|
|
22
22
|
}
|
|
23
23
|
export type AddToCartReturn = Promise<{
|
|
@@ -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 =
|
|
29
|
+
export type ResourceIncluded = "billing_address" | "shipping_address" | "line_items.line_item_options.sku_option" | "line_items.item" | "available_customer_payment_sources.payment_source" | "available_customer_payment_sources.payment_method" | "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;
|
|
@@ -36,30 +36,44 @@ export interface OrderPayload {
|
|
|
36
36
|
include?: ResourceIncluded[] | undefined;
|
|
37
37
|
includeLoaded?: ResourceIncludedLoaded;
|
|
38
38
|
withoutIncludes?: boolean;
|
|
39
|
+
manageAdyenGiftCard?: boolean;
|
|
39
40
|
}
|
|
40
|
-
export type AddToCartImportValues = Pick<AddToCartImportParams,
|
|
41
|
+
export type AddToCartImportValues = Pick<AddToCartImportParams, "lineItems">;
|
|
41
42
|
export type getOrderContext = (id: string) => Promise<undefined | Order>;
|
|
42
43
|
export type OrderState = Partial<OrderPayload>;
|
|
43
44
|
export interface OrderActions {
|
|
44
45
|
type: OrderActionType;
|
|
45
46
|
payload: OrderPayload;
|
|
46
47
|
}
|
|
47
|
-
export type OrderActionType =
|
|
48
|
+
export type OrderActionType = "setLoading" | "setOrderId" | "setOrder" | "setSingleQuantity" | "setCurrentSkuCodes" | "setCurrentSkuPrices" | "setCurrentItem" | "setErrors" | "setSaveAddressToCustomerAddressBook" | "setGiftCardOrCouponCode" | "setIncludesResource";
|
|
48
49
|
export declare function createOrder(params: CreateOrderParams): Promise<string>;
|
|
49
50
|
export declare const getApiOrder: GetOrder;
|
|
50
51
|
export interface UpdateOrderArgs {
|
|
51
52
|
id: string;
|
|
52
|
-
attributes: Omit<OrderUpdate,
|
|
53
|
+
attributes: Omit<OrderUpdate, "id">;
|
|
53
54
|
dispatch?: Dispatch<OrderActions>;
|
|
54
55
|
include?: string[];
|
|
55
56
|
config?: CommerceLayerConfig;
|
|
56
57
|
state?: OrderState;
|
|
57
58
|
}
|
|
58
|
-
export declare function updateOrder({ id, attributes, dispatch, config, include, state }: UpdateOrderArgs): Promise<{
|
|
59
|
+
export declare function updateOrder({ id, attributes, dispatch, config, include, state, }: UpdateOrderArgs): Promise<{
|
|
59
60
|
success: boolean;
|
|
60
61
|
error?: unknown;
|
|
61
62
|
order?: Order;
|
|
62
63
|
}>;
|
|
64
|
+
interface TResourceRequest {
|
|
65
|
+
resource: Extract<keyof CommerceLayerClient, "adyen_payments">;
|
|
66
|
+
requestType: "update";
|
|
67
|
+
attributes: TResourceRequest["resource"] extends "adyen_payments" ? AdyenPaymentUpdate : ResourceUpdate;
|
|
68
|
+
order: Order;
|
|
69
|
+
dispatch?: Dispatch<OrderActions>;
|
|
70
|
+
config?: CommerceLayerConfig;
|
|
71
|
+
state?: OrderState;
|
|
72
|
+
}
|
|
73
|
+
export declare function paymentSourceRequest({ resource, requestType, dispatch, attributes, config, order, state, }: TResourceRequest): Promise<{
|
|
74
|
+
success: boolean;
|
|
75
|
+
order?: Order;
|
|
76
|
+
}>;
|
|
63
77
|
export declare const setOrder: (order: Order, dispatch?: Dispatch<OrderActions>) => void;
|
|
64
78
|
export interface AddResourceToInclude {
|
|
65
79
|
resourcesIncluded?: ResourceIncluded[];
|
|
@@ -68,7 +82,7 @@ export interface AddResourceToInclude {
|
|
|
68
82
|
resourceIncludedLoaded?: ResourceIncludedLoaded;
|
|
69
83
|
newResourceLoaded?: ResourceIncludedLoaded;
|
|
70
84
|
}
|
|
71
|
-
export declare function addResourceToInclude({ resourcesIncluded, dispatch, newResource, newResourceLoaded, resourceIncludedLoaded }: AddResourceToInclude): void;
|
|
85
|
+
export declare function addResourceToInclude({ resourcesIncluded, dispatch, newResource, newResourceLoaded, resourceIncludedLoaded, }: AddResourceToInclude): void;
|
|
72
86
|
export interface LineItemOption {
|
|
73
87
|
/**
|
|
74
88
|
* SKU Option ID. Ex: mNJEgsJwBn
|
|
@@ -80,7 +94,7 @@ export interface LineItemOption {
|
|
|
80
94
|
options: Record<string, string>;
|
|
81
95
|
quantity?: number;
|
|
82
96
|
}
|
|
83
|
-
type TFrequency =
|
|
97
|
+
type TFrequency = "hourly" | "daily" | "weekly" | "monthly" | "two-month" | "three-month" | "four-month" | "six-month" | "yearly";
|
|
84
98
|
export interface CustomLineItem {
|
|
85
99
|
name?: string;
|
|
86
100
|
imageUrl?: string | null;
|
|
@@ -134,11 +148,11 @@ interface TSetGiftCardOrCouponCodeParams {
|
|
|
134
148
|
include?: string[];
|
|
135
149
|
state?: OrderState;
|
|
136
150
|
}
|
|
137
|
-
export declare function setGiftCardOrCouponCode({ code, codeType, dispatch, config, order, include, state }: TSetGiftCardOrCouponCodeParams): Promise<{
|
|
151
|
+
export declare function setGiftCardOrCouponCode({ code, codeType, dispatch, config, order, include, state, }: TSetGiftCardOrCouponCodeParams): Promise<{
|
|
138
152
|
success: boolean;
|
|
139
153
|
order?: Order;
|
|
140
154
|
}>;
|
|
141
|
-
export type CodeType =
|
|
155
|
+
export type CodeType = "coupon" | "gift_card";
|
|
142
156
|
export type OrderCodeType = `${CodeType}_code`;
|
|
143
157
|
interface TRemoveGiftCardOrCouponCodeParams {
|
|
144
158
|
codeType: OrderCodeType;
|
|
@@ -148,7 +162,7 @@ interface TRemoveGiftCardOrCouponCodeParams {
|
|
|
148
162
|
include?: string[];
|
|
149
163
|
state?: OrderState;
|
|
150
164
|
}
|
|
151
|
-
export declare function removeGiftCardOrCouponCode({ codeType, dispatch, config, order, include, state }: TRemoveGiftCardOrCouponCodeParams): Promise<{
|
|
165
|
+
export declare function removeGiftCardOrCouponCode({ codeType, dispatch, config, order, include, state, }: TRemoveGiftCardOrCouponCodeParams): Promise<{
|
|
152
166
|
success: boolean;
|
|
153
167
|
order?: Order;
|
|
154
168
|
}>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.saveAddressToCustomerAddressBook=exports.unsetOrderState=exports.setOrder=exports.getApiOrder=void 0,exports.createOrder=createOrder,exports.updateOrder=updateOrder,exports.addResourceToInclude=addResourceToInclude,exports.addToCart=addToCart,exports.setOrderErrors=setOrderErrors,exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode,exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode;const tslib_1=require("tslib"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=require("../utils/organization"),events_1=require("../utils/events"),getDomain_1=require("../utils/getDomain"),getApplicationLink_1=require("../utils/getApplicationLink"),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];function createOrder(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=yield sdk?.orders.create(Object.assign({metadata},orderAttributes));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""})}const getApiOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}});exports.getApiOrder=getApiOrder;function updateOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}function addToCart(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f;const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=yield createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:(_c=lineItem?._update_quantity)!==null&&_c!==void 0?_c:!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=yield sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({id},params),{state}));if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${(_d=config.accessToken)!==null&&_d!==void 0?_d:""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=yield(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:(_f=(_e=organizationConfig?.links)===null||_e===void 0?void 0:_e.checkout)!==null&&_f!==void 0?_f:href;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}})}const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;function setGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}function removeGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.saveAddressToCustomerAddressBook=exports.unsetOrderState=exports.setOrder=exports.getApiOrder=void 0,exports.createOrder=createOrder,exports.updateOrder=updateOrder,exports.paymentSourceRequest=paymentSourceRequest,exports.addResourceToInclude=addResourceToInclude,exports.addToCart=addToCart,exports.setOrderErrors=setOrderErrors,exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode,exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode;const tslib_1=require("tslib"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=require("../utils/organization"),events_1=require("../utils/events"),getDomain_1=require("../utils/getDomain"),getApplicationLink_1=require("../utils/getApplicationLink"),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];function createOrder(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=yield sdk?.orders.create(Object.assign({metadata},orderAttributes));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""})}const getApiOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}});exports.getApiOrder=getApiOrder;function updateOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}function paymentSourceRequest(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};yield sdk[resource][requestType](attributes);const orderUpdated=yield updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state});return{success:!0,order:orderUpdated?.order}}catch(error){console.error("Resource request",error);const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}function addToCart(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f;const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=yield createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:(_c=lineItem?._update_quantity)!==null&&_c!==void 0?_c:!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=yield sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({id},params),{state}));if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${(_d=config.accessToken)!==null&&_d!==void 0?_d:""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=yield(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:(_f=(_e=organizationConfig?.links)===null||_e===void 0?void 0:_e.checkout)!==null&&_f!==void 0?_f:href;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}})}const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;function setGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}function removeGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import type { AdyenPaymentConfig } from
|
|
2
|
-
import type { BraintreeConfig } from
|
|
3
|
-
import type { PaypalConfig } from
|
|
4
|
-
import type { StripeConfig } from
|
|
5
|
-
import type { WireTransferConfig } from
|
|
6
|
-
import type { CommerceLayerConfig } from
|
|
7
|
-
import type { getOrderContext, updateOrder } from
|
|
8
|
-
import type { BaseError } from
|
|
9
|
-
import type { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from
|
|
10
|
-
import type { Dispatch, MutableRefObject } from
|
|
11
|
-
import type { CheckoutComConfig } from
|
|
12
|
-
import type { ExternalPaymentConfig } from
|
|
13
|
-
import type { ResourceKeys } from
|
|
14
|
-
export type PaymentSourceType = Order[
|
|
1
|
+
import type { AdyenPaymentConfig } from "../components/payment_source/AdyenPayment";
|
|
2
|
+
import type { BraintreeConfig } from "../components/payment_source/BraintreePayment";
|
|
3
|
+
import type { PaypalConfig } from "../components/payment_source/PaypalPayment";
|
|
4
|
+
import type { StripeConfig } from "../components/payment_source/StripePayment";
|
|
5
|
+
import type { WireTransferConfig } from "../components/payment_source/WireTransferPayment";
|
|
6
|
+
import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
|
|
7
|
+
import type { getOrderContext, updateOrder } from "./OrderReducer";
|
|
8
|
+
import type { BaseError } from "../typings/errors";
|
|
9
|
+
import type { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from "@commercelayer/sdk";
|
|
10
|
+
import type { Dispatch, MutableRefObject } from "react";
|
|
11
|
+
import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
|
|
12
|
+
import type { ExternalPaymentConfig } from "../components/payment_source/ExternalPayment";
|
|
13
|
+
import type { ResourceKeys } from "../utils/getPaymentAttributes";
|
|
14
|
+
export type PaymentSourceType = Order["payment_source"];
|
|
15
15
|
interface Card {
|
|
16
16
|
type: string;
|
|
17
17
|
brand: string;
|
|
@@ -25,7 +25,7 @@ export interface PaymentSourceObject {
|
|
|
25
25
|
payment_method?: Card;
|
|
26
26
|
};
|
|
27
27
|
payment_response?: {
|
|
28
|
-
resultCode?:
|
|
28
|
+
resultCode?: "Authorised";
|
|
29
29
|
};
|
|
30
30
|
};
|
|
31
31
|
braintree_payments: BraintreePayment & {
|
|
@@ -43,13 +43,13 @@ export interface PaymentSourceObject {
|
|
|
43
43
|
};
|
|
44
44
|
payment_method?: {
|
|
45
45
|
card: Card;
|
|
46
|
-
type: string |
|
|
46
|
+
type: string | "klarna" | "card";
|
|
47
47
|
};
|
|
48
48
|
};
|
|
49
49
|
wire_transfers: WireTransfer;
|
|
50
50
|
checkout_com_payments: CheckoutComPayment & {
|
|
51
51
|
payment_response: {
|
|
52
|
-
source?: Pick<Card,
|
|
52
|
+
source?: Pick<Card, "last4"> & {
|
|
53
53
|
scheme: string;
|
|
54
54
|
expiry_year: number;
|
|
55
55
|
expiry_month: number;
|
|
@@ -58,7 +58,7 @@ export interface PaymentSourceObject {
|
|
|
58
58
|
};
|
|
59
59
|
klarna_payments: KlarnaPayment;
|
|
60
60
|
}
|
|
61
|
-
export type PaymentMethodActionType =
|
|
61
|
+
export type PaymentMethodActionType = "setErrors" | "setPaymentMethods" | "setPaymentMethodConfig" | "setPaymentSource" | "setPaymentRef" | "setLoading";
|
|
62
62
|
export type PaymentRef = MutableRefObject<null | HTMLFormElement>;
|
|
63
63
|
export interface PaymentMethodActionPayload {
|
|
64
64
|
errors: BaseError[];
|
|
@@ -68,10 +68,10 @@ export interface PaymentMethodActionPayload {
|
|
|
68
68
|
currentPaymentMethodRef: PaymentRef;
|
|
69
69
|
currentCustomerPaymentSourceId: string | null;
|
|
70
70
|
config: PaymentMethodConfig;
|
|
71
|
-
paymentSource: Order[
|
|
71
|
+
paymentSource: Order["payment_source"] | null;
|
|
72
72
|
loading: boolean;
|
|
73
73
|
}
|
|
74
|
-
export declare function setLoading({ loading, dispatch }: {
|
|
74
|
+
export declare function setLoading({ loading, dispatch, }: {
|
|
75
75
|
loading: boolean;
|
|
76
76
|
dispatch?: Dispatch<PaymentMethodAction>;
|
|
77
77
|
}): void;
|
|
@@ -94,8 +94,8 @@ type GetPaymentMethods = (args: {
|
|
|
94
94
|
}) => Promise<void>;
|
|
95
95
|
export declare const getPaymentMethods: GetPaymentMethods;
|
|
96
96
|
export type PaymentResource = keyof PaymentSourceObject;
|
|
97
|
-
export type PaymentResourceKey =
|
|
98
|
-
export type SDKPaymentResource =
|
|
97
|
+
export type PaymentResourceKey = "braintreePayment" | "stripePayment" | "klarnaPayment" | "wireTransfer" | "paypalPayment" | "adyenPayment" | "checkoutComPayment";
|
|
98
|
+
export type SDKPaymentResource = "AdyenPayment" | "BraintreePayment" | "ExternalPayment" | "PaypalPayment" | "StripePayment" | "WireTransfer" | "CheckoutComPayment";
|
|
99
99
|
interface TSetPaymentMethodParams {
|
|
100
100
|
config?: CommerceLayerConfig;
|
|
101
101
|
dispatch?: Dispatch<PaymentMethodAction>;
|
|
@@ -107,7 +107,7 @@ interface TSetPaymentMethodParams {
|
|
|
107
107
|
paymentMethodId: string;
|
|
108
108
|
paymentResource?: PaymentResource;
|
|
109
109
|
}
|
|
110
|
-
export declare function setPaymentMethod({ config, dispatch, order, paymentMethodId, updateOrder, setOrderErrors, paymentResource }: TSetPaymentMethodParams): Promise<{
|
|
110
|
+
export declare function setPaymentMethod({ config, dispatch, order, paymentMethodId, updateOrder, setOrderErrors, paymentResource, }: TSetPaymentMethodParams): Promise<{
|
|
111
111
|
success: boolean;
|
|
112
112
|
order?: Order;
|
|
113
113
|
}>;
|
|
@@ -116,7 +116,7 @@ export type SetPaymentSourceResponse = {
|
|
|
116
116
|
order: Order;
|
|
117
117
|
paymentSource: PaymentSourceTypes;
|
|
118
118
|
} | null;
|
|
119
|
-
export interface SetPaymentSourceParams extends Omit<PaymentMethodState,
|
|
119
|
+
export interface SetPaymentSourceParams extends Omit<PaymentMethodState, "config"> {
|
|
120
120
|
config?: CommerceLayerConfig;
|
|
121
121
|
dispatch?: Dispatch<PaymentMethodAction>;
|
|
122
122
|
getOrder?: getOrderContext;
|
|
@@ -127,7 +127,7 @@ export interface SetPaymentSourceParams extends Omit<PaymentMethodState, 'config
|
|
|
127
127
|
customerPaymentSourceId?: string;
|
|
128
128
|
updateOrder?: typeof updateOrder;
|
|
129
129
|
}
|
|
130
|
-
export declare function setPaymentSource({ config, dispatch, getOrder, attributes, order, paymentResource, customerPaymentSourceId, paymentSourceId, updateOrder, errors: currentErrors }: SetPaymentSourceParams): Promise<PaymentSourceType | undefined | null>;
|
|
130
|
+
export declare function setPaymentSource({ config, dispatch, getOrder, attributes, order, paymentResource, customerPaymentSourceId, paymentSourceId, updateOrder, errors: currentErrors, }: SetPaymentSourceParams): Promise<PaymentSourceType | undefined | null>;
|
|
131
131
|
export type UpdatePaymentSource = (args: {
|
|
132
132
|
id: string;
|
|
133
133
|
attributes: Record<string, any>;
|
|
@@ -149,7 +149,7 @@ export interface PaymentMethodConfig {
|
|
|
149
149
|
braintreePayment?: BraintreeConfig;
|
|
150
150
|
checkoutComPayment?: CheckoutComConfig;
|
|
151
151
|
externalPayment?: ExternalPaymentConfig;
|
|
152
|
-
klarnaPayment?: Pick<AdyenPaymentConfig,
|
|
152
|
+
klarnaPayment?: Pick<AdyenPaymentConfig, "placeOrderCallback"> & Pick<StripeConfig, "containerClassName">;
|
|
153
153
|
paypalPayment?: PaypalConfig;
|
|
154
154
|
stripePayment?: StripeConfig;
|
|
155
155
|
wireTransfer?: Partial<WireTransferConfig>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { Dispatch, RefObject } from
|
|
2
|
-
import type { CommerceLayerConfig } from
|
|
3
|
-
import type { BaseError } from
|
|
4
|
-
import type { Order } from
|
|
5
|
-
import type { PaymentResource, PaymentSourceType } from
|
|
6
|
-
export type PlaceOrderActionType =
|
|
1
|
+
import type { Dispatch, RefObject } from "react";
|
|
2
|
+
import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
|
|
3
|
+
import type { BaseError } from "../typings/errors";
|
|
4
|
+
import type { Order } from "@commercelayer/sdk";
|
|
5
|
+
import type { PaymentResource, PaymentSourceType } from "./PaymentMethodReducer";
|
|
6
|
+
export type PlaceOrderActionType = "setErrors" | "setPlaceOrderPermitted" | "setButtonRef" | "setStatus";
|
|
7
7
|
export interface PlaceOrderOptions {
|
|
8
8
|
paypalPayerId?: string;
|
|
9
9
|
adyen?: {
|
|
@@ -32,7 +32,7 @@ export interface PlaceOrderActionPayload {
|
|
|
32
32
|
paymentSource: PaymentSourceType;
|
|
33
33
|
options?: PlaceOrderOptions;
|
|
34
34
|
placeOrderButtonRef?: RefObject<HTMLButtonElement | null>;
|
|
35
|
-
status:
|
|
35
|
+
status: "placing" | "standby";
|
|
36
36
|
}
|
|
37
37
|
export declare function setButtonRef(ref: RefObject<HTMLButtonElement | null>, dispatch: Dispatch<PlaceOrderAction>): void;
|
|
38
38
|
export type PlaceOrderState = Partial<PlaceOrderActionPayload>;
|
|
@@ -48,7 +48,7 @@ interface TPlaceOrderPermittedParams {
|
|
|
48
48
|
order?: Order;
|
|
49
49
|
options?: PlaceOrderOptions;
|
|
50
50
|
}
|
|
51
|
-
export declare function placeOrderPermitted({ config, order, dispatch, options }: TPlaceOrderPermittedParams): void;
|
|
51
|
+
export declare function placeOrderPermitted({ config, order, dispatch, options, }: TPlaceOrderPermittedParams): void;
|
|
52
52
|
interface TSetPlaceOrderParams {
|
|
53
53
|
config?: CommerceLayerConfig;
|
|
54
54
|
order?: Order;
|
|
@@ -59,13 +59,13 @@ interface TSetPlaceOrderParams {
|
|
|
59
59
|
setOrder?: (order: Order) => void;
|
|
60
60
|
currentCustomerPaymentSourceId?: string | null;
|
|
61
61
|
}
|
|
62
|
-
export declare function setPlaceOrder({ state, order, config, setOrderErrors, paymentSource, setOrder, include, currentCustomerPaymentSourceId }: TSetPlaceOrderParams): Promise<{
|
|
62
|
+
export declare function setPlaceOrder({ state, order, config, setOrderErrors, paymentSource, setOrder, include, currentCustomerPaymentSourceId, }: TSetPlaceOrderParams): Promise<{
|
|
63
63
|
placed: boolean;
|
|
64
64
|
errors?: BaseError[];
|
|
65
65
|
order?: Order;
|
|
66
66
|
}>;
|
|
67
|
-
export declare function setPlaceOrderStatus({ status, dispatch }: {
|
|
68
|
-
status:
|
|
67
|
+
export declare function setPlaceOrderStatus({ status, dispatch, }: {
|
|
68
|
+
status: "placing" | "standby";
|
|
69
69
|
dispatch?: Dispatch<PlaceOrderAction>;
|
|
70
70
|
}): void;
|
|
71
71
|
declare const placeOrderReducer: (state: PlaceOrderState, reducer: PlaceOrderAction) => PlaceOrderState;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Order } from "@commercelayer/sdk";
|
|
2
|
+
export interface GiftCardData {
|
|
3
|
+
cardSummary: string;
|
|
4
|
+
currentBalanceValue: number;
|
|
5
|
+
currentBalanceCurrency: string;
|
|
6
|
+
formattedBalanceValue: string;
|
|
7
|
+
cardBrand: string;
|
|
8
|
+
}
|
|
9
|
+
interface Props {
|
|
10
|
+
order?: Order;
|
|
11
|
+
}
|
|
12
|
+
interface ReturnTypes extends GiftCardData {
|
|
13
|
+
formattedOrderTotal: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function manageGiftCard({ order }: Props): ReturnTypes | null;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.manageGiftCard=manageGiftCard;function manageGiftCard({order}){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k;if(!order||!order?.payment_source)return null;const getPaymentSource=((_a=order.payment_source)===null||_a===void 0?void 0:_a.type)==="adyen_payments"?order.payment_source:null;if(!getPaymentSource||!(((_c=(_b=getPaymentSource?.payment_request_data)===null||_b===void 0?void 0:_b.payment_method)===null||_c===void 0?void 0:_c.type)==="giftcard"))return null;const additionalData=(_d=getPaymentSource?.payment_response)===null||_d===void 0?void 0:_d.additionalData,amount=(_e=getPaymentSource?.payment_response)===null||_e===void 0?void 0:_e.amount.value,giftCardData={cardSummary:additionalData?.cardSummary,currentBalanceValue:amount??Number.parseInt(additionalData?.currentBalanceValue),currentBalanceCurrency:additionalData?.currentBalanceCurrency,cardBrand:(_f=additionalData?.originalSelectedBrand)!==null&&_f!==void 0?_f:additionalData?.paymentMethod,formattedBalanceValue:additionalData?.currentBalanceValue},formattedOrderTotal=((order?.total_amount_with_taxes_cents!=null?order?.total_amount_with_taxes_cents-giftCardData.currentBalanceValue:0)/100).toLocaleString((_g=order.language_code)!==null&&_g!==void 0?_g:"en",{style:"currency",currency:(_h=order?.currency_code)!==null&&_h!==void 0?_h:"USD"}),formattedCurrentBalance=(giftCardData.currentBalanceValue/100).toLocaleString((_j=order.language_code)!==null&&_j!==void 0?_j:"en",{style:"currency",currency:(_k=order?.currency_code)!==null&&_k!==void 0?_k:"USD"});return giftCardData.formattedBalanceValue=formattedCurrentBalance,Object.assign(Object.assign({},giftCardData),{formattedOrderTotal})}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { CommerceLayerConfig } from
|
|
2
|
-
import type { Order, PaymentMethod, QueryParamsRetrieve, AddressCreate } from
|
|
3
|
-
import type { PaymentRequestShippingOption } from
|
|
4
|
-
import type { PaymentResource } from
|
|
1
|
+
import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
|
|
2
|
+
import type { Order, PaymentMethod, QueryParamsRetrieve, AddressCreate } from "@commercelayer/sdk";
|
|
3
|
+
import type { PaymentRequestShippingOption } from "@stripe/stripe-js";
|
|
4
|
+
import type { PaymentResource } from "../reducers/PaymentMethodReducer";
|
|
5
5
|
export declare function getAvailableExpressPayments(paymentMethods: PaymentMethod[]): PaymentMethod[];
|
|
6
6
|
interface TFakeAddressParams {
|
|
7
7
|
/**
|
|
@@ -21,7 +21,7 @@ interface TFakeAddressParams {
|
|
|
21
21
|
*/
|
|
22
22
|
email?: string;
|
|
23
23
|
}
|
|
24
|
-
export declare function setExpressFakeAddress({ orderId, config, address, email }: TFakeAddressParams): Promise<Order>;
|
|
24
|
+
export declare function setExpressFakeAddress({ orderId, config, address, email, }: TFakeAddressParams): Promise<Order>;
|
|
25
25
|
export declare function getExpressShippingMethods(order: Order): PaymentRequestShippingOption[] | null;
|
|
26
26
|
type TSetExpressShippingMethodParams = {
|
|
27
27
|
/**
|
|
@@ -49,7 +49,7 @@ type TSetExpressShippingMethodParams = {
|
|
|
49
49
|
selectFirst?: true;
|
|
50
50
|
selectedShippingMethodId?: never;
|
|
51
51
|
});
|
|
52
|
-
export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params }: TSetExpressShippingMethodParams): Promise<Order>;
|
|
52
|
+
export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params, }: TSetExpressShippingMethodParams): Promise<Order>;
|
|
53
53
|
export type TSetExpressPlaceOrderParams = {
|
|
54
54
|
/**
|
|
55
55
|
* The Commerce Layer config
|
|
@@ -77,7 +77,7 @@ export type TSetExpressPlaceOrderParams = {
|
|
|
77
77
|
paymentSourceId?: never;
|
|
78
78
|
placeTheOrder?: true;
|
|
79
79
|
});
|
|
80
|
-
export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder }: TSetExpressPlaceOrderParams): Promise<Order>;
|
|
80
|
+
export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder, }: TSetExpressPlaceOrderParams): Promise<Order>;
|
|
81
81
|
interface TExpressRedirectUrlParams {
|
|
82
82
|
/**
|
|
83
83
|
* Order resource
|
|
@@ -88,5 +88,5 @@ interface TExpressRedirectUrlParams {
|
|
|
88
88
|
*/
|
|
89
89
|
config: CommerceLayerConfig;
|
|
90
90
|
}
|
|
91
|
-
export declare function expressRedirectUrl({ order, config: { accessToken, endpoint } }: TExpressRedirectUrlParams): void
|
|
91
|
+
export declare function expressRedirectUrl({ order, config: { accessToken, endpoint }, }: TExpressRedirectUrlParams): Promise<void>;
|
|
92
92
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=getAvailableExpressPayments,exports.setExpressFakeAddress=setExpressFakeAddress,exports.getExpressShippingMethods=getExpressShippingMethods,exports.setExpressShippingMethod=setExpressShippingMethod,exports.setExpressPlaceOrder=setExpressPlaceOrder,exports.expressRedirectUrl=expressRedirectUrl;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),getDomain_1=require("./getDomain"),availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}function setExpressFakeAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=(0,getSdk_1.default)(config),fakeAddress=yield sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),yield sdk.orders.update(resource,params),yield sdk.orders.retrieve(orderId,params)})}function getExpressShippingMethods(order){var _a,_b;const isSingleShipment=((_a=order?.shipments)===null||_a===void 0?void 0:_a.length)===1,shippingMethods=(_b=order?.shipments)===null||_b===void 0?void 0:_b.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>{var _a2,_b2,_c;return{id:(_a2=method?.id)!==null&&_a2!==void 0?_a2:"",label:(_b2=method?.name)!==null&&_b2!==void 0?_b2:"",amount:(_c=method?.price_amount_for_shipment_cents)!==null&&_c!==void 0?_c:0,detail:""}});
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=getAvailableExpressPayments,exports.setExpressFakeAddress=setExpressFakeAddress,exports.getExpressShippingMethods=getExpressShippingMethods,exports.setExpressShippingMethod=setExpressShippingMethod,exports.setExpressPlaceOrder=setExpressPlaceOrder,exports.expressRedirectUrl=expressRedirectUrl;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),getDomain_1=require("./getDomain"),organization_1=require("./organization"),availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}function setExpressFakeAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=(0,getSdk_1.default)(config),fakeAddress=yield sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),yield sdk.orders.update(resource,params),yield sdk.orders.retrieve(orderId,params)})}function getExpressShippingMethods(order){var _a,_b;const isSingleShipment=((_a=order?.shipments)===null||_a===void 0?void 0:_a.length)===1,shippingMethods=(_b=order?.shipments)===null||_b===void 0?void 0:_b.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>{var _a2,_b2,_c;return{id:(_a2=method?.id)!==null&&_a2!==void 0?_a2:"",label:(_b2=method?.name)!==null&&_b2!==void 0?_b2:"",amount:(_c=method?.price_amount_for_shipment_cents)!==null&&_c!==void 0?_c:0,detail:""}});if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{var _a2;if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push((_a2=firstMethod.price_amount_for_shipment_cents)!==null&&_a2!==void 0?_a2:0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}function setExpressShippingMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){var _b,_c,_d;const sdk=(0,getSdk_1.default)(config),order=yield sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}else selectedShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)}));else for(const shipment of(_b=order?.shipments)!==null&&_b!==void 0?_b:[]){const[firstShippingMethodId]=(_d=(_c=shipment?.available_shipping_methods)===null||_c===void 0?void 0:_c.map(method=>method.id))!==null&&_d!==void 0?_d:[];firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}return yield sdk.orders.retrieve(order.id,params)})}function setExpressPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=(0,getSdk_1.default)(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return yield sdk.orders.retrieve(orderId,{include}),yield sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),yield sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),yield sdk[paymentResource].update({id:paymentSourceId,_update:!0}),yield sdk.orders.retrieve(orderId,{include})}return yield sdk.orders.update({id:orderId,_place:!0})})}function expressRedirectUrl(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({order,config:{accessToken,endpoint}}){var _b,_c;if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=(0,getDomain_1.getDomain)(endpoint);if(slug==null)throw new Error("No slug found");const config=yield(0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{accessToken,slug,orderId:order?.id}}),href=((_b=config?.links)===null||_b===void 0?void 0:_b.checkout)!=null?(_c=config?.links)===null||_c===void 0?void 0:_c.checkout:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;!window.location.pathname.includes("/cart")?window.location.reload():window.top!=null&&(window.top.location.href=href)})}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { type JSX } from
|
|
2
|
-
import type { ChildrenFunction } from
|
|
3
|
-
import type { CodeType } from
|
|
4
|
-
interface ChildrenProps extends Omit<Props,
|
|
1
|
+
import { type JSX } from "react";
|
|
2
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
3
|
+
import type { CodeType } from "../../reducers/OrderReducer";
|
|
4
|
+
interface ChildrenProps extends Omit<Props, "children" | "type"> {
|
|
5
5
|
code?: string | null;
|
|
6
6
|
hide?: boolean;
|
|
7
7
|
discountAmountCents?: number | null;
|
|
8
8
|
discountAmountFloat?: number | null;
|
|
9
9
|
formattedDiscountAmount?: string | null;
|
|
10
10
|
}
|
|
11
|
-
interface Props extends Omit<JSX.IntrinsicElements[
|
|
11
|
+
interface Props extends Omit<JSX.IntrinsicElements["span"], "children"> {
|
|
12
12
|
type?: CodeType;
|
|
13
13
|
children?: ChildrenFunction<ChildrenProps>;
|
|
14
14
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";export function GiftCardOrCouponCode({children,type,...props}){const{order}=useContext(OrderContext);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:""
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function GiftCardOrCouponCode({children,type,...props}){const{order,manageAdyenGiftCard}=useContext(OrderContext);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:"";let hide=!(order&&code);if(manageAdyenGiftCard&&type==="gift_card"){const giftCardData=manageGiftCard({order});if(console.log("order",order),console.log("giftCardData",giftCardData),!giftCardData)return null;hide=!1;const parentProps2={...props,code:`${giftCardData.cardBrand} ${giftCardData.cardSummary}`,hide};return children?_jsx(Parent,{...parentProps2,children}):hide?null:_jsx("span",{...props,children:code})}const parentProps={...props,code,hide,discountAmountCents:order?.discount_amount_cents,discountAmountFloat:order?.discount_amount_float,formattedDiscountAmount:order?.formatted_discount_amount};return children?_jsx(Parent,{...parentProps,children}):hide?null:_jsx("span",{...props,children:code})}export default GiftCardOrCouponCode;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { type ReactNode, type JSX } from
|
|
2
|
-
import type { ChildrenFunction } from
|
|
3
|
-
import type { CodeType, OrderCodeType } from
|
|
4
|
-
import type { Order } from
|
|
5
|
-
interface ChildrenProps extends Omit<Props,
|
|
1
|
+
import { type ReactNode, type JSX } from "react";
|
|
2
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
3
|
+
import type { CodeType, OrderCodeType } from "../../reducers/OrderReducer";
|
|
4
|
+
import type { Order } from "@commercelayer/sdk";
|
|
5
|
+
interface ChildrenProps extends Omit<Props, "children" | "onClick"> {
|
|
6
6
|
codeType?: OrderCodeType;
|
|
7
7
|
hide?: boolean;
|
|
8
8
|
handleClick?: () => void;
|
|
@@ -15,6 +15,6 @@ type Props = {
|
|
|
15
15
|
success: boolean;
|
|
16
16
|
order?: Order;
|
|
17
17
|
}) => void;
|
|
18
|
-
} & Omit<JSX.IntrinsicElements[
|
|
18
|
+
} & Omit<JSX.IntrinsicElements["button"], "type" | "onClick">;
|
|
19
19
|
export declare function GiftCardOrCouponRemoveButton(props: Props): JSX.Element | null;
|
|
20
20
|
export default GiftCardOrCouponRemoveButton;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";export function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode}=useContext(OrderContext);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:""
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode,manageAdyenGiftCard,paymentSourceRequest}=useContext(OrderContext);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:"";let hide=!(order&&code);const handleClick=async()=>{if(manageAdyenGiftCard&&codeType==="gift_card_code"&&order!=null){console.log("handle click gift card");const id=order?.payment_source?.id;if(console.log("id",id),id!=null){const res=await paymentSourceRequest({resource:"adyen_payments",requestType:"update",attributes:{id,payment_request_data:{}},order});onClick!=null&&res!=null&&onClick(res)}}else if(codeType!=null&&removeGiftCardOrCouponCode!=null){const response=await removeGiftCardOrCouponCode({codeType});onClick!=null&&response!=null&&onClick(response)}};if(manageAdyenGiftCard&&type==="gift_card"){if(!manageGiftCard({order}))return null;hide=!1;const parentProps2={...p,label,handleClick,codeType};return children?_jsx(Parent,{...parentProps2,children}):hide?null:_jsx("button",{type:"button",onClick:()=>{handleClick()},...p,children:label})}const parentProps={...p,label,handleClick,codeType};return children?_jsx(Parent,{...parentProps,children}):hide?null:_jsx("button",{type:"button",onClick:()=>{handleClick()},...p,children:label})}export default GiftCardOrCouponRemoveButton;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { type PropsWithoutRef, type JSX } from
|
|
2
|
-
import type { ChildrenFunction } from
|
|
3
|
-
import type { AddToCartReturn, CustomLineItem, LineItemOption } from
|
|
4
|
-
interface TAddToCartButton extends Omit<Props,
|
|
1
|
+
import { type PropsWithoutRef, type JSX } from "react";
|
|
2
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
3
|
+
import type { AddToCartReturn, CustomLineItem, LineItemOption } from "../../reducers/OrderReducer";
|
|
4
|
+
interface TAddToCartButton extends Omit<Props, "children"> {
|
|
5
5
|
handleClick: () => AddToCartReturn;
|
|
6
6
|
}
|
|
7
7
|
type BuyNowMode = {
|
|
@@ -29,13 +29,13 @@ type THostedCart = {
|
|
|
29
29
|
/**
|
|
30
30
|
* If you have a self-hosted cart, you can pass the protocol to redirect to it.
|
|
31
31
|
*/
|
|
32
|
-
protocol?:
|
|
32
|
+
protocol?: "http" | "https";
|
|
33
33
|
} | {
|
|
34
34
|
redirectToHostedCart?: false;
|
|
35
35
|
hostedCartUrl?: never;
|
|
36
36
|
protocol?: never;
|
|
37
37
|
};
|
|
38
|
-
type TButton = PropsWithoutRef<Omit<JSX.IntrinsicElements[
|
|
38
|
+
type TButton = PropsWithoutRef<Omit<JSX.IntrinsicElements["button"], "children">>;
|
|
39
39
|
type Props = {
|
|
40
40
|
/**
|
|
41
41
|
* Code of a bundle
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import SkuListsContext from"../../context/SkuListsContext";import ExternalFunctionContext from"../../context/ExternalFunctionContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import{getApplicationLink}from"../../utils/getApplicationLink";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{getDomain}from"../../utils/getDomain";import{publish}from"../../utils/events";import{getOrganizationConfig}from"../../utils/organization";export function AddToCartButton(props){const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,protocol="https",...p}=props,{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=useContext(ExternalFunctionContext),{skuLists}=useContext(SkuListsContext),{sku}=useContext(SkuChildrenContext),sCode=sku?.code??skuCode,handleClick=async()=>{const qty=quantity!=null?parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=skuLists?.[skuListId]?.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return await callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=await addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=getDomain(endpoint),orderId2=res?.orderId;if(hostedCartUrl&&orderId2)location.href=`${protocol}://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`;else if(orderId2&&slug){const config=await getOrganizationConfig({accessToken,endpoint,params:{orderId:orderId2,accessToken,slug}});location.href=config?.links?.cart??getApplicationLink({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"})}}return res}else if(url)return await callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))},parentProps={handleClick,label,...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{...p,onClick:()=>{handleClick()},children:label})}export default AddToCartButton;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import SkuListsContext from"../../context/SkuListsContext";import ExternalFunctionContext from"../../context/ExternalFunctionContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import{getApplicationLink}from"../../utils/getApplicationLink";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{getDomain}from"../../utils/getDomain";import{publish}from"../../utils/events";import{getOrganizationConfig}from"../../utils/organization";export function AddToCartButton(props){const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,protocol="https",...p}=props,{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=useContext(ExternalFunctionContext),{skuLists}=useContext(SkuListsContext),{sku}=useContext(SkuChildrenContext),sCode=sku?.code??skuCode,handleClick=async()=>{const qty=quantity!=null?Number.parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=skuLists?.[skuListId]?.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return await callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=await addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=getDomain(endpoint),orderId2=res?.orderId;if(hostedCartUrl&&orderId2)location.href=`${protocol}://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`;else if(orderId2&&slug){const config=await getOrganizationConfig({accessToken,endpoint,params:{orderId:orderId2,accessToken,slug}});location.href=config?.links?.cart??getApplicationLink({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"})}}return res}else if(url)return await callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))},parentProps={handleClick,label,...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{...p,onClick:()=>{handleClick()},children:label})}export default AddToCartButton;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseAmountComponent } from
|
|
2
|
-
import type
|
|
3
|
-
export declare function GiftCardAmount(props: BaseAmountComponent): JSX.Element;
|
|
1
|
+
import type { BaseAmountComponent } from "../../typings/index";
|
|
2
|
+
import { type JSX } from "react";
|
|
3
|
+
export declare function GiftCardAmount(props: BaseAmountComponent): JSX.Element | null;
|
|
4
4
|
export default GiftCardAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";export function GiftCardAmount(props){return _jsx(BaseOrderPrice,{base:"amount",type:"gift_card",...props})}export default GiftCardAmount;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";import Parent from"../utils/Parent";export function GiftCardAmount(props){const{manageAdyenGiftCard,order}=useContext(OrderContext);if(manageAdyenGiftCard){const giftCardData=manageGiftCard({order});if(!giftCardData)return null;const parentProps={priceCents:giftCardData.currentBalanceValue,price:`-${giftCardData?.formattedBalanceValue}`,...props};return props.children?_jsx(Parent,{...parentProps,children:props.children}):_jsx("span",{...props,children:`-${giftCardData?.formattedBalanceValue}`})}return _jsx(BaseOrderPrice,{base:"amount",type:"gift_card",...props})}export default GiftCardAmount;
|