@commercelayer/react-components 4.15.9-beta.2 → 4.15.9
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/AddressesContainer.js +1 -1
- package/lib/cjs/components/addresses/SaveAddressesButton.js +1 -1
- package/lib/cjs/components/payment_source/BraintreePayment.js +1 -1
- package/lib/cjs/context/AddressContext.d.ts +5 -2
- package/lib/cjs/reducers/AddressReducer.d.ts +6 -1
- package/lib/cjs/reducers/AddressReducer.js +1 -1
- package/lib/cjs/reducers/CustomerReducer.js +1 -1
- package/lib/cjs/utils/addressesManager.d.ts +1 -0
- package/lib/cjs/utils/addressesManager.js +1 -1
- package/lib/esm/components/addresses/AddressesContainer.js +1 -1
- package/lib/esm/components/addresses/SaveAddressesButton.js +1 -1
- package/lib/esm/components/payment_source/BraintreePayment.js +1 -1
- package/lib/esm/context/AddressContext.d.ts +5 -2
- package/lib/esm/reducers/AddressReducer.d.ts +6 -1
- package/lib/esm/reducers/AddressReducer.js +1 -1
- package/lib/esm/reducers/CustomerReducer.js +1 -1
- package/lib/esm/utils/addressesManager.d.ts +1 -0
- package/lib/esm/utils/addressesManager.js +1 -1
- package/package.json +11 -11
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddressesContainer=AddressesContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),AddressContext_1=tslib_1.__importStar(require("../../context/AddressContext")),react_1=require("react"),AddressReducer_1=tslib_1.__importStar(require("../../reducers/AddressReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext"));function AddressesContainer(props){const{children,shipToDifferentAddress=!1,isBusiness,invertAddresses=!1}=props,[state,dispatch]=(0,react_1.useReducer)(AddressReducer_1.default,AddressReducer_1.addressInitialState),{order,orderId,updateOrder}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>(dispatch({type:"setShipToDifferentAddress",payload:{shipToDifferentAddress,isBusiness,invertAddresses}}),()=>{dispatch({type:"cleanup",payload:{}})}),[shipToDifferentAddress,isBusiness,invertAddresses]);const contextValue=Object.assign(Object.assign({},state),{setAddressErrors:(errors,resource)=>{(0,AddressReducer_1.setAddressErrors)({errors,resource,dispatch,currentErrors:state.errors})},setAddress:params=>{AddressContext_1.defaultAddressContext.setAddress(Object.assign(Object.assign({},params),{dispatch}))},saveAddresses:
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddressesContainer=AddressesContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),AddressContext_1=tslib_1.__importStar(require("../../context/AddressContext")),react_1=require("react"),AddressReducer_1=tslib_1.__importStar(require("../../reducers/AddressReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext"));function AddressesContainer(props){const{children,shipToDifferentAddress=!1,isBusiness,invertAddresses=!1}=props,[state,dispatch]=(0,react_1.useReducer)(AddressReducer_1.default,AddressReducer_1.addressInitialState),{order,orderId,updateOrder}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>(dispatch({type:"setShipToDifferentAddress",payload:{shipToDifferentAddress,isBusiness,invertAddresses}}),()=>{dispatch({type:"cleanup",payload:{}})}),[shipToDifferentAddress,isBusiness,invertAddresses]);const contextValue=Object.assign(Object.assign({},state),{setAddressErrors:(errors,resource)=>{(0,AddressReducer_1.setAddressErrors)({errors,resource,dispatch,currentErrors:state.errors})},setAddress:params=>{AddressContext_1.defaultAddressContext.setAddress(Object.assign(Object.assign({},params),{dispatch}))},saveAddresses:params=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,AddressReducer_1.saveAddresses)(Object.assign({config,dispatch,updateOrder,order,orderId,state},params))}),setCloneAddress:(id,resource)=>{(0,AddressReducer_1.setCloneAddress)(id,resource,dispatch)}});return(0,jsx_runtime_1.jsx)(AddressContext_1.default.Provider,{value:contextValue,children})}exports.default=AddressesContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SaveAddressesButton=SaveAddressesButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),addressesManager_1=require("../../utils/addressesManager"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),validateFormFields_1=require("../../utils/validateFormFields");function SaveAddressesButton(props){const{children,label="Continue to delivery",resource,disabled=!1,addressId,requiredMetadataFields,onClick}=props,p=tslib_1.__rest(props,["children","label","resource","disabled","addressId","requiredMetadataFields","onClick"]),{errors,billing_address:billingAddress,shipToDifferentAddress,shipping_address:shippingAddress,saveAddresses,billingAddressId,shippingAddressId,invertAddresses}=(0,react_1.useContext)(AddressContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{customerEmail:email,addresses,isGuest,createCustomerAddress}=(0,react_1.useContext)(CustomerContext_1.default),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled);let customerEmail=(isGuest===!0||typeof isGuest>"u")&&!order?.customer_email;if(email!=null&&email!==""){const isValidEmail=(0,validateFormFields_1.validateValue)(email,"customer_email","email","orders");customerEmail=Object.keys(isValidEmail).length>0}const shippingAddressCleaned=Object.keys(shippingAddress??{}).reduce((acc,key)=>Object.assign(Object.assign({},acc),{[key.replace("shipping_address_","")]:shippingAddress[key].value}),{}),{billingDisable,shippingDisable}=(0,addressesManager_1.addressesController)({invertAddresses,requiresBillingInfo:order?.requires_billing_info,billing_address:billingAddress,shipping_address:shippingAddressCleaned,shipToDifferentAddress,shippingAddressId,billingAddressId,errors,requiredMetadataFields}),countryLockDisable=(0,addressesManager_1.countryLockController)({countryCodeLock:order?.shipping_country_code_lock,addresses,shipToDifferentAddress,billingAddressId,billing_address:billingAddress,shipping_address:shippingAddress,shippingAddressId,lineItems:order?.line_items}),disable=disabled||customerEmail||billingDisable||(invertAddresses&&shippingAddressId?!1:shippingDisable)||countryLockDisable,handleClick=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){if(errors&&Object.keys(errors).length===0&&!disable){let response={success:!1};
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SaveAddressesButton=SaveAddressesButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),addressesManager_1=require("../../utils/addressesManager"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),validateFormFields_1=require("../../utils/validateFormFields");function SaveAddressesButton(props){const{children,label="Continue to delivery",resource,disabled=!1,addressId,requiredMetadataFields,onClick}=props,p=tslib_1.__rest(props,["children","label","resource","disabled","addressId","requiredMetadataFields","onClick"]),{errors,billing_address:billingAddress,shipToDifferentAddress,shipping_address:shippingAddress,saveAddresses,billingAddressId,shippingAddressId,invertAddresses}=(0,react_1.useContext)(AddressContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{customerEmail:email,addresses,isGuest,createCustomerAddress}=(0,react_1.useContext)(CustomerContext_1.default),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled);let customerEmail=(isGuest===!0||typeof isGuest>"u")&&!order?.customer_email;if(email!=null&&email!==""){const isValidEmail=(0,validateFormFields_1.validateValue)(email,"customer_email","email","orders");customerEmail=Object.keys(isValidEmail).length>0}const shippingAddressCleaned=Object.keys(shippingAddress??{}).reduce((acc,key)=>Object.assign(Object.assign({},acc),{[key.replace("shipping_address_","")]:shippingAddress[key].value}),{}),{billingDisable,shippingDisable}=(0,addressesManager_1.addressesController)({invertAddresses,requiresBillingInfo:order?.requires_billing_info,billing_address:billingAddress,shipping_address:shippingAddressCleaned,shipToDifferentAddress,shippingAddressId,billingAddressId,errors,requiredMetadataFields}),countryLockDisable=(0,addressesManager_1.countryLockController)({countryCodeLock:order?.shipping_country_code_lock,addresses,shipToDifferentAddress,billingAddressId,billing_address:billingAddress,shipping_address:shippingAddress,shippingAddressId,lineItems:order?.line_items}),disable=disabled||customerEmail||billingDisable||(invertAddresses&&shippingAddressId?!1:shippingDisable)||countryLockDisable,handleClick=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){if(errors&&Object.keys(errors).length===0&&!disable){let response={success:!1};switch(setForceDisable(!0),!0){case(order!=null&&addressId!=null&&createCustomerAddress!=null&&saveAddresses!=null):response=yield saveAddresses({customerEmail:email,customerAddress:{resource:invertAddresses?"shipping_address":"billing_address",id:addressId}});break;case(order!=null&&saveAddresses!=null):response=yield saveAddresses({customerEmail:email});break;case createCustomerAddress!=null:const address=invertAddresses?Object.assign({},shippingAddress):Object.assign({},billingAddress);addressId&&(address.id=addressId),createCustomerAddress(address),response={success:!0};break}setForceDisable(!1),onClick&&response.success&&onClick(response)}}),parentProps=Object.assign(Object.assign({},p),{label,resource,handleClick,disabled:disable});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({type:"button",disabled:disable||forceDisable,onClick:()=>{handleClick()}},p,{children:(0,isFunction_1.default)(label)?label():label}))}exports.default=SaveAddressesButton;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BraintreePayment=BraintreePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),promisify_1=tslib_1.__importDefault(require("../../utils/promisify")),defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){var _a,_b,_c;const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}=Object.assign(Object.assign({},defaultConfig),config),[loadBraintree,setLoadBraintree]=(0,react_1.useState)(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null),handleSubmitForm=_a2=>tslib_1.__awaiter(this,[_a2],void 0,function*({event,hostedFieldsInstance,threeDSInstance}){var _b2,_c2,_d,_e,_f,_g;const savePaymentSourceToCustomerWallet=(_c2=(_b2=event?.elements)===null||_b2===void 0?void 0:_b2.save_payment_source_to_customer_wallet)===null||_c2===void 0?void 0:_c2.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=yield(0,promisify_1.default)(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:(_d=order?.customer_email)!==null&&_d!==void 0?_d:"",billingAddress:{givenName:(_e=billingAddress?.first_name)!==null&&_e!==void 0?_e:"",surname:(_f=billingAddress?.last_name)!==null&&_f!==void 0?_f:"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:(_g=billingAddress?.zip_code)!==null&&_g!==void 0?_g:"",region:billingAddress?.state_code,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=yield threeDSInstance.verifyCard(verifyCardOptions);
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BraintreePayment=BraintreePayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),promisify_1=tslib_1.__importDefault(require("../../utils/promisify")),defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){var _a,_b,_c;const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}=Object.assign(Object.assign({},defaultConfig),config),[loadBraintree,setLoadBraintree]=(0,react_1.useState)(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null),handleSubmitForm=_a2=>tslib_1.__awaiter(this,[_a2],void 0,function*({event,hostedFieldsInstance,threeDSInstance}){var _b2,_c2,_d,_e,_f,_g,_h;const savePaymentSourceToCustomerWallet=(_c2=(_b2=event?.elements)===null||_b2===void 0?void 0:_b2.save_payment_source_to_customer_wallet)===null||_c2===void 0?void 0:_c2.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=yield(0,promisify_1.default)(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:(_d=order?.customer_email)!==null&&_d!==void 0?_d:"",billingAddress:{givenName:(_e=billingAddress?.first_name)!==null&&_e!==void 0?_e:"",surname:(_f=billingAddress?.last_name)!==null&&_f!==void 0?_f:"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:(_g=billingAddress?.zip_code)!==null&&_g!==void 0?_g:"",region:billingAddress?.state_code,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=yield threeDSInstance.verifyCard(verifyCardOptions),validStatus=response?.liabilityShiftPossible===!0&&response?.liabilityShifted===!0;if(console.log("validStatus",validStatus),validStatus&&paymentSource!=null)return yield setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"braintree_payments",attributes:{payment_method_nonce:response.nonce,options:{id:response.nonce,card:{last4:response.details.lastFour,exp_year:response.details.expirationYear,exp_month:response.details.expirationMonth,brand:response.details.cardType.toLowerCase()}}}}),!0;throw new Error(`3D Secure authentication failed - ${(_h=response?.threeDSecureInfo)===null||_h===void 0?void 0:_h.status}`)}catch(error){return console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}return!1});return(0,react_1.useEffect)(()=>{if(!ref&&authorization&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),authorization&&!loadBraintree&&!(0,isEmpty_1.default)(window)){const braintreeClient=require("braintree-web/client"),hostedFields=require("braintree-web/hosted-fields"),threeDSecure=require("braintree-web/three-d-secure");braintreeClient.create({authorization},(clientErr,clientInstance)=>{if(clientErr){console.error(clientErr);return}hostedFields.create({client:clientInstance,fields,styles},(hostedFieldsErr,hostedFieldsInstance)=>{if(hostedFieldsErr){console.error(hostedFieldsErr);return}setLoadBraintree(!0),threeDSecure.create({authorization,version:2},(threeDSecureErr,threeDSInstance)=>{threeDSecureErr&&(console.error("3DSecure error",threeDSecureErr),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:threeDSecureErr.message}])),ref.current&&(ref.current.onsubmit=paymentSource2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmitForm({event:ref.current,hostedFieldsInstance,threeDSInstance,paymentSource:paymentSource2})}),setPaymentRef({ref}))})})})}return()=>{setPaymentRef({ref:{current:null}}),setLoadBraintree(!1)}},[authorization,ref]),!authorization&&!loadBraintree?null:(0,jsx_runtime_1.jsx)("div",{className:containerClassName,children:(0,jsx_runtime_1.jsxs)("form",{ref,id:"braintree-form",onSubmit:handleSubmitForm,className:containerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:fieldsContainerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:cardContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"card-number",children:(_a=fields?.number)===null||_a===void 0?void 0:_a.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"card-number"})]}),(0,jsx_runtime_1.jsxs)("div",{className:cardDetailsContainerClassName,children:[(0,jsx_runtime_1.jsxs)("div",{className:expDateContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"expiration-date",children:(_b=fields?.expirationDate)===null||_b===void 0?void 0:_b.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"expiration-date"})]}),(0,jsx_runtime_1.jsxs)("div",{className:cvvContainerClassName,children:[(0,jsx_runtime_1.jsx)("label",{className:fieldLabelClassName,htmlFor:"cvv",children:(_c=fields?.cvv)===null||_c===void 0?void 0:_c.label}),(0,jsx_runtime_1.jsx)("div",{className:inputWrapperClassName,id:"cvv"})]})]})]}),(0,jsx_runtime_1.jsx)("div",{className:fieldsContainerClassName,children:templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})})]})})}exports.default=BraintreePayment;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import { type AddressState, setAddress, type AddressResource, type saveAddresses } from '../reducers/AddressReducer';
|
|
1
|
+
import { type AddressState, setAddress, type AddressResource, type saveAddresses, ICustomerAddress } from '../reducers/AddressReducer';
|
|
2
2
|
import { type BaseError } from '../typings/errors';
|
|
3
3
|
type DefaultContext = {
|
|
4
|
-
saveAddresses?: (
|
|
4
|
+
saveAddresses?: (params: {
|
|
5
|
+
customerEmail?: string;
|
|
6
|
+
customerAddress?: ICustomerAddress;
|
|
7
|
+
}) => ReturnType<typeof saveAddresses>;
|
|
5
8
|
setCloneAddress: (id: string, resource: AddressResource) => void;
|
|
6
9
|
setAddress: typeof setAddress;
|
|
7
10
|
setAddressErrors: (errors: BaseError[], resource: AddressResource) => void;
|
|
@@ -56,6 +56,10 @@ export declare const setAddressErrors: SetAddressErrors;
|
|
|
56
56
|
export declare function setAddress<V extends AddressSchema>({ values, resource, dispatch }: SetAddressParams<V>): void;
|
|
57
57
|
type SetCloneAddress = (id: string, resource: AddressResource, dispatch: Dispatch<AddressAction>) => void;
|
|
58
58
|
export declare const setCloneAddress: SetCloneAddress;
|
|
59
|
+
export interface ICustomerAddress {
|
|
60
|
+
id: string | undefined;
|
|
61
|
+
resource: AddressResource;
|
|
62
|
+
}
|
|
59
63
|
interface TSaveAddressesParams {
|
|
60
64
|
orderId?: string;
|
|
61
65
|
order?: Order | null;
|
|
@@ -65,8 +69,9 @@ interface TSaveAddressesParams {
|
|
|
65
69
|
dispatch: Dispatch<AddressAction>;
|
|
66
70
|
getCustomerAddresses?: () => Promise<void>;
|
|
67
71
|
customerEmail?: string;
|
|
72
|
+
customerAddress?: ICustomerAddress;
|
|
68
73
|
}
|
|
69
|
-
export declare function saveAddresses({ config, updateOrder, order, state, customerEmail }: TSaveAddressesParams): Promise<{
|
|
74
|
+
export declare function saveAddresses({ config, updateOrder, order, state, customerEmail, customerAddress }: TSaveAddressesParams): Promise<{
|
|
70
75
|
success: boolean;
|
|
71
76
|
order?: Order;
|
|
72
77
|
error?: unknown;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setCloneAddress=exports.setAddressErrors=exports.addressInitialState=exports.addressFields=void 0,exports.setAddress=setAddress,exports.saveAddresses=saveAddresses;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),camelCase_1=tslib_1.__importDefault(require("lodash/camelCase")),addressesManager_1=require("../utils/addressesManager"),formCleaner_1=require("../utils/formCleaner");exports.addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],exports.addressInitialState={errors:[]};const setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};exports.setAddressErrors=setAddressErrors;function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:Object.assign({},(0,formCleaner_1.formCleaner)(values))};dispatch&&dispatch({type:"setAddress",payload})}const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${(0,camelCase_1.default)(resource)}Id`]:id}})};exports.setCloneAddress=setCloneAddress;function saveAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,updateOrder,order,state,customerEmail}){var _b,_c,_d,_e;const{shipToDifferentAddress,invertAddresses,billing_address:billingAddress,shipping_address:shippingAddress,billingAddressId,shippingAddressId}=state;try{const sdk=(0,getSdk_1.default)(config);if(order){let orderAttributes=null;if(invertAddresses)orderAttributes=yield(0,addressesManager_1.invertedAddressesHandler)({billingAddress,billingAddressId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk});else{const doNotShipItems=(_b=order?.line_items)===null||_b===void 0?void 0:_b.every(lineItem=>{var _a2;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.do_not_ship)===!0}),currentBillingAddressRef=(_c=order?.billing_address)===null||_c===void 0?void 0:_c.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setCloneAddress=exports.setAddressErrors=exports.addressInitialState=exports.addressFields=void 0,exports.setAddress=setAddress,exports.saveAddresses=saveAddresses;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),camelCase_1=tslib_1.__importDefault(require("lodash/camelCase")),addressesManager_1=require("../utils/addressesManager"),formCleaner_1=require("../utils/formCleaner");exports.addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],exports.addressInitialState={errors:[]};const setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};exports.setAddressErrors=setAddressErrors;function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:Object.assign({},(0,formCleaner_1.formCleaner)(values))};dispatch&&dispatch({type:"setAddress",payload})}const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${(0,camelCase_1.default)(resource)}Id`]:id}})};exports.setCloneAddress=setCloneAddress;function saveAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,updateOrder,order,state,customerEmail,customerAddress}){var _b,_c,_d,_e;const{shipToDifferentAddress,invertAddresses,billing_address:billingAddress,shipping_address:shippingAddress,billingAddressId,shippingAddressId}=state;try{const sdk=(0,getSdk_1.default)(config);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=yield(0,addressesManager_1.invertedAddressesHandler)({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=(_b=order?.line_items)===null||_b===void 0?void 0:_b.every(lineItem=>{var _a2;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.do_not_ship)===!0}),currentBillingAddressRef=(_c=order?.billing_address)===null||_c===void 0?void 0:_c.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=(_d=order?.billing_address)===null||_d===void 0?void 0:_d.id,orderAttributes._shipping_address_clone_id=(_e=order?.shipping_address)===null||_e===void 0?void 0:_e.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(billingAddress),address=yield sdk.addresses.create(billingAddressWithMeta);orderAttributes.billing_address=sdk.addresses.relationship(address.id)}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(shippingAddress),address=yield sdk.addresses.create(shippingAddressWithMeta);orderAttributes.shipping_address=sdk.addresses.relationship(address.id)}}if(orderAttributes!=null&&updateOrder){const orderUpdated=yield updateOrder({id:order.id,attributes:orderAttributes});return{success:!0,order:orderUpdated?.order}}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}})}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=addressReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper");function saveCustomerUser(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}function getCustomerAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,isOrderAvailable}){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}function deleteCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{yield(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}})}function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}function getCustomerOrders(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}function getCustomerSubscriptions(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(id!=null){const subscriptions=yield sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=yield sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}})}function createCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({address,config,dispatch,state}){var _b,_c,_d;if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const upAddress=yield sdk.addresses.update(
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=void 0,exports.saveCustomerUser=saveCustomerUser,exports.setCustomerErrors=setCustomerErrors,exports.setCustomerEmail=setCustomerEmail,exports.getCustomerAddresses=getCustomerAddresses,exports.deleteCustomerAddress=deleteCustomerAddress,exports.getCustomerPaymentSources=getCustomerPaymentSources,exports.getCustomerOrders=getCustomerOrders,exports.getCustomerSubscriptions=getCustomerSubscriptions,exports.createCustomerAddress=createCustomerAddress,exports.getCustomerPayments=getCustomerPayments,exports.getCustomerInfo=getCustomerInfo,exports.setResourceTrigger=setResourceTrigger;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),jwt_1=require("../utils/jwt"),getCustomerIdByToken_1=require("../utils/getCustomerIdByToken"),triggerAttributeHelper_1=require("../utils/triggerAttributeHelper"),addressesManager_1=require("../utils/addressesManager");function saveCustomerUser(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}function getCustomerAddresses(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,isOrderAvailable}){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}function deleteCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{yield(0,getSdk_1.default)(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}})}function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}function getCustomerOrders(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const orders=yield(0,getSdk_1.default)(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}})}function getCustomerSubscriptions(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(id!=null){const subscriptions=yield sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=yield sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}})}function createCustomerAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({address,config,dispatch,state}){var _b,_c,_d;if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),upAddress=yield sdk.addresses.update(addressWithMeta),updatedAddresses=(_b=state?.addresses)===null||_b===void 0?void 0:_b.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(address),newAddress=yield sdk.addresses.create(addressWithMeta);if(!((_c=state?.customers)===null||_c===void 0)&&_c.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_d=state?.customers)===null||_d===void 0?void 0:_d.id),address:sdk.addresses.relationship(newAddress.id)});yield sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}})}function getCustomerPayments(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const payments=yield sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}})}function getCustomerInfo(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=(0,getSdk_1.default)(config),customerId=(0,getCustomerIdByToken_1.getCustomerIdByToken)(config.accessToken);if(customerId){const customers=yield sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}})}function setResourceTrigger(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const params={config,resource,attribute,id};if((yield(0,triggerAttributeHelper_1.triggerAttributeHelper)(params))!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":yield getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":yield getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}}return!1})}exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.billingAddressController=billingAddressController,exports.shippingAddressController=shippingAddressController,exports.countryLockController=countryLockController,exports.invertedAddressesHandler=invertedAddressesHandler,exports.addressesController=addressesController;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),validateFormFields_1=require("./validateFormFields"),AddressReducer_1=require("../reducers/AddressReducer");function billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo=!1,invertAddresses=!1,shipToDifferentAddress,shippingDisable,requiredMetadataFields}){let billingDisable=invertAddresses?!!(!shippingDisable&&shipToDifferentAddress):!(0,isEmpty_1.default)(errors)||(0,isEmpty_1.default)(billing_address);if((0,isEmpty_1.default)(errors)&&!(0,isEmpty_1.default)(billing_address)){let formFields=[...AddressReducer_1.addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formFields=[...formFields,...requiredMetadataFields]),invertAddresses||requiresBillingInfo&&(formFields=[...formFields,"billing_info"]),billingDisable=!!(billing_address&&(0,validateFormFields_1.fieldsExist)(billing_address,formFields))}return billingDisable&&!(0,isEmpty_1.default)(billingAddressId)&&(0,isEmpty_1.default)(billing_address)&&(billingDisable=!1),billingDisable}function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1,requiredMetadataFields}){let shippingDisable=invertAddresses?!(0,isEmpty_1.default)(errors)||(0,isEmpty_1.default)(shipping_address):!!(!billingDisable&&shipToDifferentAddress);if((0,isEmpty_1.default)(errors)&&!(0,isEmpty_1.default)(shipping_address)){let formField=[...AddressReducer_1.addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formField=[...formField,...requiredMetadataFields]),invertAddresses?(requiresBillingInfo&&(formField=[...formField,"billing_info"]),shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address,formField))):shipToDifferentAddress&&(shipping_address==null||delete shipping_address.billing_info,shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address,formField)))}return shippingDisable&&!(0,isEmpty_1.default)(shippingAddressId)&&(0,isEmpty_1.default)(shipping_address)&&(shippingDisable=!1),shippingDisable}function countryLockController({addresses,billing_address,billingAddressId,countryCodeLock,shipToDifferentAddress,shipping_address,shippingAddressId,lineItems}){var _a;if((_a=lineItems?.filter(lineItem=>{var _a2,_b;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.type)!=null&&["skus","bundles"].includes((_b=lineItem?.item)===null||_b===void 0?void 0:_b.type)}))===null||_a===void 0?void 0:_a.every(lineItem=>{var _a2;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.do_not_ship)===!0}))return!1;if(countryCodeLock&&!(0,isEmpty_1.default)(addresses)&&billingAddressId&&!shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===billingAddressId||a?.reference===billingAddressId)&&a?.country_code!==countryCodeLock);if(!(0,isEmpty_1.default)(addressLocked))return!0}if(countryCodeLock&&!(0,isEmpty_1.default)(billing_address)&&!shipToDifferentAddress)return billing_address?.country_code!==countryCodeLock;if(countryCodeLock&&!(0,isEmpty_1.default)(shipping_address)&&shipToDifferentAddress)return shipping_address?.country_code!==countryCodeLock;if(countryCodeLock&&!(0,isEmpty_1.default)(addresses)&&shippingAddressId&&shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===shippingAddressId||a?.reference===shippingAddressId)&&a?.country_code!==countryCodeLock);if(!(0,isEmpty_1.default)(addressLocked))return!0}return!1}function invertedAddressesHandler(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({order,billingAddress,billingAddressId,customerEmail,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk}){var _b,_c,_d;const currentShippingAddressRef=(_b=order?.shipping_address)===null||_b===void 0?void 0:_b.reference,orderAttributes={id:order?.id,_billing_address_clone_id:shippingAddressId,_shipping_address_clone_id:shippingAddressId,customer_email:customerEmail};if(currentShippingAddressRef===shippingAddressId&&(orderAttributes._billing_address_clone_id=(_c=order?.billing_address)===null||_c===void 0?void 0:_c.id,orderAttributes._shipping_address_clone_id=(_d=order?.shipping_address)===null||_d===void 0?void 0:_d.id),shippingAddress!=null&&Object.keys(shippingAddress).length>0){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,orderAttributes._billing_address_same_as_shipping=!0;const hasMetadata=Object.keys(shippingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");shippingAddress.metadata=Object.assign(Object.assign({},shippingAddress.metadata||{}),{[metadataKey]:shippingAddress[key]}),delete shippingAddress[key]});const address=yield sdk.addresses.create(shippingAddress);orderAttributes.shipping_address=sdk.addresses.relationship(address.id)}if(shipToDifferentAddress&&(delete orderAttributes._billing_address_same_as_shipping,billingAddressId&&(orderAttributes._billing_address_clone_id=billingAddressId),billingAddress!=null&&Object.keys(billingAddress).length>0)){delete orderAttributes._billing_address_clone_id;const hasMetadata=Object.keys(billingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");billingAddress.metadata=Object.assign(Object.assign({},billingAddress.metadata||{}),{[metadataKey]:billingAddress[key]}),delete billingAddress[key]});const address=yield sdk.addresses.create(billingAddress);orderAttributes.billing_address=sdk.addresses.relationship(address.id)}return orderAttributes})}function addressesController({billing_address,billingAddressId,shipToDifferentAddress,shipping_address,shippingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo,requiredMetadataFields}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo,requiredMetadataFields}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,requiredMetadataFields});return{billingDisable,shippingDisable}}
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.billingAddressController=billingAddressController,exports.shippingAddressController=shippingAddressController,exports.countryLockController=countryLockController,exports.invertedAddressesHandler=invertedAddressesHandler,exports.addressesController=addressesController,exports.sanitizeMetadataFields=sanitizeMetadataFields;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),validateFormFields_1=require("./validateFormFields"),AddressReducer_1=require("../reducers/AddressReducer");function billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo=!1,invertAddresses=!1,shipToDifferentAddress,shippingDisable,requiredMetadataFields}){let billingDisable=invertAddresses?!!(!shippingDisable&&shipToDifferentAddress):!(0,isEmpty_1.default)(errors)||(0,isEmpty_1.default)(billing_address);if((0,isEmpty_1.default)(errors)&&!(0,isEmpty_1.default)(billing_address)){let formFields=[...AddressReducer_1.addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formFields=[...formFields,...requiredMetadataFields]),invertAddresses||requiresBillingInfo&&(formFields=[...formFields,"billing_info"]),billingDisable=!!(billing_address&&(0,validateFormFields_1.fieldsExist)(billing_address,formFields))}return billingDisable&&!(0,isEmpty_1.default)(billingAddressId)&&(0,isEmpty_1.default)(billing_address)&&(billingDisable=!1),billingDisable}function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1,requiredMetadataFields}){let shippingDisable=invertAddresses?!(0,isEmpty_1.default)(errors)||(0,isEmpty_1.default)(shipping_address):!!(!billingDisable&&shipToDifferentAddress);if((0,isEmpty_1.default)(errors)&&!(0,isEmpty_1.default)(shipping_address)){let formField=[...AddressReducer_1.addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formField=[...formField,...requiredMetadataFields]),invertAddresses?(requiresBillingInfo&&(formField=[...formField,"billing_info"]),shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address,formField))):shipToDifferentAddress&&(shipping_address==null||delete shipping_address.billing_info,shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address,formField)))}return shippingDisable&&!(0,isEmpty_1.default)(shippingAddressId)&&(0,isEmpty_1.default)(shipping_address)&&(shippingDisable=!1),shippingDisable}function countryLockController({addresses,billing_address,billingAddressId,countryCodeLock,shipToDifferentAddress,shipping_address,shippingAddressId,lineItems}){var _a;if((_a=lineItems?.filter(lineItem=>{var _a2,_b;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.type)!=null&&["skus","bundles"].includes((_b=lineItem?.item)===null||_b===void 0?void 0:_b.type)}))===null||_a===void 0?void 0:_a.every(lineItem=>{var _a2;return((_a2=lineItem?.item)===null||_a2===void 0?void 0:_a2.do_not_ship)===!0}))return!1;if(countryCodeLock&&!(0,isEmpty_1.default)(addresses)&&billingAddressId&&!shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===billingAddressId||a?.reference===billingAddressId)&&a?.country_code!==countryCodeLock);if(!(0,isEmpty_1.default)(addressLocked))return!0}if(countryCodeLock&&!(0,isEmpty_1.default)(billing_address)&&!shipToDifferentAddress)return billing_address?.country_code!==countryCodeLock;if(countryCodeLock&&!(0,isEmpty_1.default)(shipping_address)&&shipToDifferentAddress)return shipping_address?.country_code!==countryCodeLock;if(countryCodeLock&&!(0,isEmpty_1.default)(addresses)&&shippingAddressId&&shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===shippingAddressId||a?.reference===shippingAddressId)&&a?.country_code!==countryCodeLock);if(!(0,isEmpty_1.default)(addressLocked))return!0}return!1}function invertedAddressesHandler(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({order,billingAddress,billingAddressId,customerEmail,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk}){var _b,_c,_d;const currentShippingAddressRef=(_b=order?.shipping_address)===null||_b===void 0?void 0:_b.reference,orderAttributes={id:order?.id,_billing_address_clone_id:shippingAddressId,_shipping_address_clone_id:shippingAddressId,customer_email:customerEmail};if(currentShippingAddressRef===shippingAddressId&&(orderAttributes._billing_address_clone_id=(_c=order?.billing_address)===null||_c===void 0?void 0:_c.id,orderAttributes._shipping_address_clone_id=(_d=order?.shipping_address)===null||_d===void 0?void 0:_d.id),shippingAddress!=null&&Object.keys(shippingAddress).length>0&&!shippingAddressId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,orderAttributes._billing_address_same_as_shipping=!0;const hasMetadata=Object.keys(shippingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");shippingAddress.metadata=Object.assign(Object.assign({},shippingAddress.metadata||{}),{[metadataKey]:shippingAddress[key]}),delete shippingAddress[key]});const address=yield sdk.addresses.create(shippingAddress);orderAttributes.shipping_address=sdk.addresses.relationship(address.id)}if(shipToDifferentAddress&&(delete orderAttributes._billing_address_same_as_shipping,billingAddressId&&(orderAttributes._billing_address_clone_id=billingAddressId),billingAddress!=null&&Object.keys(billingAddress).length>0)){delete orderAttributes._billing_address_clone_id;const hasMetadata=Object.keys(billingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");billingAddress.metadata=Object.assign(Object.assign({},billingAddress.metadata||{}),{[metadataKey]:billingAddress[key]}),delete billingAddress[key]});const address=yield sdk.addresses.create(billingAddress);orderAttributes.billing_address=sdk.addresses.relationship(address.id)}return orderAttributes})}function addressesController({billing_address,billingAddressId,shipToDifferentAddress,shipping_address,shippingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo,requiredMetadataFields}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo,requiredMetadataFields}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,requiredMetadataFields});return{billingDisable,shippingDisable}}function sanitizeMetadataFields(address){const hasMetadata=Object.keys(address).filter(key=>!!key.startsWith("metadata_"));return hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");address.metadata=Object.assign(Object.assign({},address.metadata||{}),{[metadataKey]:address[key]}),delete address[key]}),address}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext,{defaultAddressContext}from"../../context/AddressContext";import{useContext,useEffect,useReducer}from"react";import addressReducer,{addressInitialState,setAddressErrors,setCloneAddress,saveAddresses}from"../../reducers/AddressReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";export function AddressesContainer(props){const{children,shipToDifferentAddress=!1,isBusiness,invertAddresses=!1}=props,[state,dispatch]=useReducer(addressReducer,addressInitialState),{order,orderId,updateOrder}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>(dispatch({type:"setShipToDifferentAddress",payload:{shipToDifferentAddress,isBusiness,invertAddresses}}),()=>{dispatch({type:"cleanup",payload:{}})}),[shipToDifferentAddress,isBusiness,invertAddresses]);const contextValue={...state,setAddressErrors:(errors,resource)=>{setAddressErrors({errors,resource,dispatch,currentErrors:state.errors})},setAddress:params=>{defaultAddressContext.setAddress({...params,dispatch})},saveAddresses:async
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext,{defaultAddressContext}from"../../context/AddressContext";import{useContext,useEffect,useReducer}from"react";import addressReducer,{addressInitialState,setAddressErrors,setCloneAddress,saveAddresses}from"../../reducers/AddressReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";export function AddressesContainer(props){const{children,shipToDifferentAddress=!1,isBusiness,invertAddresses=!1}=props,[state,dispatch]=useReducer(addressReducer,addressInitialState),{order,orderId,updateOrder}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>(dispatch({type:"setShipToDifferentAddress",payload:{shipToDifferentAddress,isBusiness,invertAddresses}}),()=>{dispatch({type:"cleanup",payload:{}})}),[shipToDifferentAddress,isBusiness,invertAddresses]);const contextValue={...state,setAddressErrors:(errors,resource)=>{setAddressErrors({errors,resource,dispatch,currentErrors:state.errors})},setAddress:params=>{defaultAddressContext.setAddress({...params,dispatch})},saveAddresses:async params=>await saveAddresses({config,dispatch,updateOrder,order,orderId,state,...params}),setCloneAddress:(id,resource)=>{setCloneAddress(id,resource,dispatch)}};return _jsx(AddressesContext.Provider,{value:contextValue,children})}export default AddressesContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useState}from"react";import Parent from"../utils/Parent";import AddressContext from"../../context/AddressContext";import{countryLockController,addressesController}from"../../utils/addressesManager";import OrderContext from"../../context/OrderContext";import CustomerContext from"../../context/CustomerContext";import isFunction from"lodash/isFunction";import{validateValue}from"../../utils/validateFormFields";export function SaveAddressesButton(props){const{children,label="Continue to delivery",resource,disabled=!1,addressId,requiredMetadataFields,onClick,...p}=props,{errors,billing_address:billingAddress,shipToDifferentAddress,shipping_address:shippingAddress,saveAddresses,billingAddressId,shippingAddressId,invertAddresses}=useContext(AddressContext),{order}=useContext(OrderContext),{customerEmail:email,addresses,isGuest,createCustomerAddress}=useContext(CustomerContext),[forceDisable,setForceDisable]=useState(disabled);let customerEmail=(isGuest===!0||typeof isGuest>"u")&&!order?.customer_email;if(email!=null&&email!==""){const isValidEmail=validateValue(email,"customer_email","email","orders");customerEmail=Object.keys(isValidEmail).length>0}const shippingAddressCleaned=Object.keys(shippingAddress??{}).reduce((acc,key)=>({...acc,[key.replace("shipping_address_","")]:shippingAddress[key].value}),{}),{billingDisable,shippingDisable}=addressesController({invertAddresses,requiresBillingInfo:order?.requires_billing_info,billing_address:billingAddress,shipping_address:shippingAddressCleaned,shipToDifferentAddress,shippingAddressId,billingAddressId,errors,requiredMetadataFields}),countryLockDisable=countryLockController({countryCodeLock:order?.shipping_country_code_lock,addresses,shipToDifferentAddress,billingAddressId,billing_address:billingAddress,shipping_address:shippingAddress,shippingAddressId,lineItems:order?.line_items}),disable=disabled||customerEmail||billingDisable||(invertAddresses&&shippingAddressId?!1:shippingDisable)||countryLockDisable,handleClick=async()=>{if(errors&&Object.keys(errors).length===0&&!disable){let response={success:!1};
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useState}from"react";import Parent from"../utils/Parent";import AddressContext from"../../context/AddressContext";import{countryLockController,addressesController}from"../../utils/addressesManager";import OrderContext from"../../context/OrderContext";import CustomerContext from"../../context/CustomerContext";import isFunction from"lodash/isFunction";import{validateValue}from"../../utils/validateFormFields";export function SaveAddressesButton(props){const{children,label="Continue to delivery",resource,disabled=!1,addressId,requiredMetadataFields,onClick,...p}=props,{errors,billing_address:billingAddress,shipToDifferentAddress,shipping_address:shippingAddress,saveAddresses,billingAddressId,shippingAddressId,invertAddresses}=useContext(AddressContext),{order}=useContext(OrderContext),{customerEmail:email,addresses,isGuest,createCustomerAddress}=useContext(CustomerContext),[forceDisable,setForceDisable]=useState(disabled);let customerEmail=(isGuest===!0||typeof isGuest>"u")&&!order?.customer_email;if(email!=null&&email!==""){const isValidEmail=validateValue(email,"customer_email","email","orders");customerEmail=Object.keys(isValidEmail).length>0}const shippingAddressCleaned=Object.keys(shippingAddress??{}).reduce((acc,key)=>({...acc,[key.replace("shipping_address_","")]:shippingAddress[key].value}),{}),{billingDisable,shippingDisable}=addressesController({invertAddresses,requiresBillingInfo:order?.requires_billing_info,billing_address:billingAddress,shipping_address:shippingAddressCleaned,shipToDifferentAddress,shippingAddressId,billingAddressId,errors,requiredMetadataFields}),countryLockDisable=countryLockController({countryCodeLock:order?.shipping_country_code_lock,addresses,shipToDifferentAddress,billingAddressId,billing_address:billingAddress,shipping_address:shippingAddress,shippingAddressId,lineItems:order?.line_items}),disable=disabled||customerEmail||billingDisable||(invertAddresses&&shippingAddressId?!1:shippingDisable)||countryLockDisable,handleClick=async()=>{if(errors&&Object.keys(errors).length===0&&!disable){let response={success:!1};switch(setForceDisable(!0),!0){case(order!=null&&addressId!=null&&createCustomerAddress!=null&&saveAddresses!=null):response=await saveAddresses({customerEmail:email,customerAddress:{resource:invertAddresses?"shipping_address":"billing_address",id:addressId}});break;case(order!=null&&saveAddresses!=null):response=await saveAddresses({customerEmail:email});break;case createCustomerAddress!=null:const address=invertAddresses?{...shippingAddress}:{...billingAddress};addressId&&(address.id=addressId),createCustomerAddress(address),response={success:!0};break}setForceDisable(!1),onClick&&response.success&&onClick(response)}},parentProps={...p,label,resource,handleClick,disabled:disable};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{type:"button",disabled:disable||forceDisable,onClick:()=>{handleClick()},...p,children:isFunction(label)?label():label})}export default SaveAddressesButton;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import promisify from"../../utils/promisify";const defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};export function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}={...defaultConfig,...config},[loadBraintree,setLoadBraintree]=useState(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),ref=useRef(null),handleSubmitForm=async({event,hostedFieldsInstance,threeDSInstance})=>{const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=await promisify(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:order?.customer_email??"",billingAddress:{givenName:billingAddress?.first_name??"",surname:billingAddress?.last_name??"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:billingAddress?.zip_code??"",region:billingAddress?.state_code,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=await threeDSInstance.verifyCard(verifyCardOptions);
|
|
2
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";import promisify from"../../utils/promisify";const defaultConfig={styles:{input:{"font-size":"16px",color:"#3A3A3A"},".number":{"font-family":"monospace"},":focus":{color:"blue"},".valid":{color:"green"},".invalid":{color:"red"},"@media screen and (max-width: 700px)":{input:{"font-size":"14px"}}},fields:{number:{label:"Card Number",selector:"#card-number",placeholder:"4111 1111 1111 1111"},cvv:{label:"CVV",selector:"#cvv",placeholder:"123"},expirationDate:{label:"Expiration Date",selector:"#expiration-date",placeholder:"10/2022"}},submitLabel:"Set payment method"};export function BraintreePayment({authorization,config,templateCustomerSaveToWallet}){const{fields,styles,containerClassName,cardContainerClassName,fieldsContainerClassName,expDateContainerClassName,fieldLabelClassName,cvvContainerClassName,inputWrapperClassName,cardDetailsContainerClassName}={...defaultConfig,...config},[loadBraintree,setLoadBraintree]=useState(!1),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),ref=useRef(null),handleSubmitForm=async({event,hostedFieldsInstance,threeDSInstance})=>{const savePaymentSourceToCustomerWallet=event?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),hostedFieldsInstance)try{const payload=await promisify(hostedFieldsInstance).then(payload2=>payload2),billingAddress=order?.billing_address,verifyCardOptions={nonce:payload.nonce,bin:payload.details.bin,amount:`${order?.total_amount_with_taxes_float}`,email:order?.customer_email??"",billingAddress:{givenName:billingAddress?.first_name??"",surname:billingAddress?.last_name??"",phoneNumber:billingAddress?.phone,streetAddress:billingAddress?.line_1,countryCodeAlpha2:billingAddress?.country_code,postalCode:billingAddress?.zip_code??"",region:billingAddress?.state_code,locality:billingAddress?.city},onLookupComplete:(_data,next)=>{next()}},response=await threeDSInstance.verifyCard(verifyCardOptions),validStatus=response?.liabilityShiftPossible===!0&&response?.liabilityShifted===!0;if(console.log("validStatus",validStatus),validStatus&&paymentSource!=null)return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"braintree_payments",attributes:{payment_method_nonce:response.nonce,options:{id:response.nonce,card:{last4:response.details.lastFour,exp_year:response.details.expirationYear,exp_month:response.details.expirationMonth,brand:response.details.cardType.toLowerCase()}}}}),!0;throw new Error(`3D Secure authentication failed - ${response?.threeDSecureInfo?.status}`)}catch(error){return console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),!1}return!1};return useEffect(()=>{if(!ref&&authorization&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),authorization&&!loadBraintree&&!isEmpty(window)){const braintreeClient=require("braintree-web/client"),hostedFields=require("braintree-web/hosted-fields"),threeDSecure=require("braintree-web/three-d-secure");braintreeClient.create({authorization},(clientErr,clientInstance)=>{if(clientErr){console.error(clientErr);return}hostedFields.create({client:clientInstance,fields,styles},(hostedFieldsErr,hostedFieldsInstance)=>{if(hostedFieldsErr){console.error(hostedFieldsErr);return}setLoadBraintree(!0),threeDSecure.create({authorization,version:2},(threeDSecureErr,threeDSInstance)=>{threeDSecureErr&&(console.error("3DSecure error",threeDSecureErr),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:threeDSecureErr.message}])),ref.current&&(ref.current.onsubmit=async paymentSource2=>await handleSubmitForm({event:ref.current,hostedFieldsInstance,threeDSInstance,paymentSource:paymentSource2}),setPaymentRef({ref}))})})})}return()=>{setPaymentRef({ref:{current:null}}),setLoadBraintree(!1)}},[authorization,ref]),!authorization&&!loadBraintree?null:_jsx("div",{className:containerClassName,children:_jsxs("form",{ref,id:"braintree-form",onSubmit:handleSubmitForm,className:containerClassName,children:[_jsxs("div",{className:fieldsContainerClassName,children:[_jsxs("div",{className:cardContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"card-number",children:fields?.number?.label}),_jsx("div",{className:inputWrapperClassName,id:"card-number"})]}),_jsxs("div",{className:cardDetailsContainerClassName,children:[_jsxs("div",{className:expDateContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"expiration-date",children:fields?.expirationDate?.label}),_jsx("div",{className:inputWrapperClassName,id:"expiration-date"})]}),_jsxs("div",{className:cvvContainerClassName,children:[_jsx("label",{className:fieldLabelClassName,htmlFor:"cvv",children:fields?.cvv?.label}),_jsx("div",{className:inputWrapperClassName,id:"cvv"})]})]})]}),_jsx("div",{className:fieldsContainerClassName,children:templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})})]})})}export default BraintreePayment;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import { type AddressState, setAddress, type AddressResource, type saveAddresses } from '../reducers/AddressReducer';
|
|
1
|
+
import { type AddressState, setAddress, type AddressResource, type saveAddresses, ICustomerAddress } from '../reducers/AddressReducer';
|
|
2
2
|
import { type BaseError } from '../typings/errors';
|
|
3
3
|
type DefaultContext = {
|
|
4
|
-
saveAddresses?: (
|
|
4
|
+
saveAddresses?: (params: {
|
|
5
|
+
customerEmail?: string;
|
|
6
|
+
customerAddress?: ICustomerAddress;
|
|
7
|
+
}) => ReturnType<typeof saveAddresses>;
|
|
5
8
|
setCloneAddress: (id: string, resource: AddressResource) => void;
|
|
6
9
|
setAddress: typeof setAddress;
|
|
7
10
|
setAddressErrors: (errors: BaseError[], resource: AddressResource) => void;
|
|
@@ -56,6 +56,10 @@ export declare const setAddressErrors: SetAddressErrors;
|
|
|
56
56
|
export declare function setAddress<V extends AddressSchema>({ values, resource, dispatch }: SetAddressParams<V>): void;
|
|
57
57
|
type SetCloneAddress = (id: string, resource: AddressResource, dispatch: Dispatch<AddressAction>) => void;
|
|
58
58
|
export declare const setCloneAddress: SetCloneAddress;
|
|
59
|
+
export interface ICustomerAddress {
|
|
60
|
+
id: string | undefined;
|
|
61
|
+
resource: AddressResource;
|
|
62
|
+
}
|
|
59
63
|
interface TSaveAddressesParams {
|
|
60
64
|
orderId?: string;
|
|
61
65
|
order?: Order | null;
|
|
@@ -65,8 +69,9 @@ interface TSaveAddressesParams {
|
|
|
65
69
|
dispatch: Dispatch<AddressAction>;
|
|
66
70
|
getCustomerAddresses?: () => Promise<void>;
|
|
67
71
|
customerEmail?: string;
|
|
72
|
+
customerAddress?: ICustomerAddress;
|
|
68
73
|
}
|
|
69
|
-
export declare function saveAddresses({ config, updateOrder, order, state, customerEmail }: TSaveAddressesParams): Promise<{
|
|
74
|
+
export declare function saveAddresses({ config, updateOrder, order, state, customerEmail, customerAddress }: TSaveAddressesParams): Promise<{
|
|
70
75
|
success: boolean;
|
|
71
76
|
order?: Order;
|
|
72
77
|
error?: unknown;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import camelCase from"lodash/camelCase";import{invertedAddressesHandler}from"../utils/addressesManager";import{formCleaner}from"../utils/formCleaner";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddress,shipping_address:shippingAddress,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config);if(order){let orderAttributes=null;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import{formCleaner}from"../utils/formCleaner";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddress,shipping_address:shippingAddress,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress),address=await sdk.addresses.create(billingAddressWithMeta);orderAttributes.billing_address=sdk.addresses.relationship(address.id)}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=sanitizeMetadataFields(shippingAddress),address=await sdk.addresses.create(shippingAddressWithMeta);orderAttributes.shipping_address=sdk.addresses.relationship(address.id)}}if(orderAttributes!=null&&updateOrder)return{success:!0,order:(await updateOrder({id:order.id,attributes:orderAttributes}))?.order}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default addressReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const upAddress=await sdk.addresses.update(
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{jwt}from"../utils/jwt";import{getCustomerIdByToken}from"../utils/getCustomerIdByToken";import{triggerAttributeHelper}from"../utils/triggerAttributeHelper";import{sanitizeMetadataFields}from"../utils/addressesManager";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.address.reference==null&&(customerAddress.address.reference=customerAddress.id),customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params,payments=order?.available_customer_payment_sources;payments!=null&&payments.length>0&&dispatch&&dispatch({type:"setPayments",payload:{payments}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const orders=await getSdk(config).customers.orders(owner.id,{filters:{status_not_in:"draft,pending"},pageSize,pageNumber});dispatch({type:"setOrders",payload:{orders}})}}}export async function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(id!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_id_eq:id},include:["authorizations"],pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=await sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const addressWithMeta=sanitizeMetadataFields(address),upAddress=await sdk.addresses.update(addressWithMeta),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const addressWithMeta=sanitizeMetadataFields(address),newAddress=await sdk.addresses.create(addressWithMeta);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){if(config?.accessToken!=null&&dispatch!=null){const sdk=getSdk(config),{owner}=jwt(config.accessToken);if(owner?.id){const payments=await sdk.customer_payment_sources.list({include:["payment_source"],pageNumber,pageSize});dispatch({type:"setPayments",payload:{payments}})}}}export async function getCustomerInfo({config,dispatch}){if(config.accessToken&&dispatch!=null){const sdk=getSdk(config),customerId=getCustomerIdByToken(config.accessToken);if(customerId){const customers=await sdk.customers.retrieve(customerId),customerEmail=customers.email;dispatch({type:"setCustomers",payload:{customers,customerEmail}})}}}export async function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id&&await triggerAttributeHelper({config,resource,attribute,id})!=null&&dispatch!=null&&reloadList){switch(resource){case"orders":await getCustomerOrders({config,dispatch,pageSize,pageNumber});break;case"order_subscriptions":await getCustomerSubscriptions({config,dispatch,pageSize,pageNumber});break;default:return!1}return!0}}return!1}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import isEmpty from"lodash/isEmpty";import{fieldsExist}from"./validateFormFields";import{addressFields}from"../reducers/AddressReducer";export function billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo=!1,invertAddresses=!1,shipToDifferentAddress,shippingDisable,requiredMetadataFields}){let billingDisable=invertAddresses?!!(!shippingDisable&&shipToDifferentAddress):!isEmpty(errors)||isEmpty(billing_address);if(isEmpty(errors)&&!isEmpty(billing_address)){let formFields=[...addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formFields=[...formFields,...requiredMetadataFields]),invertAddresses?billingDisable=!!(billing_address&&fieldsExist(billing_address,formFields)):(requiresBillingInfo&&(formFields=[...formFields,"billing_info"]),billingDisable=!!(billing_address&&fieldsExist(billing_address,formFields)))}return billingDisable&&!isEmpty(billingAddressId)&&isEmpty(billing_address)&&(billingDisable=!1),billingDisable}export function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1,requiredMetadataFields}){let shippingDisable=invertAddresses?!isEmpty(errors)||isEmpty(shipping_address):!!(!billingDisable&&shipToDifferentAddress);if(isEmpty(errors)&&!isEmpty(shipping_address)){let formField=[...addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formField=[...formField,...requiredMetadataFields]),invertAddresses?(requiresBillingInfo&&(formField=[...formField,"billing_info"]),shippingDisable=!!(shipping_address&&fieldsExist(shipping_address,formField))):shipToDifferentAddress&&(delete shipping_address?.billing_info,shippingDisable=!!(shipping_address&&fieldsExist(shipping_address,formField)))}return shippingDisable&&!isEmpty(shippingAddressId)&&isEmpty(shipping_address)&&(shippingDisable=!1),shippingDisable}export function countryLockController({addresses,billing_address,billingAddressId,countryCodeLock,shipToDifferentAddress,shipping_address,shippingAddressId,lineItems}){if(lineItems?.filter(lineItem=>lineItem?.item?.type!=null&&["skus","bundles"].includes(lineItem?.item?.type))?.every(lineItem=>lineItem?.item?.do_not_ship===!0))return!1;if(countryCodeLock&&!isEmpty(addresses)&&billingAddressId&&!shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===billingAddressId||a?.reference===billingAddressId)&&a?.country_code!==countryCodeLock);if(!isEmpty(addressLocked))return!0}if(countryCodeLock&&!isEmpty(billing_address)&&!shipToDifferentAddress)return billing_address?.country_code!==countryCodeLock;if(countryCodeLock&&!isEmpty(shipping_address)&&shipToDifferentAddress)return shipping_address?.country_code!==countryCodeLock;if(countryCodeLock&&!isEmpty(addresses)&&shippingAddressId&&shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===shippingAddressId||a?.reference===shippingAddressId)&&a?.country_code!==countryCodeLock);if(!isEmpty(addressLocked))return!0}return!1}export async function invertedAddressesHandler({order,billingAddress,billingAddressId,customerEmail,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk}){const currentShippingAddressRef=order?.shipping_address?.reference,orderAttributes={id:order?.id,_billing_address_clone_id:shippingAddressId,_shipping_address_clone_id:shippingAddressId,customer_email:customerEmail};if(currentShippingAddressRef===shippingAddressId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),shippingAddress!=null&&Object.keys(shippingAddress).length>0){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,orderAttributes._billing_address_same_as_shipping=!0;const hasMetadata=Object.keys(shippingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");shippingAddress.metadata={...shippingAddress.metadata||{},[metadataKey]:shippingAddress[key]},delete shippingAddress[key]});const address=await sdk.addresses.create(shippingAddress);orderAttributes.shipping_address=sdk.addresses.relationship(address.id)}if(shipToDifferentAddress&&(delete orderAttributes._billing_address_same_as_shipping,billingAddressId&&(orderAttributes._billing_address_clone_id=billingAddressId),billingAddress!=null&&Object.keys(billingAddress).length>0)){delete orderAttributes._billing_address_clone_id;const hasMetadata=Object.keys(billingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");billingAddress.metadata={...billingAddress.metadata||{},[metadataKey]:billingAddress[key]},delete billingAddress[key]});const address=await sdk.addresses.create(billingAddress);orderAttributes.billing_address=sdk.addresses.relationship(address.id)}return orderAttributes}export function addressesController({billing_address,billingAddressId,shipToDifferentAddress,shipping_address,shippingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo,requiredMetadataFields}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo,requiredMetadataFields}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,requiredMetadataFields});return{billingDisable,shippingDisable}}
|
|
2
|
+
import isEmpty from"lodash/isEmpty";import{fieldsExist}from"./validateFormFields";import{addressFields}from"../reducers/AddressReducer";export function billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo=!1,invertAddresses=!1,shipToDifferentAddress,shippingDisable,requiredMetadataFields}){let billingDisable=invertAddresses?!!(!shippingDisable&&shipToDifferentAddress):!isEmpty(errors)||isEmpty(billing_address);if(isEmpty(errors)&&!isEmpty(billing_address)){let formFields=[...addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formFields=[...formFields,...requiredMetadataFields]),invertAddresses?billingDisable=!!(billing_address&&fieldsExist(billing_address,formFields)):(requiresBillingInfo&&(formFields=[...formFields,"billing_info"]),billingDisable=!!(billing_address&&fieldsExist(billing_address,formFields)))}return billingDisable&&!isEmpty(billingAddressId)&&isEmpty(billing_address)&&(billingDisable=!1),billingDisable}export function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1,requiredMetadataFields}){let shippingDisable=invertAddresses?!isEmpty(errors)||isEmpty(shipping_address):!!(!billingDisable&&shipToDifferentAddress);if(isEmpty(errors)&&!isEmpty(shipping_address)){let formField=[...addressFields];requiredMetadataFields!=null&&requiredMetadataFields.length>0&&(formField=[...formField,...requiredMetadataFields]),invertAddresses?(requiresBillingInfo&&(formField=[...formField,"billing_info"]),shippingDisable=!!(shipping_address&&fieldsExist(shipping_address,formField))):shipToDifferentAddress&&(delete shipping_address?.billing_info,shippingDisable=!!(shipping_address&&fieldsExist(shipping_address,formField)))}return shippingDisable&&!isEmpty(shippingAddressId)&&isEmpty(shipping_address)&&(shippingDisable=!1),shippingDisable}export function countryLockController({addresses,billing_address,billingAddressId,countryCodeLock,shipToDifferentAddress,shipping_address,shippingAddressId,lineItems}){if(lineItems?.filter(lineItem=>lineItem?.item?.type!=null&&["skus","bundles"].includes(lineItem?.item?.type))?.every(lineItem=>lineItem?.item?.do_not_ship===!0))return!1;if(countryCodeLock&&!isEmpty(addresses)&&billingAddressId&&!shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===billingAddressId||a?.reference===billingAddressId)&&a?.country_code!==countryCodeLock);if(!isEmpty(addressLocked))return!0}if(countryCodeLock&&!isEmpty(billing_address)&&!shipToDifferentAddress)return billing_address?.country_code!==countryCodeLock;if(countryCodeLock&&!isEmpty(shipping_address)&&shipToDifferentAddress)return shipping_address?.country_code!==countryCodeLock;if(countryCodeLock&&!isEmpty(addresses)&&shippingAddressId&&shipToDifferentAddress){const addressLocked=addresses?.find(a=>(a?.id===shippingAddressId||a?.reference===shippingAddressId)&&a?.country_code!==countryCodeLock);if(!isEmpty(addressLocked))return!0}return!1}export async function invertedAddressesHandler({order,billingAddress,billingAddressId,customerEmail,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk}){const currentShippingAddressRef=order?.shipping_address?.reference,orderAttributes={id:order?.id,_billing_address_clone_id:shippingAddressId,_shipping_address_clone_id:shippingAddressId,customer_email:customerEmail};if(currentShippingAddressRef===shippingAddressId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),shippingAddress!=null&&Object.keys(shippingAddress).length>0&&!shippingAddressId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,orderAttributes._billing_address_same_as_shipping=!0;const hasMetadata=Object.keys(shippingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");shippingAddress.metadata={...shippingAddress.metadata||{},[metadataKey]:shippingAddress[key]},delete shippingAddress[key]});const address=await sdk.addresses.create(shippingAddress);orderAttributes.shipping_address=sdk.addresses.relationship(address.id)}if(shipToDifferentAddress&&(delete orderAttributes._billing_address_same_as_shipping,billingAddressId&&(orderAttributes._billing_address_clone_id=billingAddressId),billingAddress!=null&&Object.keys(billingAddress).length>0)){delete orderAttributes._billing_address_clone_id;const hasMetadata=Object.keys(billingAddress).filter(key=>!!key.startsWith("metadata_"));hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");billingAddress.metadata={...billingAddress.metadata||{},[metadataKey]:billingAddress[key]},delete billingAddress[key]});const address=await sdk.addresses.create(billingAddress);orderAttributes.billing_address=sdk.addresses.relationship(address.id)}return orderAttributes}export function addressesController({billing_address,billingAddressId,shipToDifferentAddress,shipping_address,shippingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo,requiredMetadataFields}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses,requiredMetadataFields});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo,requiredMetadataFields}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,requiredMetadataFields});return{billingDisable,shippingDisable}}export function sanitizeMetadataFields(address){const hasMetadata=Object.keys(address).filter(key=>!!key.startsWith("metadata_"));return hasMetadata?.length>0&&hasMetadata.forEach(key=>{const metadataKey=key.replace("metadata_","");address.metadata={...address.metadata||{},[metadataKey]:address[key]},delete address[key]}),address}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commercelayer/react-components",
|
|
3
|
-
"version": "4.15.9
|
|
3
|
+
"version": "4.15.9",
|
|
4
4
|
"description": "The Official Commerce Layer React Components",
|
|
5
5
|
"main": "lib/cjs/index.js",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -167,13 +167,13 @@
|
|
|
167
167
|
"dependencies": {
|
|
168
168
|
"@adyen/adyen-web": "^5.66.1",
|
|
169
169
|
"@commercelayer/organization-config": "^1.4.8",
|
|
170
|
-
"@commercelayer/sdk": "6.
|
|
171
|
-
"@stripe/react-stripe-js": "^2.
|
|
172
|
-
"@stripe/stripe-js": "^4.
|
|
170
|
+
"@commercelayer/sdk": "6.13.0",
|
|
171
|
+
"@stripe/react-stripe-js": "^2.8.0",
|
|
172
|
+
"@stripe/stripe-js": "^4.3.0",
|
|
173
173
|
"@tanstack/react-table": "^8.17.3",
|
|
174
174
|
"@types/iframe-resizer": "^3.5.13",
|
|
175
175
|
"axios": "^1.7.3",
|
|
176
|
-
"braintree-web": "^3.
|
|
176
|
+
"braintree-web": "^3.106.0",
|
|
177
177
|
"frames-react": "^1.1.2",
|
|
178
178
|
"iframe-resizer": "^4.4.5",
|
|
179
179
|
"jwt-decode": "^4.0.0",
|
|
@@ -183,19 +183,19 @@
|
|
|
183
183
|
"devDependencies": {
|
|
184
184
|
"@commercelayer/js-auth": "^6.3.1",
|
|
185
185
|
"@faker-js/faker": "^8.4.0",
|
|
186
|
-
"@playwright/test": "^1.
|
|
186
|
+
"@playwright/test": "^1.46.1",
|
|
187
187
|
"@testing-library/dom": "^10.4.0",
|
|
188
188
|
"@testing-library/react": "^16.0.0",
|
|
189
189
|
"@types/braintree-web": "^3.96.12",
|
|
190
190
|
"@types/lodash": "^4.17.7",
|
|
191
|
-
"@types/node": "^22.
|
|
191
|
+
"@types/node": "^22.5.0",
|
|
192
192
|
"@types/prop-types": "^15.7.12",
|
|
193
|
-
"@types/react": "^18.3.
|
|
193
|
+
"@types/react": "^18.3.4",
|
|
194
194
|
"@types/react-test-renderer": "^18.0.7",
|
|
195
195
|
"@types/react-window": "^1.8.8",
|
|
196
196
|
"@vitejs/plugin-react": "^4.3.1",
|
|
197
197
|
"@vitest/coverage-v8": "^2.0.5",
|
|
198
|
-
"eslint": "~
|
|
198
|
+
"eslint": "~8.57.0",
|
|
199
199
|
"jsdom": "^24.1.1",
|
|
200
200
|
"minimize-js": "^1.4.0",
|
|
201
201
|
"msw": "^2.3.5",
|
|
@@ -205,8 +205,8 @@
|
|
|
205
205
|
"tsc-alias": "^1.8.8",
|
|
206
206
|
"tslib": "^2.6.3",
|
|
207
207
|
"typescript": "^5.5.4",
|
|
208
|
-
"vite": "^5.
|
|
209
|
-
"vite-tsconfig-paths": "^
|
|
208
|
+
"vite": "^5.4.2",
|
|
209
|
+
"vite-tsconfig-paths": "^5.0.1",
|
|
210
210
|
"vitest": "^2.0.5"
|
|
211
211
|
},
|
|
212
212
|
"peerDependencies": {
|