@commercelayer/react-components 4.13.6 → 4.14.1
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/addresses/AddressStateSelector.js +1 -1
- package/lib/cjs/components/customers/CustomerContainer.js +1 -1
- package/lib/cjs/components/customers/MyIdentityLink.d.ts +4 -0
- package/lib/cjs/components/customers/MyIdentityLink.js +1 -1
- package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
- package/lib/cjs/context/CustomerContext.d.ts +2 -0
- package/lib/cjs/hooks/useCustomerContainer.d.ts +2 -1
- package/lib/cjs/hooks/useCustomerContainer.js +1 -1
- package/lib/cjs/reducers/OrderReducer.d.ts +1 -0
- package/lib/cjs/reducers/OrderReducer.js +1 -1
- package/lib/cjs/reducers/PaymentMethodReducer.js +1 -1
- package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
- package/lib/cjs/utils/getApplicationLink.d.ts +4 -1
- package/lib/cjs/utils/getApplicationLink.js +1 -1
- package/lib/cjs/utils/validateFormFields.js +1 -1
- package/lib/esm/components/addresses/AddressStateSelector.js +1 -1
- package/lib/esm/components/customers/CustomerContainer.js +1 -1
- package/lib/esm/components/customers/MyIdentityLink.d.ts +4 -0
- package/lib/esm/components/customers/MyIdentityLink.js +1 -1
- package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
- package/lib/esm/context/CustomerContext.d.ts +2 -0
- package/lib/esm/hooks/useCustomerContainer.d.ts +2 -1
- package/lib/esm/hooks/useCustomerContainer.js +1 -1
- package/lib/esm/reducers/OrderReducer.d.ts +1 -0
- package/lib/esm/reducers/OrderReducer.js +1 -1
- package/lib/esm/reducers/PaymentMethodReducer.js +1 -1
- package/lib/esm/reducers/PlaceOrderReducer.js +1 -1
- package/lib/esm/utils/getApplicationLink.d.ts +4 -1
- package/lib/esm/utils/getApplicationLink.js +1 -1
- package/lib/esm/utils/validateFormFields.js +1 -1
- package/package.json +23 -23
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddressStateSelector=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),BaseSelect_1=tslib_1.__importDefault(require("../utils/BaseSelect")),BillingAddressFormContext_1=tslib_1.__importDefault(require("../../context/BillingAddressFormContext")),ShippingAddressFormContext_1=tslib_1.__importDefault(require("../../context/ShippingAddressFormContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),countryStateCity_1=require("../../utils/countryStateCity"),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),BaseInput_1=tslib_1.__importDefault(require("../utils/BaseInput")),CustomerAddressFormContext_1=tslib_1.__importDefault(require("../../context/CustomerAddressFormContext"));function AddressStateSelector(props){var _a,_b,_c;const{required=!
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddressStateSelector=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),BaseSelect_1=tslib_1.__importDefault(require("../utils/BaseSelect")),BillingAddressFormContext_1=tslib_1.__importDefault(require("../../context/BillingAddressFormContext")),ShippingAddressFormContext_1=tslib_1.__importDefault(require("../../context/ShippingAddressFormContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),countryStateCity_1=require("../../utils/countryStateCity"),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),BaseInput_1=tslib_1.__importDefault(require("../utils/BaseInput")),CustomerAddressFormContext_1=tslib_1.__importDefault(require("../../context/CustomerAddressFormContext"));function AddressStateSelector(props){var _a,_b,_c;const{required=!1,value,name,className="",inputClassName="",selectClassName="",states}=props,p=tslib_1.__rest(props,["required","value","name","className","inputClassName","selectClassName","states"]),billingAddress=(0,react_1.useContext)(BillingAddressFormContext_1.default),shippingAddress=(0,react_1.useContext)(ShippingAddressFormContext_1.default),customerAddress=(0,react_1.useContext)(CustomerAddressFormContext_1.default),{errors:addressErrors}=(0,react_1.useContext)(AddressContext_1.default),[hasError,setHasError]=(0,react_1.useState)(!1),[countryCode,setCountryCode]=(0,react_1.useState)(""),[val,setVal]=(0,react_1.useState)(value??""),stateOptions=(0,react_1.useMemo)(()=>(0,isEmpty_1.default)(countryCode)?[]:(0,countryStateCity_1.getStateOfCountry)({countryCode,states}),[states,countryCode]),isEmptyStates=(0,react_1.useMemo)(()=>()=>(0,isEmpty_1.default)(stateOptions),[stateOptions]);(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p;const billingCountryCode=typeof((_a2=billingAddress?.values)===null||_a2===void 0?void 0:_a2.billing_address_country_code)=="string"?(_b2=billingAddress?.values)===null||_b2===void 0?void 0:_b2.billing_address_country_code:(_d=(_c2=billingAddress?.values)===null||_c2===void 0?void 0:_c2.billing_address_country_code)===null||_d===void 0?void 0:_d.value;billingCountryCode&&billingCountryCode!==countryCode&&setCountryCode(billingCountryCode);const shippingCountryCode=typeof((_e=shippingAddress?.values)===null||_e===void 0?void 0:_e.shipping_address_country_code)=="string"?(_f=shippingAddress?.values)===null||_f===void 0?void 0:_f.shipping_address_country_code:(_h=(_g=shippingAddress?.values)===null||_g===void 0?void 0:_g.shipping_address_country_code)===null||_h===void 0?void 0:_h.value;shippingCountryCode&&shippingCountryCode!==countryCode&&setCountryCode(shippingCountryCode);const changeBillingCountry=[Object.keys(billingAddress).length>0,billingCountryCode,countryCode!==billingCountryCode].every(Boolean);!changeBillingCountry&&value!=null&&value!==""&&value!==val&&(billingAddress.setValue!=null&&billingAddress?.setValue(name,value),setVal(value)),changeBillingCountry&&billingCountryCode&&!(0,countryStateCity_1.isValidState)({stateCode:val??"",countryCode:billingCountryCode,states})&&!isEmptyStates()&&(billingAddress.resetField&&billingAddress?.resetField(name),setVal(""));const changeShippingCountry=[!(0,isEmpty_1.default)(shippingAddress),shippingCountryCode,countryCode!==shippingCountryCode].every(Boolean);if(!changeShippingCountry&&value!=null&&value!==""&&value!==val&&(shippingAddress.setValue!=null&&shippingAddress?.setValue(name,value),setVal(value)),changeShippingCountry&&shippingCountryCode&&!(0,countryStateCity_1.isValidState)({stateCode:val??"",countryCode:shippingCountryCode,states})&&!isEmptyStates()&&(shippingAddress.resetField&&shippingAddress?.resetField(name),setVal("")),!(0,isEmpty_1.default)(billingAddress)){const fieldError=(_k=(_j=billingAddress?.errors)===null||_j===void 0?void 0:_j[name])===null||_k===void 0?void 0:_k.error;setHasError(!!fieldError)}if(!(0,isEmpty_1.default)(customerAddress)){const fieldError=(_m=(_l=customerAddress?.errors)===null||_l===void 0?void 0:_l[name])===null||_m===void 0?void 0:_m.error;setHasError(!!fieldError)}if(!(0,isEmpty_1.default)(shippingAddress)){const fieldError=(_p=(_o=shippingAddress?.errors)===null||_o===void 0?void 0:_o[name])===null||_p===void 0?void 0:_p.error;setHasError(!!fieldError)}return()=>{setHasError(!1)}},[value,(_a=billingAddress?.values)===null||_a===void 0?void 0:_a.billing_address_country_code,(_b=shippingAddress?.values)===null||_b===void 0?void 0:_b.shipping_address_country_code,addressErrors,customerAddress]);const errorClassName=billingAddress?.errorClassName||shippingAddress?.errorClassName||customerAddress?.errorClassName||"",classNameComputed=isEmptyStates()?`${className} ${inputClassName} ${hasError?errorClassName:""}`:`${className} ${selectClassName} ${hasError?errorClassName:""}`;return isEmptyStates()?(0,jsx_runtime_1.jsx)(BaseInput_1.default,Object.assign({},p,{name,ref:billingAddress?.validation||shippingAddress?.validation||customerAddress?.validation,className:classNameComputed,required,placeholder:((_c=p.placeholder)===null||_c===void 0?void 0:_c.label)||"",defaultValue:val,type:"text"})):(0,jsx_runtime_1.jsx)(BaseSelect_1.default,Object.assign({},p,{className:classNameComputed,ref:billingAddress?.validation||shippingAddress?.validation||customerAddress?.validation,required,options:stateOptions,name,value:val}))}exports.AddressStateSelector=AddressStateSelector,exports.default=AddressStateSelector;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({customerAddressId}){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:_b=>tslib_1.__awaiter(this,[_b],void 0,function*({pageNumber,pageSize}){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize})}),getCustomerSubscriptions:_c=>tslib_1.__awaiter(this,[_c],void 0,function*({pageNumber,pageSize,id}){yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize,id})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.CustomerContainer=CustomerContainer,exports.default=CustomerContainer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:_a=>tslib_1.__awaiter(this,[_a],void 0,function*({customerAddressId}){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:_b=>tslib_1.__awaiter(this,[_b],void 0,function*({pageNumber,pageSize}){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize})}),getCustomerSubscriptions:_c=>tslib_1.__awaiter(this,[_c],void 0,function*({pageNumber,pageSize,id}){yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize,id})}),reloadCustomerAddresses:()=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.CustomerContainer=CustomerContainer,exports.default=CustomerContainer;
|
|
@@ -34,6 +34,10 @@ interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
|
|
|
34
34
|
* The domain of your forked application
|
|
35
35
|
*/
|
|
36
36
|
customDomain?: string;
|
|
37
|
+
/**
|
|
38
|
+
* The reset password url
|
|
39
|
+
*/
|
|
40
|
+
resetPasswordUrl?: string;
|
|
37
41
|
}
|
|
38
42
|
/**
|
|
39
43
|
* This component generates a link to the hosted mfe-identity application.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MyIdentityLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain"),organization_1=require("../../utils/organization");function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain}=props,p=tslib_1.__rest(props,["label","children","type","clientId","scope","returnUrl","customDomain"]),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default),[href,setHref]=(0,react_1.useState)(void 0);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint);(0,react_1.useEffect)(()=>((0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{accessToken}}).then(config=>{var _a;if(!((_a=config?.links)===null||_a===void 0)&&_a.identity)setHref(config.links.identity);else{const link=(0,getApplicationLink_1.getApplicationLink)({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,customDomain});setHref(link)}}),()=>{setHref(void 0)}),[]);const parentProps=Object.assign({label,href,clientId,scope},p);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({href},p,{children:label}))}exports.MyIdentityLink=MyIdentityLink,exports.default=MyIdentityLink;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MyIdentityLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain"),organization_1=require("../../utils/organization");function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain,resetPasswordUrl}=props,p=tslib_1.__rest(props,["label","children","type","clientId","scope","returnUrl","customDomain","resetPasswordUrl"]),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default),[href,setHref]=(0,react_1.useState)(void 0);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint);(0,react_1.useEffect)(()=>((0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{accessToken}}).then(config=>{var _a;if(!((_a=config?.links)===null||_a===void 0)&&_a.identity)setHref(config.links.identity);else{const link=(0,getApplicationLink_1.getApplicationLink)({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,resetPasswordUrl,customDomain});setHref(link)}}),()=>{setHref(void 0)}),[]);const parentProps=Object.assign({label,href,clientId,scope},p);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({href},p,{children:label}))}exports.MyIdentityLink=MyIdentityLink,exports.default=MyIdentityLink;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails"));function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2;paymentType==="stripe_payments"&&["succeeded","pending"].includes((_b2=(_a2=options?.stripe)===null||_a2===void 0?void 0:_a2.redirectStatus)!==null&&_b2!==void 0?_b2:"")&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[(_b=options?.stripe)===null||_b===void 0?void 0:_b.redirectStatus,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h,_j,_k;if(order?.status!=null&&["draft","pending"].includes(order?.status))if(paymentType==="adyen_payments"&&(!((
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails"));function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2;paymentType==="stripe_payments"&&["succeeded","pending"].includes((_b2=(_a2=options?.stripe)===null||_a2===void 0?void 0:_a2.redirectStatus)!==null&&_b2!==void 0?_b2:"")&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[(_b=options?.stripe)===null||_b===void 0?void 0:_b.redirectStatus,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e=options?.adyen)===null||_e===void 0)&&_e.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&¤tCustomerPaymentSourceId==null&&autoPlaceOrder&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _e,_f,_g,_h,_j;e?.preventDefault(),e?.stopPropagation(),setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}),card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_e=currentPaymentMethodRef?.current)===null||_e===void 0)&&_e.onsubmit&&[!options?.paypalPayerId,!(!((_f=options?.adyen)===null||_f===void 0)&&_f.MD),!(!((_g=options?.checkoutCom)===null||_g===void 0)&&_g.session_id)].every(Boolean)?(isValid=yield(_h=currentPaymentMethodRef.current)===null||_h===void 0?void 0:_h.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_j=checkPaymentSource.payment_response)===null||_j===void 0?void 0:_j.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));setForceDisable(!1),onClick&&placed&&onClick(placed),setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"})}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.PlaceOrderButton=PlaceOrderButton,exports.default=PlaceOrderButton;
|
|
@@ -11,6 +11,7 @@ export type InitialCustomerContext = Partial<{
|
|
|
11
11
|
setResourceTrigger: typeof setResourceTrigger;
|
|
12
12
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
13
13
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
14
|
+
reloadCustomerAddresses: () => Promise<void>;
|
|
14
15
|
} & CustomerState>;
|
|
15
16
|
export declare const defaultCustomerContext: {};
|
|
16
17
|
declare const CustomerContext: import("react").Context<Partial<{
|
|
@@ -24,5 +25,6 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
24
25
|
setResourceTrigger: typeof setResourceTrigger;
|
|
25
26
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
26
27
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
28
|
+
reloadCustomerAddresses: () => Promise<void>;
|
|
27
29
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
28
30
|
export default CustomerContext;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { type InitialCustomerContext } from '../context/CustomerContext';
|
|
1
2
|
import { type setResourceTrigger, type CustomerState } from '../reducers/CustomerReducer';
|
|
2
3
|
type TCustomer = Omit<CustomerState, 'errors' | 'isGuest'> & {
|
|
3
4
|
setResourceTrigger?: typeof setResourceTrigger;
|
|
4
|
-
}
|
|
5
|
+
} & Pick<InitialCustomerContext, 'reloadCustomerAddresses'>;
|
|
5
6
|
interface TReturnCustomer extends Omit<TCustomer, 'errors' | 'isGuest'> {
|
|
6
7
|
}
|
|
7
8
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useCustomerContainer=void 0;const tslib_1=require("tslib"),CustomerContext_1=tslib_1.__importDefault(require("../context/CustomerContext")),react_1=require("react");function useCustomerContainer(){const ctx=(0,react_1.useContext)(CustomerContext_1.default);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers,setResourceTrigger:ctx.setResourceTrigger};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}exports.useCustomerContainer=useCustomerContainer,exports.default=useCustomerContainer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useCustomerContainer=void 0;const tslib_1=require("tslib"),CustomerContext_1=tslib_1.__importDefault(require("../context/CustomerContext")),react_1=require("react");function useCustomerContainer(){const ctx=(0,react_1.useContext)(CustomerContext_1.default);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers,setResourceTrigger:ctx.setResourceTrigger,reloadCustomerAddresses:ctx.reloadCustomerAddresses};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}exports.useCustomerContainer=useCustomerContainer,exports.default=useCustomerContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.removeGiftCardOrCouponCode=exports.setGiftCardOrCouponCode=exports.saveAddressToCustomerAddressBook=exports.setOrderErrors=exports.unsetOrderState=exports.addToCart=exports.addResourceToInclude=exports.setOrder=exports.updateOrder=exports.getApiOrder=exports.createOrder=void 0;const tslib_1=require("tslib"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=require("../utils/organization"),events_1=require("../utils/events"),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];function createOrder(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=yield sdk?.orders.create(Object.assign({metadata},orderAttributes));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""})}exports.createOrder=createOrder;const getApiOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}});exports.getApiOrder=getApiOrder;function updateOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}exports.updateOrder=updateOrder;const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}exports.addResourceToInclude=addResourceToInclude;function addToCart(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d;const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=yield createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=yield sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({id},params),{state}));if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=(0,organization_1.getOrganizationSlug)((
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.removeGiftCardOrCouponCode=exports.setGiftCardOrCouponCode=exports.saveAddressToCustomerAddressBook=exports.setOrderErrors=exports.unsetOrderState=exports.addToCart=exports.addResourceToInclude=exports.setOrder=exports.updateOrder=exports.getApiOrder=exports.createOrder=void 0;const tslib_1=require("tslib"),localStorage_1=require("../utils/localStorage"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),organization_1=require("../utils/organization"),events_1=require("../utils/events"),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];function createOrder(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=yield sdk?.orders.create(Object.assign({metadata},orderAttributes));return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""})}exports.createOrder=createOrder;const getApiOrder=params=>tslib_1.__awaiter(void 0,void 0,void 0,function*(){const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=yield sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}});exports.getApiOrder=getApiOrder;function updateOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource=Object.assign(Object.assign({},attributes),{id});yield sdk.orders.update(resource,{include});const order=yield(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}})}exports.updateOrder=updateOrder;const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded=Object.assign(Object.assign({},payload.includeLoaded),{[resource]:!0});payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded=Object.assign(Object.assign(Object.assign({},resourceIncludedLoaded),newResourceLoaded),payload.includeLoaded&&payload.includeLoaded);payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:Object.assign(Object.assign({},payload),{withoutIncludes:!1})})}exports.addResourceToInclude=addResourceToInclude;function addToCart(params){return tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e;const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=yield createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(!((_a=state?.order)===null||_a===void 0)&&_a.line_items)yield Promise.all((_b=state?.order)===null||_b===void 0?void 0:_b.line_items.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)})));else{const{line_items:lineItems}=yield sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&(yield Promise.all(lineItems.map(lineItem2=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield sdk.line_items.delete(lineItem2.id)}))))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:(_c=lineItem?._update_quantity)!==null&&_c!==void 0?_c:!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=yield sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};yield sdk.line_item_options.create(lineItemOptionsAttributes),yield(0,exports.getApiOrder)(Object.assign({id},params))}else yield(0,exports.getApiOrder)(Object.assign(Object.assign({id},params),{state}));if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode){const{organization}=(0,organization_1.getOrganizationSlug)((_d=config.endpoint)!==null&&_d!==void 0?_d:""),params2=`${id}?accessToken=${(_e=config.accessToken)!==null&&_e!==void 0?_e:""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}})}exports.addToCart=addToCart;const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}exports.setOrderErrors=setOrderErrors;const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;function setGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode;function removeGiftCardOrCouponCode(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=yield updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}})}exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode,exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPaymentConfig=exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.setPaymentSource=exports.setPaymentMethod=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=exports.setLoading=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),snakeToCamelCase_1=require("../utils/snakeToCamelCase"),replace_1=require("../utils/replace"),pick_1=require("../utils/pick");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}exports.setLoading=setLoading;const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({order,dispatch}){const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})});exports.getPaymentMethods=getPaymentMethods;function setPaymentMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=yield updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}})}exports.setPaymentMethod=setPaymentMethod;function setPaymentSource(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){var _b;try{if(config&&order){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(customerPaymentSourceId){if(updateOrder!=null){const{order:orderUpdated}=yield updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:(_b=orderUpdated.payment_source)===null||_b===void 0?void 0:_b.id}})}}else{if(paymentSourceId){const attrs=Object.assign({id:paymentSourceId},attributes);paymentSource=attributes!=null?yield sdk[paymentResource].update(attrs):yield sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs=Object.assign(Object.assign({},attributes),{order:sdk.orders.relationship(order.id)});paymentSource=yield sdk[paymentResource].create(attrs)}return getOrder&&(yield getOrder(order.id)),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=yield getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}})}exports.setPaymentSource=setPaymentSource;const updatePaymentSource=_b=>tslib_1.__awaiter(void 0,[_b],void 0,function*({id,attributes,config,dispatch,paymentResource}){if(config)try{const paymentSource=yield(0,getSdk_1.default)(config)[paymentResource].update(Object.assign({id},attributes));dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}});exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=_c=>tslib_1.__awaiter(void 0,[_c],void 0,function*({paymentSourceId,paymentResource,dispatch}){paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})});exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}exports.getPaymentConfig=getPaymentConfig;const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPaymentConfig=exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.setPaymentSource=exports.setPaymentMethod=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=exports.setLoading=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),snakeToCamelCase_1=require("../utils/snakeToCamelCase"),replace_1=require("../utils/replace"),pick_1=require("../utils/pick");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}exports.setLoading=setLoading;const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({order,dispatch}){const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})});exports.getPaymentMethods=getPaymentMethods;function setPaymentMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=yield updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}})}exports.setPaymentMethod=setPaymentMethod;function setPaymentSource(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){var _b;try{const isAlreadyPlaced=order?.status==="placed";if(console.log("setPaymentSource",order),console.log("isAlreadyPlaced",isAlreadyPlaced),config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(customerPaymentSourceId){if(updateOrder!=null){const{order:orderUpdated}=yield updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:(_b=orderUpdated.payment_source)===null||_b===void 0?void 0:_b.id}})}}else{if(paymentSourceId){const attrs=Object.assign({id:paymentSourceId},attributes);paymentSource=attributes!=null?yield sdk[paymentResource].update(attrs):yield sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs=Object.assign(Object.assign({},attributes),{order:sdk.orders.relationship(order.id)});paymentSource=yield sdk[paymentResource].create(attrs)}return getOrder&&(yield getOrder(order.id)),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=yield getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}})}exports.setPaymentSource=setPaymentSource;const updatePaymentSource=_b=>tslib_1.__awaiter(void 0,[_b],void 0,function*({id,attributes,config,dispatch,paymentResource}){if(config)try{const paymentSource=yield(0,getSdk_1.default)(config)[paymentResource].update(Object.assign({id},attributes));dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}});exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=_c=>tslib_1.__awaiter(void 0,[_c],void 0,function*({paymentSourceId,paymentResource,dispatch}){paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})});exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}exports.getPaymentConfig=getPaymentConfig;const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPlaceOrderStatus=exports.setPlaceOrder=exports.placeOrderPermitted=exports.setPlaceOrderErrors=exports.placeOrderInitialState=exports.setButtonRef=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.setButtonRef=setButtonRef,exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setPlaceOrderErrors=setPlaceOrderErrors;function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}exports.placeOrderPermitted=placeOrderPermitted;function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d,_e,_f,_g,_h;const response={placed:!1};if(state&&config&&order){const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_b=options?.checkoutCom)===null||_b===void 0)&&_b.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:(_c=options?.checkoutCom)===null||_c===void 0?void 0:_c.session_id});if(((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.status)!=="Authorized"){const[action]=((_e=payment?.payment_response)===null||_e===void 0?void 0:_e.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_f=ps?.options)===null||_f===void 0?void 0:_f.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&¤tCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_g=order?.total_amount_cents)!==null&&_g!==void 0?_g:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_h=orderUpdated?.total_amount_cents)!==null&&_h!==void 0?_h:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}exports.setPlaceOrder=setPlaceOrder;function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}exports.setPlaceOrderStatus=setPlaceOrderStatus;const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPlaceOrderStatus=exports.setPlaceOrder=exports.placeOrderPermitted=exports.setPlaceOrderErrors=exports.placeOrderInitialState=exports.setButtonRef=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.setButtonRef=setButtonRef,exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setPlaceOrderErrors=setPlaceOrderErrors;function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}exports.placeOrderPermitted=placeOrderPermitted;function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d,_e,_f,_g,_h;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_b=options?.checkoutCom)===null||_b===void 0)&&_b.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:(_c=options?.checkoutCom)===null||_c===void 0?void 0:_c.session_id});if(((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.status)!=="Authorized"){const[action]=((_e=payment?.payment_response)===null||_e===void 0?void 0:_e.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_f=ps?.options)===null||_f===void 0?void 0:_f.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&¤tCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_g=order?.total_amount_cents)!==null&&_g!==void 0?_g:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_h=orderUpdated?.total_amount_cents)!==null&&_h!==void 0?_h:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}exports.setPlaceOrder=setPlaceOrder;function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}exports.setPlaceOrderStatus=setPlaceOrderStatus;const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
|
|
@@ -6,6 +6,7 @@ type ApplicationTypeProps<T extends ApplicationType = ApplicationType> = T exten
|
|
|
6
6
|
clientId?: string;
|
|
7
7
|
scope?: string;
|
|
8
8
|
returnUrl?: string;
|
|
9
|
+
resetPasswordUrl?: string;
|
|
9
10
|
} : T extends 'identity' ? {
|
|
10
11
|
applicationType: T;
|
|
11
12
|
orderId?: string;
|
|
@@ -13,6 +14,7 @@ type ApplicationTypeProps<T extends ApplicationType = ApplicationType> = T exten
|
|
|
13
14
|
clientId: string;
|
|
14
15
|
scope: string;
|
|
15
16
|
returnUrl: string;
|
|
17
|
+
resetPasswordUrl?: string;
|
|
16
18
|
} : {
|
|
17
19
|
applicationType: Omit<T, 'my-account' | 'identity'>;
|
|
18
20
|
orderId: string;
|
|
@@ -20,6 +22,7 @@ type ApplicationTypeProps<T extends ApplicationType = ApplicationType> = T exten
|
|
|
20
22
|
clientId?: string;
|
|
21
23
|
scope?: string;
|
|
22
24
|
returnUrl?: string;
|
|
25
|
+
resetPasswordUrl?: string;
|
|
23
26
|
};
|
|
24
27
|
interface TArgs {
|
|
25
28
|
accessToken: string;
|
|
@@ -28,5 +31,5 @@ interface TArgs {
|
|
|
28
31
|
customDomain?: string;
|
|
29
32
|
}
|
|
30
33
|
type Props = ApplicationTypeProps & TArgs;
|
|
31
|
-
export declare function getApplicationLink({ orderId, accessToken, slug, domain, applicationType, modeType, clientId, scope, returnUrl, customDomain }: Props): string;
|
|
34
|
+
export declare function getApplicationLink({ orderId, accessToken, slug, domain, applicationType, modeType, clientId, scope, returnUrl, resetPasswordUrl, customDomain }: Props): string;
|
|
32
35
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getApplicationLink=void 0;function getApplicationLink({orderId,accessToken,slug,domain,applicationType,modeType,clientId,scope,returnUrl,customDomain}){var _a;const env=domain==="commercelayer.io"?"":"stg.",t=applicationType==="identity"?modeType==="login"?"":"signup":"",c=clientId?`&clientId=${clientId}`:"",s=scope?`&scope=${scope}`:"",r=returnUrl?`&returnUrl=${returnUrl}`:"",params=applicationType==="identity"?`${c}${s}${r}`:"",domainName=customDomain??`${slug}.${env}commercelayer.app`,application=customDomain?"":`/${applicationType.toString()}`;return`https://${domainName}${application}/${(_a=orderId??t)!==null&&_a!==void 0?_a:""}?accessToken=${accessToken}${params}`}exports.getApplicationLink=getApplicationLink;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getApplicationLink=void 0;function getApplicationLink({orderId,accessToken,slug,domain,applicationType,modeType,clientId,scope,returnUrl,resetPasswordUrl,customDomain}){var _a;const env=domain==="commercelayer.io"?"":"stg.",t=applicationType==="identity"?modeType==="login"?"":"signup":"",c=clientId?`&clientId=${clientId}`:"",s=scope?`&scope=${scope}`:"",r=returnUrl?`&returnUrl=${returnUrl}`:"",p=resetPasswordUrl?`&resetPasswordUrl=${resetPasswordUrl}`:"",params=applicationType==="identity"?`${c}${s}${r}${p}`:"",domainName=customDomain??`${slug}.${env}commercelayer.app`,application=customDomain?"":`/${applicationType.toString()}`;return`https://${domainName}${application}/${(_a=orderId??t)!==null&&_a!==void 0?_a:""}?accessToken=${accessToken}${params}`}exports.getApplicationLink=getApplicationLink;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.businessMandatoryField=exports.fieldsExist=exports.validateValue=void 0;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),isString_1=tslib_1.__importDefault(require("lodash/isString")),without_1=tslib_1.__importDefault(require("lodash/without")),keys_1=tslib_1.__importDefault(require("lodash/keys")),map_1=tslib_1.__importDefault(require("lodash/map")),AddressReducer_1=require("../reducers/AddressReducer"),EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,validateValue=(val,name,type,resource)=>val?type==="email"&&(0,isString_1.default)(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};exports.validateValue=validateValue;const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return(0,map_1.default)(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=(0,exports.validateValue)(val,v.name,v.type,resourceType);(0,isEmpty_1.default)(error)||errors.push(error),values=Object.assign(Object.assign({},values),{[`${v.name}`]:val})}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?Object.assign(Object.assign({},values),{metadata:Object.assign(Object.assign({},values.metadata),{[`${v.name}`]:val})}):Object.assign(Object.assign({},values),{[`${v.name}`]:val}))}),{errors,values}};function fieldsExist(address,schema=AddressReducer_1.addressFields){if(address.business){const required=(0,without_1.default)(schema,"first_name","last_name","line_2"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=(0,without_1.default)(schema,"line_2","company"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}}exports.fieldsExist=fieldsExist;const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}exports.businessMandatoryField=businessMandatoryField,exports.default=validateFormFields;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.businessMandatoryField=exports.fieldsExist=exports.validateValue=void 0;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),isString_1=tslib_1.__importDefault(require("lodash/isString")),without_1=tslib_1.__importDefault(require("lodash/without")),keys_1=tslib_1.__importDefault(require("lodash/keys")),map_1=tslib_1.__importDefault(require("lodash/map")),AddressReducer_1=require("../reducers/AddressReducer"),EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,validateValue=(val,name,type,resource)=>val?type==="email"&&(0,isString_1.default)(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};exports.validateValue=validateValue;const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return(0,map_1.default)(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=(0,exports.validateValue)(val,v.name,v.type,resourceType);(0,isEmpty_1.default)(error)||errors.push(error),values=Object.assign(Object.assign({},values),{[`${v.name}`]:val})}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?Object.assign(Object.assign({},values),{metadata:Object.assign(Object.assign({},values.metadata),{[`${v.name}`]:val})}):Object.assign(Object.assign({},values),{[`${v.name}`]:val}))}),{errors,values}};function fieldsExist(address,schema=AddressReducer_1.addressFields){if(address.business){const required=(0,without_1.default)(schema,"first_name","last_name","line_2","state_code"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=(0,without_1.default)(schema,"line_2","company","state_code"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}}exports.fieldsExist=fieldsExist;const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}exports.businessMandatoryField=businessMandatoryField,exports.default=validateFormFields;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo,useState}from"react";import BaseSelect from"../utils/BaseSelect";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import isEmpty from"lodash/isEmpty";import{getStateOfCountry,isValidState}from"../../utils/countryStateCity";import AddressesContext from"../../context/AddressContext";import BaseInput from"../utils/BaseInput";import CustomerAddressFormContext from"../../context/CustomerAddressFormContext";export function AddressStateSelector(props){const{required=!
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo,useState}from"react";import BaseSelect from"../utils/BaseSelect";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import isEmpty from"lodash/isEmpty";import{getStateOfCountry,isValidState}from"../../utils/countryStateCity";import AddressesContext from"../../context/AddressContext";import BaseInput from"../utils/BaseInput";import CustomerAddressFormContext from"../../context/CustomerAddressFormContext";export function AddressStateSelector(props){const{required=!1,value,name,className="",inputClassName="",selectClassName="",states,...p}=props,billingAddress=useContext(BillingAddressFormContext),shippingAddress=useContext(ShippingAddressFormContext),customerAddress=useContext(CustomerAddressFormContext),{errors:addressErrors}=useContext(AddressesContext),[hasError,setHasError]=useState(!1),[countryCode,setCountryCode]=useState(""),[val,setVal]=useState(value??""),stateOptions=useMemo(()=>isEmpty(countryCode)?[]:getStateOfCountry({countryCode,states}),[states,countryCode]),isEmptyStates=useMemo(()=>()=>isEmpty(stateOptions),[stateOptions]);useEffect(()=>{const billingCountryCode=typeof billingAddress?.values?.billing_address_country_code=="string"?billingAddress?.values?.billing_address_country_code:billingAddress?.values?.billing_address_country_code?.value;billingCountryCode&&billingCountryCode!==countryCode&&setCountryCode(billingCountryCode);const shippingCountryCode=typeof shippingAddress?.values?.shipping_address_country_code=="string"?shippingAddress?.values?.shipping_address_country_code:shippingAddress?.values?.shipping_address_country_code?.value;shippingCountryCode&&shippingCountryCode!==countryCode&&setCountryCode(shippingCountryCode);const changeBillingCountry=[Object.keys(billingAddress).length>0,billingCountryCode,countryCode!==billingCountryCode].every(Boolean);!changeBillingCountry&&value!=null&&value!==""&&value!==val&&(billingAddress.setValue!=null&&billingAddress?.setValue(name,value),setVal(value)),changeBillingCountry&&billingCountryCode&&!isValidState({stateCode:val??"",countryCode:billingCountryCode,states})&&!isEmptyStates()&&(billingAddress.resetField&&billingAddress?.resetField(name),setVal(""));const changeShippingCountry=[!isEmpty(shippingAddress),shippingCountryCode,countryCode!==shippingCountryCode].every(Boolean);if(!changeShippingCountry&&value!=null&&value!==""&&value!==val&&(shippingAddress.setValue!=null&&shippingAddress?.setValue(name,value),setVal(value)),changeShippingCountry&&shippingCountryCode&&!isValidState({stateCode:val??"",countryCode:shippingCountryCode,states})&&!isEmptyStates()&&(shippingAddress.resetField&&shippingAddress?.resetField(name),setVal("")),!isEmpty(billingAddress)){const fieldError=billingAddress?.errors?.[name]?.error;setHasError(!!fieldError)}if(!isEmpty(customerAddress)){const fieldError=customerAddress?.errors?.[name]?.error;setHasError(!!fieldError)}if(!isEmpty(shippingAddress)){const fieldError=shippingAddress?.errors?.[name]?.error;setHasError(!!fieldError)}return()=>{setHasError(!1)}},[value,billingAddress?.values?.billing_address_country_code,shippingAddress?.values?.shipping_address_country_code,addressErrors,customerAddress]);const errorClassName=billingAddress?.errorClassName||shippingAddress?.errorClassName||customerAddress?.errorClassName||"",classNameComputed=isEmptyStates()?`${className} ${inputClassName} ${hasError?errorClassName:""}`:`${className} ${selectClassName} ${hasError?errorClassName:""}`;return isEmptyStates()?_jsx(BaseInput,{...p,name,ref:billingAddress?.validation||shippingAddress?.validation||customerAddress?.validation,className:classNameComputed,required,placeholder:p.placeholder?.label||"",defaultValue:val,type:"text"}):_jsx(BaseSelect,{...p,className:classNameComputed,ref:billingAddress?.validation||shippingAddress?.validation||customerAddress?.validation,required,options:stateOptions,name,value:val})}export default AddressStateSelector;
|
|
@@ -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}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize})},getCustomerSubscriptions:async({pageNumber,pageSize,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize,id})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize})},getCustomerSubscriptions:async({pageNumber,pageSize,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize,id})},reloadCustomerAddresses:async()=>{await getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
|
|
@@ -34,6 +34,10 @@ interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
|
|
|
34
34
|
* The domain of your forked application
|
|
35
35
|
*/
|
|
36
36
|
customDomain?: string;
|
|
37
|
+
/**
|
|
38
|
+
* The reset password url
|
|
39
|
+
*/
|
|
40
|
+
resetPasswordUrl?: string;
|
|
37
41
|
}
|
|
38
42
|
/**
|
|
39
43
|
* This component generates a link to the hosted mfe-identity application.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";import{getOrganizationConfig}from"../../utils/organization";export function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain,...p}=props,{accessToken,endpoint}=useContext(CommerceLayerContext),[href,setHref]=useState(void 0);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint);useEffect(()=>(getOrganizationConfig({accessToken,endpoint,params:{accessToken}}).then(config=>{if(config?.links?.identity)setHref(config.links.identity);else{const link=getApplicationLink({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,customDomain});setHref(link)}}),()=>{setHref(void 0)}),[]);const parentProps={label,href,clientId,scope,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,...p,children:label})}export default MyIdentityLink;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";import{getOrganizationConfig}from"../../utils/organization";export function MyIdentityLink(props){const{label,children,type,clientId,scope,returnUrl,customDomain,resetPasswordUrl,...p}=props,{accessToken,endpoint}=useContext(CommerceLayerContext),[href,setHref]=useState(void 0);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyIdentityLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint);useEffect(()=>(getOrganizationConfig({accessToken,endpoint,params:{accessToken}}).then(config=>{if(config?.links?.identity)setHref(config.links.identity);else{const link=getApplicationLink({slug,accessToken,applicationType:"identity",domain,modeType:type,clientId,scope,returnUrl:returnUrl??window.location.href,resetPasswordUrl,customDomain});setHref(link)}}),()=>{setHref(void 0)}),[]);const parentProps={label,href,clientId,scope,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,...p,children:label})}export default MyIdentityLink;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),useEffect(()=>{paymentType==="stripe_payments"&&["succeeded","pending"].includes(options?.stripe?.redirectStatus??"")&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.stripe?.redirectStatus,paymentType]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status))if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),useEffect(()=>{paymentType==="stripe_payments"&&["succeeded","pending"].includes(options?.stripe?.redirectStatus??"")&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.stripe?.redirectStatus,paymentType]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&ref?.current?.disabled===!1&¤tCustomerPaymentSourceId==null&&autoPlaceOrder&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation(),setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}),card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});setForceDisable(!1),onClick&&placed&&onClick(placed),setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"})},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
|
|
@@ -11,6 +11,7 @@ export type InitialCustomerContext = Partial<{
|
|
|
11
11
|
setResourceTrigger: typeof setResourceTrigger;
|
|
12
12
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
13
13
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
14
|
+
reloadCustomerAddresses: () => Promise<void>;
|
|
14
15
|
} & CustomerState>;
|
|
15
16
|
export declare const defaultCustomerContext: {};
|
|
16
17
|
declare const CustomerContext: import("react").Context<Partial<{
|
|
@@ -24,5 +25,6 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
24
25
|
setResourceTrigger: typeof setResourceTrigger;
|
|
25
26
|
getCustomerOrders: (props: Partial<Parameters<typeof getCustomerOrders>[0]>) => Promise<void>;
|
|
26
27
|
getCustomerSubscriptions: (props: Partial<Parameters<typeof getCustomerSubscriptions>[0]>) => Promise<void>;
|
|
28
|
+
reloadCustomerAddresses: () => Promise<void>;
|
|
27
29
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
28
30
|
export default CustomerContext;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { type InitialCustomerContext } from '../context/CustomerContext';
|
|
1
2
|
import { type setResourceTrigger, type CustomerState } from '../reducers/CustomerReducer';
|
|
2
3
|
type TCustomer = Omit<CustomerState, 'errors' | 'isGuest'> & {
|
|
3
4
|
setResourceTrigger?: typeof setResourceTrigger;
|
|
4
|
-
}
|
|
5
|
+
} & Pick<InitialCustomerContext, 'reloadCustomerAddresses'>;
|
|
5
6
|
interface TReturnCustomer extends Omit<TCustomer, 'errors' | 'isGuest'> {
|
|
6
7
|
}
|
|
7
8
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import CustomerContext from"../context/CustomerContext";import{useContext}from"react";export function useCustomerContainer(){const ctx=useContext(CustomerContext);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers,setResourceTrigger:ctx.setResourceTrigger};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}export default useCustomerContainer;
|
|
2
|
+
import CustomerContext from"../context/CustomerContext";import{useContext}from"react";export function useCustomerContainer(){const ctx=useContext(CustomerContext);if("addresses"in ctx)return{addresses:ctx.addresses,payments:ctx.payments,orders:ctx.orders,subscriptions:ctx.subscriptions,customerEmail:ctx.customerEmail,customers:ctx.customers,setResourceTrigger:ctx.setResourceTrigger,reloadCustomerAddresses:ctx.reloadCustomerAddresses};throw new Error("Cannot use `useCustomerContainer` outside of <CustomerContainer/>")}export default useCustomerContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
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";import{publish}from"../utils/events";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";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""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;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=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};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,openMiniCart=!0}=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,externalPrice=lineItem?.externalPrice;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
|
|
2
|
+
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";import{publish}from"../utils/events";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";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""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;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=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};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,openMiniCart=!0}=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,externalPrice=lineItem?.externalPrice;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:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const 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}else openMiniCart&&publish("open-cart");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,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{snakeToCamelCase}from"../utils/snakeToCamelCase";import{replace}from"../utils/replace";import{pick}from"../utils/pick";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=await updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{if(config&&order){let paymentSource;const sdk=getSdk(config);if(customerPaymentSourceId){if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}else{if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{snakeToCamelCase}from"../utils/snakeToCamelCase";import{replace}from"../utils/replace";import{pick}from"../utils/pick";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=await updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(console.log("setPaymentSource",order),console.log("isAlreadyPlaced",isAlreadyPlaced),config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=getSdk(config);if(customerPaymentSourceId){if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}else{if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){const sdk=getSdk(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&¤tCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&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([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&¤tCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&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([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
|
|
@@ -6,6 +6,7 @@ type ApplicationTypeProps<T extends ApplicationType = ApplicationType> = T exten
|
|
|
6
6
|
clientId?: string;
|
|
7
7
|
scope?: string;
|
|
8
8
|
returnUrl?: string;
|
|
9
|
+
resetPasswordUrl?: string;
|
|
9
10
|
} : T extends 'identity' ? {
|
|
10
11
|
applicationType: T;
|
|
11
12
|
orderId?: string;
|
|
@@ -13,6 +14,7 @@ type ApplicationTypeProps<T extends ApplicationType = ApplicationType> = T exten
|
|
|
13
14
|
clientId: string;
|
|
14
15
|
scope: string;
|
|
15
16
|
returnUrl: string;
|
|
17
|
+
resetPasswordUrl?: string;
|
|
16
18
|
} : {
|
|
17
19
|
applicationType: Omit<T, 'my-account' | 'identity'>;
|
|
18
20
|
orderId: string;
|
|
@@ -20,6 +22,7 @@ type ApplicationTypeProps<T extends ApplicationType = ApplicationType> = T exten
|
|
|
20
22
|
clientId?: string;
|
|
21
23
|
scope?: string;
|
|
22
24
|
returnUrl?: string;
|
|
25
|
+
resetPasswordUrl?: string;
|
|
23
26
|
};
|
|
24
27
|
interface TArgs {
|
|
25
28
|
accessToken: string;
|
|
@@ -28,5 +31,5 @@ interface TArgs {
|
|
|
28
31
|
customDomain?: string;
|
|
29
32
|
}
|
|
30
33
|
type Props = ApplicationTypeProps & TArgs;
|
|
31
|
-
export declare function getApplicationLink({ orderId, accessToken, slug, domain, applicationType, modeType, clientId, scope, returnUrl, customDomain }: Props): string;
|
|
34
|
+
export declare function getApplicationLink({ orderId, accessToken, slug, domain, applicationType, modeType, clientId, scope, returnUrl, resetPasswordUrl, customDomain }: Props): string;
|
|
32
35
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
export function getApplicationLink({orderId,accessToken,slug,domain,applicationType,modeType,clientId,scope,returnUrl,customDomain}){const env=domain==="commercelayer.io"?"":"stg.",t=applicationType==="identity"?modeType==="login"?"":"signup":"",c=clientId?`&clientId=${clientId}`:"",s=scope?`&scope=${scope}`:"",r=returnUrl?`&returnUrl=${returnUrl}`:"",params=applicationType==="identity"?`${c}${s}${r}`:"",domainName=customDomain??`${slug}.${env}commercelayer.app`,application=customDomain?"":`/${applicationType.toString()}`;return`https://${domainName}${application}/${orderId??t??""}?accessToken=${accessToken}${params}`}
|
|
2
|
+
export function getApplicationLink({orderId,accessToken,slug,domain,applicationType,modeType,clientId,scope,returnUrl,resetPasswordUrl,customDomain}){const env=domain==="commercelayer.io"?"":"stg.",t=applicationType==="identity"?modeType==="login"?"":"signup":"",c=clientId?`&clientId=${clientId}`:"",s=scope?`&scope=${scope}`:"",r=returnUrl?`&returnUrl=${returnUrl}`:"",p=resetPasswordUrl?`&resetPasswordUrl=${resetPasswordUrl}`:"",params=applicationType==="identity"?`${c}${s}${r}${p}`:"",domainName=customDomain??`${slug}.${env}commercelayer.app`,application=customDomain?"":`/${applicationType.toString()}`;return`https://${domainName}${application}/${orderId??t??""}?accessToken=${accessToken}${params}`}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import isEmpty from"lodash/isEmpty";import isString from"lodash/isString";import without from"lodash/without";import keys from"lodash/keys";import map from"lodash/map";import{addressFields}from"../reducers/AddressReducer";const EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;export const validateValue=(val,name,type,resource)=>val?type==="email"&&isString(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return map(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=validateValue(val,v.name,v.type,resourceType);isEmpty(error)||errors.push(error),values={...values,[`${v.name}`]:val}}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?{...values,metadata:{...values.metadata,[`${v.name}`]:val}}:{...values,[`${v.name}`]:val})}),{errors,values}};export function fieldsExist(address,schema=addressFields){if(address.business){const required=without(schema,"first_name","last_name","line_2"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=without(schema,"line_2","company"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}}const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];export function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}export default validateFormFields;
|
|
2
|
+
import isEmpty from"lodash/isEmpty";import isString from"lodash/isString";import without from"lodash/without";import keys from"lodash/keys";import map from"lodash/map";import{addressFields}from"../reducers/AddressReducer";const EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;export const validateValue=(val,name,type,resource)=>val?type==="email"&&isString(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return map(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=validateValue(val,v.name,v.type,resourceType);isEmpty(error)||errors.push(error),values={...values,[`${v.name}`]:val}}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?{...values,metadata:{...values.metadata,[`${v.name}`]:val}}:{...values,[`${v.name}`]:val})}),{errors,values}};export function fieldsExist(address,schema=addressFields){if(address.business){const required=without(schema,"first_name","last_name","line_2","state_code"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=without(schema,"line_2","company","state_code"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}}const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];export function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}export default validateFormFields;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commercelayer/react-components",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.14.1",
|
|
4
4
|
"description": "The Official Commerce Layer React Components",
|
|
5
5
|
"main": "lib/cjs/index.js",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -165,47 +165,47 @@
|
|
|
165
165
|
},
|
|
166
166
|
"homepage": "https://github.com/commercelayer/commercelayer-react-components#readme",
|
|
167
167
|
"dependencies": {
|
|
168
|
-
"@adyen/adyen-web": "^5.
|
|
169
|
-
"@commercelayer/organization-config": "^1.4.
|
|
170
|
-
"@commercelayer/sdk": "6.0
|
|
171
|
-
"@stripe/react-stripe-js": "^2.
|
|
172
|
-
"@stripe/stripe-js": "^
|
|
173
|
-
"@tanstack/react-table": "^8.
|
|
168
|
+
"@adyen/adyen-web": "^5.66.1",
|
|
169
|
+
"@commercelayer/organization-config": "^1.4.6",
|
|
170
|
+
"@commercelayer/sdk": "6.9.0",
|
|
171
|
+
"@stripe/react-stripe-js": "^2.7.1",
|
|
172
|
+
"@stripe/stripe-js": "^4.0.0",
|
|
173
|
+
"@tanstack/react-table": "^8.17.3",
|
|
174
174
|
"@types/iframe-resizer": "^3.5.13",
|
|
175
|
-
"axios": "^1.
|
|
176
|
-
"braintree-web": "^3.
|
|
177
|
-
"frames-react": "^1.1.
|
|
178
|
-
"iframe-resizer": "^4.
|
|
175
|
+
"axios": "^1.7.2",
|
|
176
|
+
"braintree-web": "^3.102.0",
|
|
177
|
+
"frames-react": "^1.1.1",
|
|
178
|
+
"iframe-resizer": "^4.4.2",
|
|
179
179
|
"jwt-decode": "^4.0.0",
|
|
180
180
|
"lodash": "^4.17.21",
|
|
181
181
|
"rapid-form": "^2.1.0"
|
|
182
182
|
},
|
|
183
183
|
"devDependencies": {
|
|
184
|
-
"@commercelayer/js-auth": "^6.2.
|
|
184
|
+
"@commercelayer/js-auth": "^6.2.2",
|
|
185
185
|
"@faker-js/faker": "^8.4.0",
|
|
186
|
-
"@playwright/test": "^1.
|
|
186
|
+
"@playwright/test": "^1.44.1",
|
|
187
187
|
"@testing-library/dom": "^10.1.0",
|
|
188
|
-
"@testing-library/react": "^
|
|
188
|
+
"@testing-library/react": "^16.0.0",
|
|
189
189
|
"@types/braintree-web": "^3.96.10",
|
|
190
|
-
"@types/lodash": "^4.17.
|
|
191
|
-
"@types/node": "^20.
|
|
190
|
+
"@types/lodash": "^4.17.5",
|
|
191
|
+
"@types/node": "^20.14.6",
|
|
192
192
|
"@types/prop-types": "^15.7.12",
|
|
193
|
-
"@types/react": "^18.
|
|
193
|
+
"@types/react": "^18.3.3",
|
|
194
194
|
"@types/react-test-renderer": "^18.0.7",
|
|
195
195
|
"@types/react-window": "^1.8.8",
|
|
196
|
-
"@vitejs/plugin-react": "^4.
|
|
196
|
+
"@vitejs/plugin-react": "^4.3.1",
|
|
197
197
|
"@vitest/coverage-v8": "^1.6.0",
|
|
198
|
-
"eslint": "
|
|
199
|
-
"jsdom": "^24.
|
|
198
|
+
"eslint": "~9.5.0",
|
|
199
|
+
"jsdom": "^24.1.0",
|
|
200
200
|
"minimize-js": "^1.4.0",
|
|
201
|
-
"msw": "^2.
|
|
201
|
+
"msw": "^2.3.1",
|
|
202
202
|
"react": "^18.2.0",
|
|
203
203
|
"react-dom": "^18.2.0",
|
|
204
204
|
"react-test-renderer": "^18.2.0",
|
|
205
205
|
"tsc-alias": "^1.8.8",
|
|
206
|
-
"tslib": "^2.6.
|
|
206
|
+
"tslib": "^2.6.3",
|
|
207
207
|
"typescript": "^5.4.4",
|
|
208
|
-
"vite": "^5.
|
|
208
|
+
"vite": "^5.3.1",
|
|
209
209
|
"vite-tsconfig-paths": "^4.3.2",
|
|
210
210
|
"vitest": "^1.4.0"
|
|
211
211
|
},
|