@commercelayer/react-components 4.4.4 → 4.5.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/components/ExternalFunction.js +1 -1
- package/lib/cjs/components/addresses/Address.js +1 -1
- package/lib/cjs/components/addresses/AddressField.js +1 -1
- package/lib/cjs/components/addresses/AddressesContainer.js +1 -1
- package/lib/cjs/components/addresses/BillingAddressContainer.js +1 -1
- package/lib/cjs/components/addresses/BillingAddressForm.js +1 -1
- package/lib/cjs/components/addresses/ShippingAddressContainer.js +1 -1
- package/lib/cjs/components/addresses/ShippingAddressForm.js +1 -1
- package/lib/cjs/components/auth/CommerceLayer.js +1 -1
- package/lib/cjs/components/customers/CustomerAddressForm.js +1 -1
- package/lib/cjs/components/customers/CustomerContainer.js +1 -1
- package/lib/cjs/components/customers/CustomerPaymentSource.js +1 -1
- package/lib/cjs/components/gift_cards/GiftCard.js +1 -1
- package/lib/cjs/components/gift_cards/GiftCardContainer.js +1 -1
- package/lib/cjs/components/gift_cards/GiftCardOrCouponForm.js +1 -1
- package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionsContainer.js +1 -1
- package/lib/cjs/components/line_items/LineItem.js +1 -1
- package/lib/cjs/components/line_items/LineItemOption.js +1 -1
- package/lib/cjs/components/line_items/LineItemOptions.js +1 -1
- package/lib/cjs/components/line_items/LineItemQuantity.js +1 -1
- package/lib/cjs/components/line_items/LineItemRemoveLink.js +1 -1
- package/lib/cjs/components/line_items/LineItemsContainer.js +1 -1
- package/lib/cjs/components/orders/AddToCartButton.js +1 -1
- package/lib/cjs/components/orders/CartLink.js +1 -1
- package/lib/cjs/components/orders/OrderContainer.js +1 -1
- package/lib/cjs/components/orders/OrderList.d.ts +20 -38
- package/lib/cjs/components/orders/OrderList.js +1 -1
- package/lib/cjs/components/orders/OrderListPaginationButtons.js +1 -1
- package/lib/cjs/components/orders/OrderListPaginationInfo.js +1 -1
- package/lib/cjs/components/orders/OrderListRow.d.ts +6 -14
- package/lib/cjs/components/orders/OrderListRow.js +1 -1
- package/lib/cjs/components/orders/OrderStorage.js +1 -1
- package/lib/cjs/components/orders/PlaceOrderContainer.js +1 -1
- package/lib/cjs/components/parcels/ParcelLineItem.js +1 -1
- package/lib/cjs/components/parcels/Parcels.js +1 -1
- package/lib/cjs/components/payment_gateways/AdyenGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/BraintreeGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/CheckoutComGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/ExternalGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/KlarnaGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/PaypalGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/StripeGateway.js +1 -1
- package/lib/cjs/components/payment_gateways/WireTransferGateway.js +1 -1
- package/lib/cjs/components/payment_methods/PaymentMethod.js +1 -1
- package/lib/cjs/components/payment_methods/PaymentMethodsContainer.js +1 -1
- package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
- package/lib/cjs/components/payment_source/BraintreePayment.js +1 -1
- package/lib/cjs/components/payment_source/CheckoutComPayment.js +1 -1
- package/lib/cjs/components/payment_source/ExternalPayment.js +1 -1
- package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceEditButton.js +1 -1
- package/lib/cjs/components/payment_source/PaypalPayment.js +1 -1
- package/lib/cjs/components/payment_source/StripePayment.js +1 -1
- package/lib/cjs/components/payment_source/WireTransferPayment.js +1 -1
- package/lib/cjs/components/prices/PricesContainer.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/shipping_methods/ShippingMethod.js +1 -1
- package/lib/cjs/components/skus/AvailabilityContainer.js +1 -1
- package/lib/cjs/components/skus/SkuListsContainer.js +1 -1
- package/lib/cjs/components/skus/Skus.js +1 -1
- package/lib/cjs/components/skus/SkusContainer.js +1 -1
- package/lib/cjs/components/stock_transfers/StockTransfer.js +1 -1
- package/lib/cjs/context/CustomerContext.d.ts +5 -1
- package/lib/cjs/context/OrderListChildrenContext.d.ts +15 -10
- package/lib/cjs/context/OrderListPaginationContext.d.ts +0 -3
- package/lib/cjs/reducers/CustomerReducer.d.ts +15 -4
- package/lib/cjs/reducers/CustomerReducer.js +1 -1
- package/lib/cjs/reducers/OrderReducer.d.ts +1 -0
- package/lib/cjs/reducers/OrderReducer.js +1 -1
- package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
- package/lib/cjs/typings/globals.d.ts +3 -0
- package/lib/cjs/utils/filterChildren.d.ts +3 -0
- package/lib/cjs/utils/hasSubscriptions.d.ts +7 -0
- package/lib/cjs/utils/hasSubscriptions.js +1 -0
- package/lib/cjs/utils/icons.js +1 -1
- package/lib/esm/components/customers/CustomerContainer.js +1 -1
- package/lib/esm/components/orders/OrderContainer.js +1 -1
- package/lib/esm/components/orders/OrderList.d.ts +20 -38
- package/lib/esm/components/orders/OrderList.js +1 -1
- package/lib/esm/components/orders/OrderListPaginationButtons.js +1 -1
- package/lib/esm/components/orders/OrderListPaginationInfo.js +1 -1
- package/lib/esm/components/orders/OrderListRow.d.ts +6 -14
- package/lib/esm/components/orders/OrderListRow.js +1 -1
- package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
- package/lib/esm/components/payment_source/StripePayment.js +1 -1
- package/lib/esm/context/CustomerContext.d.ts +5 -1
- package/lib/esm/context/OrderListChildrenContext.d.ts +15 -10
- package/lib/esm/context/OrderListPaginationContext.d.ts +0 -3
- package/lib/esm/reducers/CustomerReducer.d.ts +15 -4
- package/lib/esm/reducers/CustomerReducer.js +1 -1
- package/lib/esm/reducers/OrderReducer.d.ts +1 -0
- package/lib/esm/reducers/OrderReducer.js +1 -1
- package/lib/esm/reducers/PlaceOrderReducer.js +1 -1
- package/lib/esm/typings/globals.d.ts +3 -0
- package/lib/esm/utils/filterChildren.d.ts +3 -0
- package/lib/esm/utils/hasSubscriptions.d.ts +7 -0
- package/lib/esm/utils/hasSubscriptions.js +1 -0
- package/package.json +19 -21
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import Parent from"../utils/Parent";import getBrowserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import omit from"../../utils/omit";const threeDSConfiguration={challengeWindowSize:"05"},defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,threeDSecureContainerClassName,styles}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(
|
|
1
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import Parent from"../utils/Parent";import getBrowserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import omit from"../../utils/omit";const threeDSConfiguration={challengeWindowSize:"05"},defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,threeDSecureContainerClassName,styles}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),{placeOrderButtonRef}=useContext(PlaceOrderContext),ref=useRef(null),handleSubmit=async(e,component)=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),component?.submit&&component.submit(),!1},handleChange=async(state,_component)=>{if(state.isValid){ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current,checkout),setPaymentRef({ref}));const browserInfo=getBrowserInfo(),attributes={payment_request_data:{payment_method:state.data.paymentMethod,shopperInteraction:"Ecommerce",recurringProcessingModel:"CardOnFile",origin:window.location.origin,return_url:window.location.href,redirect_from_issuer_method:"GET",browser_info:{acceptHeader:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",...browserInfo}}};paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes})}},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),adyenAction=pSource?.payment_response?.action,resultCode=pSource?.payment_response?.resultCode;if(adyenAction&&component)return component.handleAction(adyenAction),!1;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),!0;if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return!1}catch(error){return console.error("Adyen additional details error:",error),!1}},onSubmit=async(state,component)=>{const browserInfo=getBrowserInfo(),saveCustomer=document.getElementById("save_payment_source_to_customer_wallet"),url=cleanUrlBy();let control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"});if(control?.payment_response?.resultCode==="Authorised")return!0;const paymentDataAvailable=Object.keys(control?.payment_request_data).length>0,paymentMethodSelected=control?.payment_request_data?.payment_method?.type,paymentMethod=saveCustomer?.checked?state.data.paymentMethod:omit(state.data.paymentMethod,["encryptedCardNumber","encryptedExpiryMonth","encryptedExpiryYear","encryptedSecurityCode"]);(!paymentDataAvailable||paymentMethodSelected!==state.data.paymentMethod.type)&&(control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:{...state.data,payment_method:paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",browser_info:{acceptHeader:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",...browserInfo}}}}));const attributes={payment_request_data:{...state.data,payment_method:paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",browser_info:{acceptHeader:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",...browserInfo}},_authorize:1};delete attributes.payment_request_data.paymentMethod;try{const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),action=res?.payment_response?.action;if(component&&action)return component.handleAction(action),!1;const resultCode=res?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),!0;if(["Cancelled"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])}return!1}catch(error){return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}};return useEffect(()=>{const paymentMethodsResponse=paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],[firstPaymentMethod]=paymentMethodsResponse,isOnlyCard=paymentMethodsResponse?.length===1&&firstPaymentMethod.type==="scheme";paymentMethodsResponse.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const options={locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse:{paymentMethods:paymentMethodsResponse},showPayButton:!1,paymentMethodsConfiguration:{threeDS2:threeDSConfiguration,paypal:{showPayButton:!0,style:styles?.paypal},card:{styles:styles?.card,holderNameRequired:!1}},onAdditionalDetails:(state,element)=>{handleOnAdditionalDetails(state,element)},onChange:(state,element)=>{handleChange(state,element)},onSubmit:(state,element)=>{onSubmit(state,element)}};return!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout&&import("@adyen/adyen-web").then(({default:AdyenCheckout})=>{const type=isOnlyCard?"card":"dropin";AdyenCheckout(options).then(adyenCheckout=>{const component=adyenCheckout.create(type,{onSelect:component2=>{const id=component2._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current,component2):ref.current.onsubmit=null,setPaymentRef({ref}))}}).mount("#adyen-dropin");component&&(setCheckout(component),setLoadAdyen(!0))})}),()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e,checkout)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet}),_jsx("div",{className:threeDSecureContainerClassName,id:"adyen-action"})]})}export default AdyenPayment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Elements,PaymentElement,useElements,useStripe}from"@stripe/react-stripe-js";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import OrderContext from"../../context/OrderContext";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),stripe=useStripe(),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:window.location.href,payment_method_data:{billing_details:billingDetails}}});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1):!0}return!1};return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options}}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const res=await loadStripe(publishableKey,{locale});res!=null&&(setStripe(res),setIsLoaded(!0))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
|
|
1
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Elements,PaymentElement,useElements,useStripe}from"@stripe/react-stripe-js";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import OrderContext from"../../context/OrderContext";import{StripeExpressPayment}from"./StripeExpressPayment";const defaultOptions={layout:{type:"accordion",defaultCollapsed:!1,radios:!0,spacedAccordionItems:!1},fields:{billingDetails:"never"}},defaultAppearance={theme:"stripe",variables:{colorText:"#32325d",fontFamily:'"Helvetica Neue", Helvetica, sans-serif'}};function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet}){const ref=useRef(null),{currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),stripe=useStripe(),elements=useElements();useEffect(()=>(ref.current&&stripe&&elements&&(ref.current.onsubmit=async()=>await onSubmit({event:ref.current,stripe,elements}),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,stripe,elements]);const onSubmit=async({event,stripe:stripe2,elements:elements2})=>{if(!stripe2)return!1;const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),elements2!=null){const billingInfo=order?.billing_address,email=order?.customer_email??"",billingDetails={name:billingInfo?.full_name??"",email,phone:billingInfo?.phone,address:{city:billingInfo?.city,country:billingInfo?.country_code,line1:billingInfo?.line_1,line2:billingInfo?.line_2??"",postal_code:billingInfo?.zip_code??"",state:billingInfo?.state_code}},{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:window.location.href,payment_method_data:{billing_details:billingDetails}},redirect:"if_required"});return error?(console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1):!0}return!1};return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options}}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,...p}){const[isLoaded,setIsLoaded]=useState(!1),[stripe,setStripe]=useState(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;useEffect(()=>(show&&publishableKey&&import("@stripe/stripe-js").then(({loadStripe})=>{(async()=>{const res=await loadStripe(publishableKey,{locale});res!=null&&(setStripe(res),setIsLoaded(!0))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?_jsx("div",{className:containerClassName,...divProps,children:_jsx(Elements,{stripe,options:elementsOptions,children:expressPayments?_jsx(StripeExpressPayment,{clientSecret}):_jsx(StripePaymentForm,{options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses } from '../reducers/CustomerReducer';
|
|
2
|
+
import { type SetCustomerErrors, type deleteCustomerAddress, type CustomerState, type getCustomerPaymentSources, type setCustomerEmail, type TCustomerAddress, type getCustomerAddresses, type getCustomerOrders, type getCustomerSubscriptions } from '../reducers/CustomerReducer';
|
|
3
3
|
export type InitialCustomerContext = Partial<{
|
|
4
4
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
5
5
|
setCustomerErrors: SetCustomerErrors;
|
|
@@ -8,6 +8,8 @@ export type InitialCustomerContext = Partial<{
|
|
|
8
8
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
9
9
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
10
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
11
|
+
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
12
|
+
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
11
13
|
} & CustomerState>;
|
|
12
14
|
export declare const defaultCustomerContext: {};
|
|
13
15
|
declare const CustomerContext: import("react").Context<Partial<{
|
|
@@ -18,5 +20,7 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
18
20
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
19
21
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
20
22
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
23
|
+
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
24
|
+
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
21
25
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
22
26
|
export default CustomerContext;
|
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import type { Order } from '@commercelayer/sdk';
|
|
3
|
-
import { type Row } from 'react-table';
|
|
2
|
+
import type { Order, OrderSubscription } from '@commercelayer/sdk';
|
|
3
|
+
import { type Row } from '@tanstack/react-table';
|
|
4
|
+
export type TOrderList = 'orders' | 'subscriptions';
|
|
5
|
+
export type TableAccessor<T extends TOrderList> = T extends 'orders' ? keyof Order : keyof OrderSubscription;
|
|
6
|
+
export type OrderListContent<T extends TOrderList> = T extends 'orders' ? Order : OrderSubscription;
|
|
4
7
|
export type InitialOrderListContext = Partial<{
|
|
8
|
+
type: TOrderList;
|
|
5
9
|
/**
|
|
6
10
|
* The current order
|
|
7
11
|
*/
|
|
8
|
-
order:
|
|
12
|
+
order: OrderListContent<TOrderList> | null;
|
|
9
13
|
/**
|
|
10
14
|
* The list of orders
|
|
11
15
|
*/
|
|
12
|
-
orders:
|
|
16
|
+
orders: Array<OrderListContent<TOrderList>> | null | undefined;
|
|
13
17
|
/**
|
|
14
18
|
* The current row
|
|
15
19
|
*/
|
|
16
|
-
row: Row<
|
|
20
|
+
row: Row<OrderListContent<TOrderList>>;
|
|
17
21
|
/**
|
|
18
22
|
* Show the row actions
|
|
19
23
|
*/
|
|
@@ -22,7 +26,7 @@ export type InitialOrderListContext = Partial<{
|
|
|
22
26
|
* Function to assign as custom row renderer
|
|
23
27
|
*/
|
|
24
28
|
actionsComponent: (props: {
|
|
25
|
-
order:
|
|
29
|
+
order: OrderListContent<TOrderList>;
|
|
26
30
|
}) => JSX.Element;
|
|
27
31
|
/**
|
|
28
32
|
* Class name to assign as custom row renderer
|
|
@@ -34,18 +38,19 @@ export type InitialOrderListContext = Partial<{
|
|
|
34
38
|
infiniteScroll: boolean;
|
|
35
39
|
}>;
|
|
36
40
|
declare const OrderListChildrenContext: import("react").Context<Partial<{
|
|
41
|
+
type: TOrderList;
|
|
37
42
|
/**
|
|
38
43
|
* The current order
|
|
39
44
|
*/
|
|
40
|
-
order:
|
|
45
|
+
order: OrderListContent<TOrderList> | null;
|
|
41
46
|
/**
|
|
42
47
|
* The list of orders
|
|
43
48
|
*/
|
|
44
|
-
orders:
|
|
49
|
+
orders: Array<OrderListContent<TOrderList>> | null | undefined;
|
|
45
50
|
/**
|
|
46
51
|
* The current row
|
|
47
52
|
*/
|
|
48
|
-
row: Row<
|
|
53
|
+
row: Row<OrderListContent<TOrderList>>;
|
|
49
54
|
/**
|
|
50
55
|
* Show the row actions
|
|
51
56
|
*/
|
|
@@ -54,7 +59,7 @@ declare const OrderListChildrenContext: import("react").Context<Partial<{
|
|
|
54
59
|
* Function to assign as custom row renderer
|
|
55
60
|
*/
|
|
56
61
|
actionsComponent: (props: {
|
|
57
|
-
order:
|
|
62
|
+
order: OrderListContent<TOrderList>;
|
|
58
63
|
}) => JSX.Element;
|
|
59
64
|
/**
|
|
60
65
|
* Class name to assign as custom row renderer
|
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { type Row } from 'react-table';
|
|
3
2
|
export interface OrderListPaginationContext {
|
|
4
3
|
canNextPage: boolean;
|
|
5
4
|
canPreviousPage: boolean;
|
|
6
5
|
gotoPage: (page: number) => void;
|
|
7
6
|
nextPage: () => void;
|
|
8
|
-
page: Row[];
|
|
9
7
|
pageCount: number;
|
|
10
8
|
pageIndex: number;
|
|
11
|
-
pageNumber: number;
|
|
12
9
|
pageOptions: number[];
|
|
13
10
|
pageSize: number;
|
|
14
11
|
previousPage: () => void;
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { type Dispatch } from 'react';
|
|
2
2
|
import { type BaseError } from '../typings/errors';
|
|
3
|
-
import type { Address, AddressCreate, AddressUpdate, Customer, CustomerPaymentSource, Order } from '@commercelayer/sdk';
|
|
3
|
+
import type { Address, AddressCreate, AddressUpdate, Customer, CustomerPaymentSource, Order, OrderSubscription } from '@commercelayer/sdk';
|
|
4
4
|
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
5
5
|
import { type updateOrder } from './OrderReducer';
|
|
6
|
-
|
|
6
|
+
import { type ListResponse } from '@commercelayer/sdk/lib/cjs/resource';
|
|
7
|
+
export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders' | 'setSubscriptions';
|
|
7
8
|
export interface CustomerActionPayload {
|
|
8
9
|
addresses: Address[] | null;
|
|
9
10
|
payments: CustomerPaymentSource[] | null;
|
|
10
11
|
customerEmail: string;
|
|
11
12
|
errors: BaseError[];
|
|
12
|
-
orders: Order
|
|
13
|
+
orders: ListResponse<Order>;
|
|
14
|
+
subscriptions: ListResponse<OrderSubscription> | null;
|
|
13
15
|
isGuest: boolean;
|
|
14
16
|
customers: Customer;
|
|
15
17
|
}
|
|
@@ -106,8 +108,17 @@ interface GetCustomerOrdersProps {
|
|
|
106
108
|
* The Customer dispatch function
|
|
107
109
|
*/
|
|
108
110
|
dispatch: Dispatch<CustomerAction>;
|
|
111
|
+
/**
|
|
112
|
+
* The page size
|
|
113
|
+
*/
|
|
114
|
+
pageSize?: number;
|
|
115
|
+
/**
|
|
116
|
+
* The page number
|
|
117
|
+
*/
|
|
118
|
+
pageNumber?: number;
|
|
109
119
|
}
|
|
110
|
-
export declare function getCustomerOrders({ config, dispatch }: GetCustomerOrdersProps): Promise<void>;
|
|
120
|
+
export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
|
|
121
|
+
export declare function getCustomerSubscriptions({ config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
|
|
111
122
|
export type TCustomerAddress = AddressCreate & AddressUpdate;
|
|
112
123
|
interface TCreateCustomerAddress {
|
|
113
124
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const
|
|
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,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const subscriptions=await getSdk(config).customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch}){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","setSubscriptions"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
@@ -84,6 +84,7 @@ export interface CustomLineItem {
|
|
|
84
84
|
name?: string;
|
|
85
85
|
imageUrl?: string | null;
|
|
86
86
|
metadata?: Record<string, string>;
|
|
87
|
+
frequency?: 'hourly' | 'daily' | 'weekly' | 'monthly' | 'two-month' | 'three-month' | 'four-month' | 'six-month' | 'yearly';
|
|
87
88
|
}
|
|
88
89
|
export type AddToCartParams = Partial<{
|
|
89
90
|
bundleCode: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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,resource:"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,resource:"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,resource:"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,resource:"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,resource:"orders",field: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,resource:"orders",field: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,resource:"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,resource:"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,resource:"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,frequency=lineItem?.frequency;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,frequency},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,resource:"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,resource:"orders",field: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,resource:"orders",field: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 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include}){const response={placed:!1};if(state&&config&&order){const sdk=getSdk(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};switch(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType){case"braintree_payments":{saveToWallet()&&await sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0});const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),saveToWallet()&&await sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}),setOrderErrors&&setOrderErrors([]),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}const type=["setErrors","setPlaceOrderPermitted","setButtonRef"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{hasSubscriptions}from"../utils/hasSubscriptions";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include}){const response={placed:!1};if(state&&config&&order){const sdk=getSdk(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};switch(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType){case"braintree_payments":{saveToWallet()&&await sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0});const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),hasSubscriptions(orderUpdated)&&await sdk.orders.update({id:order.id,_create_subscriptions:!0}),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),saveToWallet()&&await sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}),setOrderErrors&&setOrderErrors([]),hasSubscriptions(orderUpdated)&&await sdk.orders.update({id:order.id,_create_subscriptions:!0}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}const type=["setErrors","setPlaceOrderPermitted","setButtonRef"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
|
|
@@ -1 +1,4 @@
|
|
|
1
1
|
export type DefaultChildrenType = JSX.Element[] | JSX.Element | null;
|
|
2
|
+
type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N ? Acc[number] : Enumerate<N, [...Acc, Acc['length']]>;
|
|
3
|
+
export type TRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
|
|
4
|
+
export {};
|
|
@@ -4,5 +4,8 @@ interface Props<T> {
|
|
|
4
4
|
filterBy: T[];
|
|
5
5
|
componentName: string;
|
|
6
6
|
}
|
|
7
|
+
/**
|
|
8
|
+
* Filter children by component display name
|
|
9
|
+
*/
|
|
7
10
|
export default function filterChildren<T = string>({ children, filterBy, componentName }: Props<T>): JSX.Element | JSX.Element[] | null;
|
|
8
11
|
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function hasSubscriptions(order){return order?.line_items?.some(li=>li.frequency!=null)!=null}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commercelayer/react-components",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.5.0-beta.0",
|
|
4
4
|
"description": "The Official Commerce Layer React Components",
|
|
5
5
|
"main": "lib/cjs/index.js",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -167,47 +167,45 @@
|
|
|
167
167
|
"dependencies": {
|
|
168
168
|
"@ac-dev/countries-service": "^1.2.0",
|
|
169
169
|
"@ac-dev/states-service": "^1.1.1",
|
|
170
|
-
"@adyen/adyen-web": "^5.
|
|
171
|
-
"@commercelayer/sdk": "^5.
|
|
170
|
+
"@adyen/adyen-web": "^5.44.0",
|
|
171
|
+
"@commercelayer/sdk": "^5.4.1",
|
|
172
172
|
"@stripe/react-stripe-js": "^2.1.0",
|
|
173
|
-
"@stripe/stripe-js": "^1.
|
|
173
|
+
"@stripe/stripe-js": "^1.54.0",
|
|
174
|
+
"@tanstack/react-table": "^8.9.2",
|
|
174
175
|
"axios": "^1.4.0",
|
|
175
176
|
"braintree-web": "^3.94.0",
|
|
176
177
|
"frames-react": "^1.1.0",
|
|
177
178
|
"jwt-decode": "^3.1.2",
|
|
178
179
|
"lodash": "^4.17.21",
|
|
179
|
-
"rapid-form": "^2.1.0"
|
|
180
|
-
"react-table": "^7.8.0",
|
|
181
|
-
"react-window": "^1.8.9"
|
|
180
|
+
"rapid-form": "^2.1.0"
|
|
182
181
|
},
|
|
183
182
|
"devDependencies": {
|
|
184
|
-
"@commercelayer/js-auth": "^4.
|
|
185
|
-
"@faker-js/faker": "^8.0.
|
|
186
|
-
"@playwright/test": "^1.
|
|
183
|
+
"@commercelayer/js-auth": "^4.1.1",
|
|
184
|
+
"@faker-js/faker": "^8.0.2",
|
|
185
|
+
"@playwright/test": "^1.35.0",
|
|
187
186
|
"@testing-library/dom": "^9.3.0",
|
|
188
187
|
"@testing-library/react": "^14.0.0",
|
|
189
188
|
"@types/braintree-web": "^3.75.23",
|
|
190
|
-
"@types/lodash": "^4.14.
|
|
191
|
-
"@types/node": "^20.
|
|
189
|
+
"@types/lodash": "^4.14.195",
|
|
190
|
+
"@types/node": "^20.3.0",
|
|
192
191
|
"@types/prop-types": "^15.7.5",
|
|
193
|
-
"@types/react": "^18.2.
|
|
194
|
-
"@types/react-table": "^7.7.14",
|
|
192
|
+
"@types/react": "^18.2.11",
|
|
195
193
|
"@types/react-test-renderer": "^18.0.0",
|
|
196
194
|
"@types/react-window": "^1.8.5",
|
|
197
195
|
"@vitejs/plugin-react": "^4.0.0",
|
|
198
|
-
"@vitest/coverage-c8": "^0.
|
|
199
|
-
"jsdom": "^22.
|
|
196
|
+
"@vitest/coverage-c8": "^0.32.0",
|
|
197
|
+
"jsdom": "^22.1.0",
|
|
200
198
|
"minimize-js": "^1.3.1",
|
|
201
|
-
"msw": "^1.2.
|
|
199
|
+
"msw": "^1.2.2",
|
|
202
200
|
"react": "^18.2.0",
|
|
203
201
|
"react-dom": "^18.2.0",
|
|
204
202
|
"react-test-renderer": "^18.2.0",
|
|
205
203
|
"tsc-alias": "^1.8.6",
|
|
206
|
-
"tslib": "^2.5.
|
|
207
|
-
"typescript": "^5.
|
|
208
|
-
"vite": "^4.3.
|
|
204
|
+
"tslib": "^2.5.3",
|
|
205
|
+
"typescript": "^5.1.3",
|
|
206
|
+
"vite": "^4.3.9",
|
|
209
207
|
"vite-tsconfig-paths": "^4.2.0",
|
|
210
|
-
"vitest": "^0.
|
|
208
|
+
"vitest": "^0.32.0"
|
|
211
209
|
},
|
|
212
210
|
"peerDependencies": {
|
|
213
211
|
"react": "^18.0.0"
|