@commercelayer/react-components 4.15.9-beta.2 → 4.15.9-beta.3

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.
@@ -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:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,AddressReducer_1.saveAddresses)({config,dispatch,updateOrder,order,orderId,state,customerEmail})}),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;
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};if(setForceDisable(!0),order&&saveAddresses!=null)response=yield saveAddresses(email);else if(createCustomerAddress){const address=invertAddresses?Object.assign({},shippingAddress):Object.assign({},billingAddress);addressId&&(address.id=addressId),createCustomerAddress(address),response={success:!0}}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;
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):console.log("----- createCustomerAddress and saveAddresses with order ----"),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:console.log("----- createCustomerAddress ----");const address=invertAddresses?Object.assign({},shippingAddress):Object.assign({},billingAddress);addressId&&(address.id=addressId),console.log("address",address),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,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?: (customerEmail?: string) => ReturnType<typeof 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:billingAddressId,_shipping_address_clone_id:billingAddressId,customer_email:customerEmail},currentBillingAddressRef===billingAddressId&&(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){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);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)}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressId&&(orderAttributes._shipping_address_clone_id=shippingAddressId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;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(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;
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(console.log("billingAddressCloneId",billingAddressCloneId),console.log("shippingAddressCloneId",shippingAddressCloneId),console.log("invertAddresses",invertAddresses),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(address),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 newAddress=yield sdk.addresses.create(address);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;
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;
@@ -60,4 +60,5 @@ export declare function addressesController({ billing_address, billingAddressId,
60
60
  billingDisable: boolean;
61
61
  shippingDisable: boolean;
62
62
  };
63
+ export declare function sanitizeMetadataFields(address: AddressCreate): AddressCreate;
63
64
  export {};
@@ -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(console.log("--- shippingAddress ---",shippingAddress),console.log("orderAttributes",orderAttributes),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 customerEmail=>await saveAddresses({config,dispatch,updateOrder,order,orderId,state,customerEmail}),setCloneAddress:(id,resource)=>{setCloneAddress(id,resource,dispatch)}};return _jsx(AddressesContext.Provider,{value:contextValue,children})}export default AddressesContainer;
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};if(setForceDisable(!0),order&&saveAddresses!=null)response=await saveAddresses(email);else if(createCustomerAddress){const address=invertAddresses?{...shippingAddress}:{...billingAddress};addressId&&(address.id=addressId),createCustomerAddress(address),response={success:!0}}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;
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):console.log("----- createCustomerAddress and saveAddresses with order ----"),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:console.log("----- createCustomerAddress ----");const address=invertAddresses?{...shippingAddress}:{...billingAddress};addressId&&(address.id=addressId),console.log("address",address),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,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?: (customerEmail?: string) => ReturnType<typeof 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:billingAddressId,_shipping_address_clone_id:billingAddressId,customer_email:customerEmail},currentBillingAddressRef===billingAddressId&&(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){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);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)}if(shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressId&&(orderAttributes._shipping_address_clone_id=shippingAddressId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;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(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;
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(console.log("billingAddressCloneId",billingAddressCloneId),console.log("shippingAddressCloneId",shippingAddressCloneId),console.log("invertAddresses",invertAddresses),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(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch,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;
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;
@@ -60,4 +60,5 @@ export declare function addressesController({ billing_address, billingAddressId,
60
60
  billingDisable: boolean;
61
61
  shippingDisable: boolean;
62
62
  };
63
+ export declare function sanitizeMetadataFields(address: AddressCreate): AddressCreate;
63
64
  export {};
@@ -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(console.log("--- shippingAddress ---",shippingAddress),console.log("orderAttributes",orderAttributes),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-beta.2",
3
+ "version": "4.15.9-beta.3",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",