@commercelayer/react-components 4.29.0-beta.4 → 4.29.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/components/customers/CustomerContainer.js +1 -1
- package/lib/cjs/components/customers/CustomerPaymentSource.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSource.js +1 -1
- package/lib/cjs/components/payment_source/StripePayment.js +1 -1
- package/lib/cjs/context/CustomerContext.d.ts +3 -1
- package/lib/cjs/reducers/CustomerReducer.d.ts +6 -0
- package/lib/cjs/reducers/CustomerReducer.js +1 -1
- package/lib/esm/components/customers/CustomerContainer.js +1 -1
- package/lib/esm/components/customers/CustomerPaymentSource.js +1 -1
- package/lib/esm/components/payment_source/PaymentSource.js +1 -1
- package/lib/esm/components/payment_source/StripePayment.js +1 -1
- package/lib/esm/context/CustomerContext.d.ts +3 -1
- package/lib/esm/reducers/CustomerReducer.d.ts +6 -0
- package/lib/esm/reducers/CustomerReducer.js +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=CustomerContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await(0,CustomerReducer_1.setResourceTrigger)({...props2,dispatch,config}),createCustomerAddress:async address=>{await(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.default=CustomerContainer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=CustomerContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerPayment:async({customerPaymentSourceId})=>{await(0,CustomerReducer_1.deleteCustomerPayment)({customerPaymentSourceId,dispatch,config})},deleteCustomerAddress:async({customerAddressId})=>{await(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await(0,CustomerReducer_1.setResourceTrigger)({...props2,dispatch,config}),createCustomerAddress:async address=>{await(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.default=CustomerContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerPaymentSource=CustomerPaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),CustomerPaymentSourceContext_1=tslib_1.__importDefault(require("../../context/CustomerPaymentSourceContext")),
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerPaymentSource=CustomerPaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),CustomerPaymentSourceContext_1=tslib_1.__importDefault(require("../../context/CustomerPaymentSourceContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function CustomerPaymentSource({children,loader="Loading..."}){const[loading,setLoading]=(0,react_1.useState)(!0),{payments,deleteCustomerPayment}=(0,useCustomContext_1.default)({context:CustomerContext_1.default,contextComponentName:"CustomerContainer",currentComponentName:"CustomerPaymentSource",key:"payments"});(0,react_1.useEffect)(()=>(payments!=null&&setLoading(!1),()=>{setLoading(!0)}),[payments]);const provider=payments?.filter(p=>p?.payment_source!=null).map(p=>{const paymentType=p.payment_source?.type,customerPayment=p,value={...(0,getCardDetails_1.default)({paymentType,customerPayment}),handleDeleteClick:e=>{e?.preventDefault(),e?.stopPropagation(),deleteCustomerPayment?.({customerPaymentSourceId:p.id})}};return(0,jsx_runtime_1.jsx)(CustomerPaymentSourceContext_1.default.Provider,{value,children},p.id)});return loading?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:loader}):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:provider})}exports.default=CustomerPaymentSource;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentSource=PaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),PaymentGateway_1=tslib_1.__importDefault(require("../payment_gateways/PaymentGateway"));function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{payments}=(0,react_1.useContext)(CustomerContext_1.default),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),[show,setShow]=(0,react_1.useState)(!1),[showCard,setShowCard]=(0,react_1.useState)(!1);(0,react_1.useEffect)(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&¤tCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=(0,getCardDetails_1.default)({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&¤tPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return(0,jsx_runtime_1.jsx)(PaymentGateway_1.default,{...gatewayProps})}exports.default=PaymentSource;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentSource=PaymentSource;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),PaymentGateway_1=tslib_1.__importDefault(require("../payment_gateways/PaymentGateway"));function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{payments}=(0,react_1.useContext)(CustomerContext_1.default),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),[show,setShow]=(0,react_1.useState)(!1),[showCard,setShowCard]=(0,react_1.useState)(!1);(0,react_1.useEffect)(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&¤tCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=(0,getCardDetails_1.default)({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&card.brand!=="giftcard"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&¤tPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return(0,jsx_runtime_1.jsx)(PaymentGateway_1.default,{...gatewayProps})}exports.default=PaymentSource;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),localStorage_1=require("../../utils/localStorage"),StripeExpressPayment_1=require("./StripeExpressPayment"),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'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{errors,currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.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 sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.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}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,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};async function handleChange(event){if(selectedPaymentMethodType=event.value.type,
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripePayment=StripePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),localStorage_1=require("../../utils/localStorage"),StripeExpressPayment_1=require("./StripeExpressPayment"),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'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=(0,react_1.useRef)(null),{errors,currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors}=(0,react_1.useContext)(OrderContext_1.default),{sdkClient}=(0,useCommerceLayer_1.default)(),{setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),elements=(0,react_stripe_js_1.useElements)();(0,react_1.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 sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!1}const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.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}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,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};async function handleChange(event){if(selectedPaymentMethodType=event.value.type,event.complete&&(errors&&errors.length>0&&setPaymentMethodErrors([]),["apple_pay","google_pay"].includes(event.value.type))){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...p}){const[isLoaded,setIsLoaded]=(0,react_1.useState)(!1),[stripe,setStripe]=(0,react_1.useState)(null),{containerClassName,templateCustomerSaveToWallet,fonts=[],appearance,...divProps}=p;(0,react_1.useEffect)(()=>(show&&publishableKey&&Promise.resolve().then(()=>tslib_1.__importStar(require("@stripe/stripe-js"))).then(({loadStripe})=>{(async()=>{const options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);const elementsOptions={clientSecret,appearance:{...defaultAppearance,...appearance},fonts};return isLoaded&&stripe!=null&&clientSecret!=null?(0,jsx_runtime_1.jsx)("div",{className:containerClassName,...divProps,children:(0,jsx_runtime_1.jsx)(react_stripe_js_1.Elements,{stripe,options:elementsOptions,children:expressPayments?(0,jsx_runtime_1.jsx)(StripeExpressPayment_1.StripeExpressPayment,{clientSecret}):(0,jsx_runtime_1.jsx)(StripePaymentForm,{stripe,options,templateCustomerSaveToWallet})})}):null}exports.default=StripePayment;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger } from '../reducers/CustomerReducer';
|
|
1
|
+
import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger, deleteCustomerPayment } from '../reducers/CustomerReducer';
|
|
2
2
|
export type InitialCustomerContext = Partial<{
|
|
3
3
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
4
4
|
setCustomerErrors: SetCustomerErrors;
|
|
5
5
|
setCustomerEmail: typeof setCustomerEmail;
|
|
6
6
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
7
|
+
deleteCustomerPayment: typeof deleteCustomerPayment;
|
|
7
8
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
8
9
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
9
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
@@ -18,6 +19,7 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
18
19
|
setCustomerErrors: SetCustomerErrors;
|
|
19
20
|
setCustomerEmail: typeof setCustomerEmail;
|
|
20
21
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
22
|
+
deleteCustomerPayment: typeof deleteCustomerPayment;
|
|
21
23
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
22
24
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
23
25
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
@@ -155,6 +155,12 @@ export declare function createCustomerAddress({ address, config, dispatch, state
|
|
|
155
155
|
interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
|
|
156
156
|
}
|
|
157
157
|
export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
|
|
158
|
+
export interface DeleteCustomerPayment {
|
|
159
|
+
customerPaymentSourceId: string;
|
|
160
|
+
dispatch?: Dispatch<CustomerAction>;
|
|
161
|
+
config?: CommerceLayerConfig;
|
|
162
|
+
}
|
|
163
|
+
export declare function deleteCustomerPayment({ customerPaymentSourceId, dispatch, config, }: DeleteCustomerPayment): Promise<void>;
|
|
158
164
|
export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
|
|
159
165
|
export type SetResourceTriggerParams = {
|
|
160
166
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await(0,getSdk_1.default)(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=await(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),newAddress=await sdk.addresses.create(addressWithMeta);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")}}}async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if(await(0,triggerAttributeHelper_1.triggerAttributeHelper)(params)!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}}return!1}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.deleteCustomerPayment=deleteCustomerPayment,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}async function getCustomerAddresses({config,dispatch,isOrderAvailable,pageSize=10}){try{const addresses=[];(await(0,getSdk_1.default)(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=await(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),newAddress=await sdk.addresses.create(addressWithMeta);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")}}}async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}async function deleteCustomerPayment({customerPaymentSourceId,dispatch,config}){if(config&&dispatch)try{await(0,getSdk_1.default)(config).customer_payment_sources.delete(customerPaymentSourceId),getCustomerPayments({config,dispatch})}catch{throw new Error("Couldn't delete payment source")}}async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if(await(0,triggerAttributeHelper_1.triggerAttributeHelper)(params)!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}}return!1}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&getCustomerPayments({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,deleteCustomerPayment,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest,addressesPageSize:pageSize}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&getCustomerPayments({config,dispatch})}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerPayment:async({customerPaymentSourceId})=>{await deleteCustomerPayment({customerPaymentSourceId,dispatch,config})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize:pageSize2,sortBy})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize:pageSize2,sortBy})},getCustomerSubscriptions:async({pageNumber,pageSize:pageSize2,sortBy,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize:pageSize2,sortBy,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null,pageSize})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";import
|
|
2
|
+
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";import getCardDetails from"../../utils/getCardDetails";import useCustomContext from"../../utils/hooks/useCustomContext";export function CustomerPaymentSource({children,loader="Loading..."}){const[loading,setLoading]=useState(!0),{payments,deleteCustomerPayment}=useCustomContext({context:CustomerContext,contextComponentName:"CustomerContainer",currentComponentName:"CustomerPaymentSource",key:"payments"});useEffect(()=>(payments!=null&&setLoading(!1),()=>{setLoading(!0)}),[payments]);const provider=payments?.filter(p=>p?.payment_source!=null).map(p=>{const paymentType=p.payment_source?.type,value={...getCardDetails({paymentType,customerPayment:p}),handleDeleteClick:e=>{e?.preventDefault(),e?.stopPropagation(),deleteCustomerPayment?.({customerPaymentSourceId:p.id})}};return _jsx(CustomerPaymentSourceContext.Provider,{value,children},p.id)});return loading?_jsx(_Fragment,{children:loader}):_jsx(_Fragment,{children:provider})}export default CustomerPaymentSource;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import getCardDetails from"../../utils/getCardDetails";import PaymentGateway from"../payment_gateways/PaymentGateway";export function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{payments}=useContext(CustomerContext),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),[show,setShow]=useState(!1),[showCard,setShowCard]=useState(!1);useEffect(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&¤tCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=getCardDetails({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&¤tPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return _jsx(PaymentGateway,{...gatewayProps})}export default PaymentSource;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import getCardDetails from"../../utils/getCardDetails";import PaymentGateway from"../payment_gateways/PaymentGateway";export function PaymentSource(props){const{readonly}=props,{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{payments}=useContext(CustomerContext),{errors,currentPaymentMethodId,paymentSource,destroyPaymentSource,currentPaymentMethodType,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),[show,setShow]=useState(!1),[showCard,setShowCard]=useState(!1);useEffect(()=>{const isCustomerPaymentSource=currentCustomerPaymentSourceId!=null&¤tCustomerPaymentSourceId===paymentSource?.id,checkPaymentSourceStatus=paymentSource?.payment_response?.status?.toLowerCase();if(readonly)setShow(!0),setShowCard(!0);else if((payment?.id===currentPaymentMethodId||isCustomerPaymentSource)&&!expressPayments){const card=getCardDetails({paymentType:payment?.payment_source_type,customerPayment:{payment_source:paymentSource??order?.payment_source}});isCustomerPaymentSource&&card.brand===""&&(card.brand=card.issuer_type!=null&&card.issuer_type!==""?card.issuer_type:"credit-card"),card.brand&&errors?.length===0&&checkPaymentSourceStatus!=="declined"&&card.brand!=="giftcard"&&setShowCard(!0),checkPaymentSourceStatus==="declined"&&setShowCard(!1),setShow(!0)}else expressPayments&¤tPaymentMethodType==="stripe_payments"&&setShow(!0);return()=>{setShow(!1),setShowCard(!1)}},[currentPaymentMethodId,paymentSource?.id,payments!=null,payment!=null,readonly,order?.status,expressPayments,errors?.length]);const gatewayProps={...props,show,showCard,handleEditClick:async e=>{if(e.stopPropagation(),paymentSource){const paymentSourceId=paymentSource?.id;await destroyPaymentSource({paymentSourceId,paymentResource:payment?.payment_source_type})}setShowCard(!showCard),setShow(!0)},readonly};return _jsx(PaymentGateway,{...gatewayProps})}export default PaymentSource;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";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'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{errors,currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),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 sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!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}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,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};async function handleChange(event){if(selectedPaymentMethodType=event.value.type,
|
|
2
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{Elements,PaymentElement,useElements}from"@stripe/react-stripe-js";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import{setCustomerOrderParam}from"../../utils/localStorage";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'}};let selectedPaymentMethodType=null;function StripePaymentForm({options=defaultOptions,templateCustomerSaveToWallet,stripe}){const ref=useRef(null),{errors,currentPaymentMethodType,setPaymentMethodErrors,setPaymentRef}=useContext(PaymentMethodContext),{order,setOrderErrors}=useContext(OrderContext),{sdkClient}=useCommerceLayer(),{setPlaceOrderStatus}=useContext(PlaceOrderContext),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 sdk=sdkClient();if(sdk==null||order==null)return!1;if(selectedPaymentMethodType&&!["apple_pay","google_pay"].includes(selectedPaymentMethodType)){const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft")return setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"}),!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}},url=new URL(window.location.href),cleanUrl=`${url.origin}${url.pathname}?accessToken=${url.searchParams.get("accessToken")}`,{error}=await stripe2.confirmPayment({elements:elements2,confirmParams:{return_url:cleanUrl,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};async function handleChange(event){if(selectedPaymentMethodType=event.value.type,event.complete&&(errors&&errors.length>0&&setPaymentMethodErrors([]),["apple_pay","google_pay"].includes(event.value.type))){const sdk=sdkClient();if(sdk==null||order==null)return;const{status}=await sdk.orders.retrieve(order?.id,{fields:["status"]});if(status==="draft"){setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]),setPlaceOrderStatus?.({status:"disabled"});return}}}return _jsxs("form",{ref,children:[_jsx(PaymentElement,{id:"payment-element",options:{...defaultOptions,...options},onChange:handleChange}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export function StripePayment({publishableKey,show,options,clientSecret,locale="auto",expressPayments=!1,connectedAccount,...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 options2={locale,...connectedAccount?{stripeAccount:connectedAccount}:{}},res=await loadStripe(publishableKey,options2);res!=null?(setStripe(res),setIsLoaded(!0)):(console.error("Stripe failed to load"),setIsLoaded(!1))})()}),()=>{setIsLoaded(!1)}),[show,publishableKey,connectedAccount]);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,{stripe,options,templateCustomerSaveToWallet})})}):null}export default StripePayment;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger } from '../reducers/CustomerReducer';
|
|
1
|
+
import type { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses, getCustomerOrders, getCustomerSubscriptions, setResourceTrigger, deleteCustomerPayment } from '../reducers/CustomerReducer';
|
|
2
2
|
export type InitialCustomerContext = Partial<{
|
|
3
3
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
4
4
|
setCustomerErrors: SetCustomerErrors;
|
|
5
5
|
setCustomerEmail: typeof setCustomerEmail;
|
|
6
6
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
7
|
+
deleteCustomerPayment: typeof deleteCustomerPayment;
|
|
7
8
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
8
9
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
9
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
@@ -18,6 +19,7 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
18
19
|
setCustomerErrors: SetCustomerErrors;
|
|
19
20
|
setCustomerEmail: typeof setCustomerEmail;
|
|
20
21
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
22
|
+
deleteCustomerPayment: typeof deleteCustomerPayment;
|
|
21
23
|
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
22
24
|
getCustomerAddresses: typeof getCustomerAddresses;
|
|
23
25
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
@@ -155,6 +155,12 @@ export declare function createCustomerAddress({ address, config, dispatch, state
|
|
|
155
155
|
interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
|
|
156
156
|
}
|
|
157
157
|
export declare function getCustomerPayments({ config, dispatch, pageSize, pageNumber }: GetCustomerPaymentsParams): Promise<void>;
|
|
158
|
+
export interface DeleteCustomerPayment {
|
|
159
|
+
customerPaymentSourceId: string;
|
|
160
|
+
dispatch?: Dispatch<CustomerAction>;
|
|
161
|
+
config?: CommerceLayerConfig;
|
|
162
|
+
}
|
|
163
|
+
export declare function deleteCustomerPayment({ customerPaymentSourceId, dispatch, config, }: DeleteCustomerPayment): Promise<void>;
|
|
158
164
|
export declare function getCustomerInfo({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
|
|
159
165
|
export type SetResourceTriggerParams = {
|
|
160
166
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";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,pageSize=10}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),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,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},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 addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";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,pageSize=10}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"],pageSize})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),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,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},sort:sortBy??{number:"desc"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1,sortBy}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},sort:sortBy??{number:"desc"},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{sort:sortBy??{starts_at:"desc"},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 addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],sort:{updated_at:"desc"},pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function deleteCustomerPayment({customerPaymentSourceId,dispatch,config}){if(config&&dispatch)try{await getSdk(config).customer_payment_sources.delete(customerPaymentSourceId),getCustomerPayments({config,dispatch})}catch{throw new Error("Couldn't delete payment source")}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|