@commercelayer/react-components 4.9.0 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/lib/cjs/components/addresses/BillingAddressForm.d.ts +5 -0
  2. package/lib/cjs/components/addresses/BillingAddressForm.js +1 -1
  3. package/lib/cjs/components/addresses/ShippingAddressForm.d.ts +5 -0
  4. package/lib/cjs/components/addresses/ShippingAddressForm.js +1 -1
  5. package/lib/cjs/components/customers/CustomerContainer.js +1 -1
  6. package/lib/cjs/components/orders/OrderList.d.ts +3 -3
  7. package/lib/cjs/components/orders/OrderList.js +1 -1
  8. package/lib/cjs/index.d.ts +1 -0
  9. package/lib/cjs/index.js +1 -1
  10. package/lib/cjs/reducers/AddressReducer.d.ts +9 -1
  11. package/lib/cjs/reducers/CustomerReducer.d.ts +3 -3
  12. package/lib/cjs/reducers/CustomerReducer.js +1 -1
  13. package/lib/cjs/utils/addressesManager.js +1 -1
  14. package/lib/cjs/utils/validateFormFields.d.ts +1 -2
  15. package/lib/cjs/utils/validateFormFields.js +1 -1
  16. package/lib/esm/components/addresses/BillingAddressForm.d.ts +5 -0
  17. package/lib/esm/components/addresses/BillingAddressForm.js +1 -1
  18. package/lib/esm/components/addresses/ShippingAddressForm.d.ts +5 -0
  19. package/lib/esm/components/addresses/ShippingAddressForm.js +1 -1
  20. package/lib/esm/components/customers/CustomerContainer.js +1 -1
  21. package/lib/esm/components/orders/OrderList.d.ts +3 -3
  22. package/lib/esm/components/orders/OrderList.js +1 -1
  23. package/lib/esm/index.d.ts +1 -0
  24. package/lib/esm/index.js +1 -1
  25. package/lib/esm/reducers/AddressReducer.d.ts +9 -1
  26. package/lib/esm/reducers/CustomerReducer.d.ts +3 -3
  27. package/lib/esm/reducers/CustomerReducer.js +1 -1
  28. package/lib/esm/utils/addressesManager.js +1 -1
  29. package/lib/esm/utils/validateFormFields.d.ts +1 -2
  30. package/lib/esm/utils/validateFormFields.js +1 -1
  31. package/package.json +3 -3
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
+ import { type CustomFieldMessageError } from '../../reducers/AddressReducer';
2
3
  type Props = {
3
4
  children: ReactNode;
4
5
  /**
@@ -9,6 +10,10 @@ type Props = {
9
10
  * Define children input and select classnames assigned in case of validation error.
10
11
  */
11
12
  errorClassName?: string;
13
+ /**
14
+ * Callback to customize the error message for a specific field. Called for each error in the form.
15
+ */
16
+ customFieldMessageError?: CustomFieldMessageError;
12
17
  } & Omit<JSX.IntrinsicElements['form'], 'onSubmit'>;
13
18
  /**
14
19
  * Form container for creating or editing an order related billing address or a customer address, depending on the context in use.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BillingAddressForm=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),rapid_form_1=require("rapid-form"),react_1=require("react"),BillingAddressFormContext_1=tslib_1.__importDefault(require("../../context/BillingAddressFormContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),localStorage_1=require("../../utils/localStorage");function BillingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1}=props,p=tslib_1.__rest(props,["children","errorClassName","autoComplete","reset"]),{validation,values,errors,reset:resetForm,setValue:setValueForm}=(0,rapid_form_1.useRapidForm)(),{setAddressErrors,setAddress,isBusiness}=(0,react_1.useContext)(AddressContext_1.default),{saveAddressToCustomerAddressBook,order,include,addResourceToInclude,includeLoaded}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null);(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;if(include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),(0,isEmpty_1.default)(errors)){if(values&&Object.keys(values).length>0){setAddressErrors([],"billing_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("billing_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"billing_address",value:field.checked}))}setAddress({values:Object.assign(Object.assign({},values),isBusiness&&{business:isBusiness}),resource:"billing_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=(_a=errors[fieldName])===null||_a===void 0?void 0:_a.code,message=(_b=errors[fieldName])===null||_b===void 0?void 0:_b.message;["billing_address_state_code"].includes(fieldName)?values?.state_code?formErrors.push({code,message:message||"",resource:"billing_address",field:fieldName}):delete errors[fieldName]:formErrors.push({code,message:message||"",resource:"billing_address",field:fieldName})}setAddressErrors(formErrors,"billing_address")}const checkboxChecked=((_d=(_c=ref.current)===null||_c===void 0?void 0:_c.querySelector('[name="billing_address_save_to_customer_book"]'))===null||_d===void 0?void 0:_d.checked)||(0,localStorage_1.getSaveBillingAddressToAddressBook)();reset&&(!(0,isEmpty_1.default)(values)||!(0,isEmpty_1.default)(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"billing_address",value:!1}),ref&&((_e=ref.current)===null||_e===void 0||_e.reset(),resetForm({target:ref.current}),setAddressErrors([],"billing_address"),setAddress({values:{},resource:"billing_address"})))},[errors,values,reset,include,includeLoaded,isBusiness]);const providerValues={isBusiness,values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("billing_address_","")]:value};setAddress({values:Object.assign(Object.assign(Object.assign({},values),field),isBusiness&&{business:isBusiness}),resource:"billing_address"})},errorClassName,requiresBillingInfo:order?.requires_billing_info||!1,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return(0,jsx_runtime_1.jsx)(BillingAddressFormContext_1.default.Provider,{value:providerValues,children:(0,jsx_runtime_1.jsx)("form",Object.assign({ref,autoComplete},p,{children}))})}exports.BillingAddressForm=BillingAddressForm,exports.default=BillingAddressForm;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BillingAddressForm=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),rapid_form_1=require("rapid-form"),react_1=require("react"),BillingAddressFormContext_1=tslib_1.__importDefault(require("../../context/BillingAddressFormContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),localStorage_1=require("../../utils/localStorage");function BillingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,customFieldMessageError}=props,p=tslib_1.__rest(props,["children","errorClassName","autoComplete","reset","customFieldMessageError"]),{validation,values,errors,reset:resetForm,setValue:setValueForm}=(0,rapid_form_1.useRapidForm)(),{setAddressErrors,setAddress,isBusiness}=(0,react_1.useContext)(AddressContext_1.default),{saveAddressToCustomerAddressBook,order,include,addResourceToInclude,includeLoaded}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null);(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e,_f;if(include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),(0,isEmpty_1.default)(errors)){if(values&&Object.keys(values).length>0){setAddressErrors([],"billing_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("billing_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"billing_address",value:field.checked}))}setAddress({values:Object.assign(Object.assign({},values),isBusiness&&{business:isBusiness}),resource:"billing_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=(_a=errors[fieldName])===null||_a===void 0?void 0:_a.code,message=(_b=errors[fieldName])===null||_b===void 0?void 0:_b.message;if(["billing_address_state_code"].includes(fieldName))values?.state_code?formErrors.push({code,message:message||"",resource:"billing_address",field:fieldName}):delete errors[fieldName];else{const customMessage=customFieldMessageError!=null?customFieldMessageError({field:fieldName,code,message,value:values[fieldName].value}):null;formErrors.push({code,message:(_c=customMessage??message)!==null&&_c!==void 0?_c:"",resource:"billing_address",field:fieldName})}}setAddressErrors(formErrors,"billing_address")}const checkboxChecked=((_e=(_d=ref.current)===null||_d===void 0?void 0:_d.querySelector('[name="billing_address_save_to_customer_book"]'))===null||_e===void 0?void 0:_e.checked)||(0,localStorage_1.getSaveBillingAddressToAddressBook)();reset&&(!(0,isEmpty_1.default)(values)||!(0,isEmpty_1.default)(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"billing_address",value:!1}),ref&&((_f=ref.current)===null||_f===void 0||_f.reset(),resetForm({target:ref.current}),setAddressErrors([],"billing_address"),setAddress({values:{},resource:"billing_address"})))},[errors,values,reset,include,includeLoaded,isBusiness]);const providerValues={isBusiness,values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("billing_address_","")]:value};setAddress({values:Object.assign(Object.assign(Object.assign({},values),field),isBusiness&&{business:isBusiness}),resource:"billing_address"})},errorClassName,requiresBillingInfo:order?.requires_billing_info||!1,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return(0,jsx_runtime_1.jsx)(BillingAddressFormContext_1.default.Provider,{value:providerValues,children:(0,jsx_runtime_1.jsx)("form",Object.assign({ref,autoComplete},p,{children}))})}exports.BillingAddressForm=BillingAddressForm,exports.default=BillingAddressForm;
@@ -1,8 +1,13 @@
1
1
  import { type ReactNode } from 'react';
2
+ import { type CustomFieldMessageError } from '../../reducers/AddressReducer';
2
3
  interface Props extends Omit<JSX.IntrinsicElements['form'], 'onSubmit'> {
3
4
  children: ReactNode;
4
5
  reset?: boolean;
5
6
  errorClassName?: string;
7
+ /**
8
+ * Callback to customize the error message for a specific field. Called for each error in the form.
9
+ */
10
+ customFieldMessageError?: CustomFieldMessageError;
6
11
  }
7
12
  /**
8
13
  * Form container for creating or editing an order related shipping address.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ShippingAddressForm=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),rapid_form_1=require("rapid-form"),react_1=require("react"),ShippingAddressFormContext_1=tslib_1.__importDefault(require("../../context/ShippingAddressFormContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),localStorage_1=require("../../utils/localStorage");function ShippingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1}=props,p=tslib_1.__rest(props,["children","errorClassName","autoComplete","reset"]),{validation,values,errors,reset:resetForm,setValue:setValueForm}=(0,rapid_form_1.useRapidForm)(),{setAddressErrors,setAddress,shipToDifferentAddress,isBusiness,invertAddresses}=(0,react_1.useContext)(AddressContext_1.default),{saveAddressToCustomerAddressBook,include,addResourceToInclude,includeLoaded}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null);(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;if(include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address"}),(0,isEmpty_1.default)(errors)){if(!(0,isEmpty_1.default)(values)&&(shipToDifferentAddress||invertAddresses)){setAddressErrors([],"shipping_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("shipping_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"shipping_address",value:field.checked}))}setAddress({values:Object.assign(Object.assign({},values),isBusiness&&{business:isBusiness}),resource:"shipping_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=(_a=errors[fieldName])===null||_a===void 0?void 0:_a.code,message=(_b=errors[fieldName])===null||_b===void 0?void 0:_b.message;["shipping_address_state_code"].includes(fieldName)?(0,isEmpty_1.default)(values.state_code)?delete errors[fieldName]:formErrors.push({code,message:message||"",resource:"shipping_address",field:fieldName}):formErrors.push({code,message:message||"",resource:"shipping_address",field:fieldName})}(shipToDifferentAddress||invertAddresses)&&setAddressErrors(formErrors,"shipping_address")}const checkboxChecked=((_d=(_c=ref.current)===null||_c===void 0?void 0:_c.querySelector('[name="shipping_address_save_to_customer_book"]'))===null||_d===void 0?void 0:_d.checked)||(0,localStorage_1.getSaveShippingAddressToAddressBook)();reset&&(!(0,isEmpty_1.default)(values)||!(0,isEmpty_1.default)(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"shipping_address",value:!1}),ref&&((_e=ref.current)===null||_e===void 0||_e.reset(),resetForm({target:ref.current}),setAddressErrors([],"shipping_address"),setAddress({values:{},resource:"shipping_address"})))},[values,errors,shipToDifferentAddress,reset,include,includeLoaded,isBusiness]);const providerValues={values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("shipping_address_","")]:value};setAddress({values:Object.assign(Object.assign(Object.assign({},values),field),isBusiness&&{business:isBusiness}),resource:"shipping_address"})},errorClassName,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return(0,jsx_runtime_1.jsx)(ShippingAddressFormContext_1.default.Provider,{value:providerValues,children:(0,jsx_runtime_1.jsx)("form",Object.assign({ref,autoComplete},p,{children}))})}exports.ShippingAddressForm=ShippingAddressForm,exports.default=ShippingAddressForm;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ShippingAddressForm=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),rapid_form_1=require("rapid-form"),react_1=require("react"),ShippingAddressFormContext_1=tslib_1.__importDefault(require("../../context/ShippingAddressFormContext")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),localStorage_1=require("../../utils/localStorage");function ShippingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,customFieldMessageError}=props,p=tslib_1.__rest(props,["children","errorClassName","autoComplete","reset","customFieldMessageError"]),{validation,values,errors,reset:resetForm,setValue:setValueForm}=(0,rapid_form_1.useRapidForm)(),{setAddressErrors,setAddress,shipToDifferentAddress,isBusiness,invertAddresses}=(0,react_1.useContext)(AddressContext_1.default),{saveAddressToCustomerAddressBook,include,addResourceToInclude,includeLoaded}=(0,react_1.useContext)(OrderContext_1.default),ref=(0,react_1.useRef)(null);(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e,_f;if(include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address"}),(0,isEmpty_1.default)(errors)){if(!(0,isEmpty_1.default)(values)&&(shipToDifferentAddress||invertAddresses)){setAddressErrors([],"shipping_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("shipping_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"shipping_address",value:field.checked}))}setAddress({values:Object.assign(Object.assign({},values),isBusiness&&{business:isBusiness}),resource:"shipping_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=(_a=errors[fieldName])===null||_a===void 0?void 0:_a.code,message=(_b=errors[fieldName])===null||_b===void 0?void 0:_b.message;if(["shipping_address_state_code"].includes(fieldName))(0,isEmpty_1.default)(values.state_code)?delete errors[fieldName]:formErrors.push({code,message:message||"",resource:"shipping_address",field:fieldName});else{const customMessage=customFieldMessageError!=null?customFieldMessageError({field:fieldName,code,message,value:values[fieldName].value}):null;formErrors.push({code,message:(_c=customMessage??message)!==null&&_c!==void 0?_c:"",resource:"shipping_address",field:fieldName})}}(shipToDifferentAddress||invertAddresses)&&setAddressErrors(formErrors,"shipping_address")}const checkboxChecked=((_e=(_d=ref.current)===null||_d===void 0?void 0:_d.querySelector('[name="shipping_address_save_to_customer_book"]'))===null||_e===void 0?void 0:_e.checked)||(0,localStorage_1.getSaveShippingAddressToAddressBook)();reset&&(!(0,isEmpty_1.default)(values)||!(0,isEmpty_1.default)(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"shipping_address",value:!1}),ref&&((_f=ref.current)===null||_f===void 0||_f.reset(),resetForm({target:ref.current}),setAddressErrors([],"shipping_address"),setAddress({values:{},resource:"shipping_address"})))},[values,errors,shipToDifferentAddress,reset,include,includeLoaded,isBusiness]);const providerValues={values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("shipping_address_","")]:value};setAddress({values:Object.assign(Object.assign(Object.assign({},values),field),isBusiness&&{business:isBusiness}),resource:"shipping_address"})},errorClassName,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return(0,jsx_runtime_1.jsx)(ShippingAddressFormContext_1.default.Provider,{value:providerValues,children:(0,jsx_runtime_1.jsx)("form",Object.assign({ref,autoComplete},p,{children}))})}exports.ShippingAddressForm=ShippingAddressForm,exports.default=ShippingAddressForm;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:({customerAddressId})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:({pageNumber,pageSize})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize})}),getCustomerSubscriptions:({pageNumber,pageSize,number})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize,number})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.CustomerContainer=CustomerContainer,exports.default=CustomerContainer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomerContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerReducer_1=tslib_1.__importStar(require("../../reducers/CustomerReducer")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),isGuestToken_1=require("../../utils/isGuestToken");function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=(0,react_1.useReducer)(CustomerReducer_1.default,CustomerReducer_1.customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=(0,react_1.useContext)(OrderContext_1.default),config=(0,react_1.useContext)(CommerceLayerContext_1.default);(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),(0,react_1.useEffect)(()=>{if(config.accessToken){if(isGuest??(0,isGuestToken_1.isGuestToken)(config.accessToken))return;state.customers==null&&(0,CustomerReducer_1.getCustomerInfo)({config,dispatch}),state.addresses==null&&(0,CustomerReducer_1.getCustomerAddresses)({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0&&function(){return tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch}),yield(0,CustomerReducer_1.getCustomerPayments)({config,dispatch})})}()}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=(0,react_1.useMemo)(()=>Object.assign(Object.assign({isGuest},state),{saveCustomerUser:customerEmail=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.saveCustomerUser)({config,customerEmail,dispatch,updateOrder,order})}),setCustomerErrors:errors=>{(0,CustomerReducer_1.setCustomerErrors)(errors,dispatch)},setCustomerEmail:customerEmail=>{(0,CustomerReducer_1.setCustomerEmail)(customerEmail,dispatch)},getCustomerPaymentSources:()=>{(0,CustomerReducer_1.getCustomerPaymentSources)({dispatch,order})},deleteCustomerAddress:({customerAddressId})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.deleteCustomerAddress)({customerAddressId,dispatch,config,addresses:state.addresses})}),setResourceTrigger:props2=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,CustomerReducer_1.setResourceTrigger)(Object.assign(Object.assign({},props2),{dispatch,config}))}),createCustomerAddress:address=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.createCustomerAddress)({address,config,dispatch,state})}),getCustomerOrders:({pageNumber,pageSize})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerOrders)({config,dispatch,pageNumber,pageSize})}),getCustomerSubscriptions:({pageNumber,pageSize,id})=>tslib_1.__awaiter(this,void 0,void 0,function*(){yield(0,CustomerReducer_1.getCustomerSubscriptions)({config,dispatch,pageNumber,pageSize,id})})}),[state,isGuest]);return(0,jsx_runtime_1.jsx)(CustomerContext_1.default.Provider,{value:contextValue,children})}exports.CustomerContainer=CustomerContainer,exports.default=CustomerContainer;
@@ -26,10 +26,10 @@ type SubscriptionFields = {
26
26
  /**
27
27
  * Subscriptions id - Use to fetch subscriptions and shows its orders
28
28
  */
29
- number?: string;
29
+ id?: string;
30
30
  type?: 'subscriptions';
31
31
  } | {
32
- number?: never;
32
+ id?: never;
33
33
  type?: 'orders';
34
34
  };
35
35
  type Props = {
@@ -78,5 +78,5 @@ type Props = {
78
78
  */
79
79
  rowTrClassName?: string;
80
80
  } & Omit<JSX.IntrinsicElements['table'], 'children'> & PaginationProps & SubscriptionFields;
81
- export declare function OrderList({ number, type, children, columns, loadingElement, showActions, showPagination, sortBy, pageSize, paginationContainerClassName, actionsComponent, actionsContainerClassName, theadClassName, rowTrClassName, ...p }: Props): JSX.Element;
81
+ export declare function OrderList({ id, type, children, columns, loadingElement, showActions, showPagination, sortBy, pageSize, paginationContainerClassName, actionsComponent, actionsContainerClassName, theadClassName, rowTrClassName, ...p }: Props): JSX.Element;
82
82
  export default OrderList;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderList=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderListChildrenContext_1=tslib_1.__importDefault(require("../../context/OrderListChildrenContext")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),react_table_1=require("@tanstack/react-table"),icons_1=require("../../utils/icons"),filterChildren_1=tslib_1.__importDefault(require("../../utils/filterChildren")),rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];function OrderList(_a){var _b,_c,_d,_e,_f,{number,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName}=_a,p=tslib_1.__rest(_a,["number","type","children","columns","loadingElement","showActions","showPagination","sortBy","pageSize","paginationContainerClassName","actionsComponent","actionsContainerClassName","theadClassName","rowTrClassName"]);const[loading,setLoading]=(0,react_1.useState)(!0),[sorting,setSorting]=(0,react_1.useState)(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=(0,react_1.useState)({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=(0,react_1.useContext)(CustomerContext_1.default);(0,react_1.useEffect)(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,number})},[pageIndex,currentPageSize,number!=null]);const data=(0,react_1.useMemo)(()=>type==="subscriptions"?subscriptions??[]:orders??[],[orders,subscriptions]),cols=(0,react_1.useMemo)(()=>columns,[columns]),pagination=(0,react_1.useMemo)(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=(_c=(_b=orders?.pageCount)!==null&&_b!==void 0?_b:subscriptions?.pageCount)!==null&&_c!==void 0?_c:-1,table=(0,react_table_1.useReactTable)({data,columns:cols,getSortedRowModel:(0,react_table_1.getSortedRowModel)(),getCoreRowModel:(0,react_table_1.getCoreRowModel)(),getPaginationRowModel:(0,react_table_1.getPaginationRowModel)(),manualPagination:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";(0,react_1.useEffect)(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||(0,jsx_runtime_1.jsx)("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{var _a2,_b2,_c2,_d2;const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return(0,jsx_runtime_1.jsx)(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:(_a2=columns[k])===null||_a2===void 0?void 0:_a2.className,children:(0,jsx_runtime_1.jsxs)("span",{className:`${(_c2=(_b2=columns[k])===null||_b2===void 0?void 0:_b2.titleClassName)!==null&&_c2!==void 0?_c2:""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[(0,react_table_1.flexRender)(header.column.columnDef.header,header.getContext()),(_d2={asc:icons_1.sortAscIcon,desc:icons_1.sortDescIcon}[header.column.getIsSorted()])!==null&&_d2!==void 0?_d2:null]})},header.id)});return(0,jsx_runtime_1.jsx)(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=(0,filterChildren_1.default)({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return(0,jsx_runtime_1.jsx)(TrHtmlElement,{className:rowTrClassName,children:(0,jsx_runtime_1.jsx)(OrderListChildrenContext_1.default.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=(0,filterChildren_1.default)({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=(_e=(_d=orders?.meta.recordCount)!==null&&_d!==void 0?_d:subscriptions?.meta.recordCount)!==null&&_e!==void 0?_e:0,Pagination=()=>showPagination?(0,jsx_runtime_1.jsx)(OrderListPaginationContext_1.default.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:LoadingComponent}):((_f=type==="orders"?orders:subscriptions)===null||_f===void 0?void 0:_f.length)===0?(0,jsx_runtime_1.jsxs)(OrderListChildrenContext_1.default.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,(0,jsx_runtime_1.jsx)(Pagination,{})]}):(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,jsx_runtime_1.jsxs)(TableHtmlElement,Object.assign({},p,{children:[(0,jsx_runtime_1.jsx)(TheadHtmlElement,{className:theadClassName,children:headerComponent}),(0,jsx_runtime_1.jsx)(TbodyHtmlElement,{children:components})]})),totalRows<=pageSize?null:(0,jsx_runtime_1.jsx)("div",{className:paginationContainerClassName,children:(0,jsx_runtime_1.jsx)(Pagination,{})})]})}exports.OrderList=OrderList,exports.default=OrderList;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderList=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderListChildrenContext_1=tslib_1.__importDefault(require("../../context/OrderListChildrenContext")),OrderListPaginationContext_1=tslib_1.__importDefault(require("../../context/OrderListPaginationContext")),react_table_1=require("@tanstack/react-table"),icons_1=require("../../utils/icons"),filterChildren_1=tslib_1.__importDefault(require("../../utils/filterChildren")),rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];function OrderList(_a){var _b,_c,_d,_e,_f,{id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName}=_a,p=tslib_1.__rest(_a,["id","type","children","columns","loadingElement","showActions","showPagination","sortBy","pageSize","paginationContainerClassName","actionsComponent","actionsContainerClassName","theadClassName","rowTrClassName"]);const[loading,setLoading]=(0,react_1.useState)(!0),[sorting,setSorting]=(0,react_1.useState)(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=(0,react_1.useState)({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=(0,react_1.useContext)(CustomerContext_1.default);(0,react_1.useEffect)(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,id})},[pageIndex,currentPageSize,id!=null]);const data=(0,react_1.useMemo)(()=>type==="subscriptions"?subscriptions??[]:orders??[],[orders,subscriptions]),cols=(0,react_1.useMemo)(()=>columns,[columns]),pagination=(0,react_1.useMemo)(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=(_c=(_b=orders?.pageCount)!==null&&_b!==void 0?_b:subscriptions?.pageCount)!==null&&_c!==void 0?_c:-1,table=(0,react_table_1.useReactTable)({data,columns:cols,getSortedRowModel:(0,react_table_1.getSortedRowModel)(),getCoreRowModel:(0,react_table_1.getCoreRowModel)(),getPaginationRowModel:(0,react_table_1.getPaginationRowModel)(),manualPagination:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";(0,react_1.useEffect)(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||(0,jsx_runtime_1.jsx)("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{var _a2,_b2,_c2,_d2;const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return(0,jsx_runtime_1.jsx)(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:(_a2=columns[k])===null||_a2===void 0?void 0:_a2.className,children:(0,jsx_runtime_1.jsxs)("span",{className:`${(_c2=(_b2=columns[k])===null||_b2===void 0?void 0:_b2.titleClassName)!==null&&_c2!==void 0?_c2:""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[(0,react_table_1.flexRender)(header.column.columnDef.header,header.getContext()),(_d2={asc:icons_1.sortAscIcon,desc:icons_1.sortDescIcon}[header.column.getIsSorted()])!==null&&_d2!==void 0?_d2:null]})},header.id)});return(0,jsx_runtime_1.jsx)(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=(0,filterChildren_1.default)({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return(0,jsx_runtime_1.jsx)(TrHtmlElement,{className:rowTrClassName,children:(0,jsx_runtime_1.jsx)(OrderListChildrenContext_1.default.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=(0,filterChildren_1.default)({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?(_d=orders?.meta.recordCount)!==null&&_d!==void 0?_d:0:(_e=subscriptions?.meta.recordCount)!==null&&_e!==void 0?_e:0,Pagination=()=>showPagination?(0,jsx_runtime_1.jsx)(OrderListPaginationContext_1.default.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:LoadingComponent}):((_f=type==="orders"?orders:subscriptions)===null||_f===void 0?void 0:_f.length)===0?(0,jsx_runtime_1.jsxs)(OrderListChildrenContext_1.default.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,(0,jsx_runtime_1.jsx)(Pagination,{})]}):(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,jsx_runtime_1.jsxs)(TableHtmlElement,Object.assign({},p,{children:[(0,jsx_runtime_1.jsx)(TheadHtmlElement,{className:theadClassName,children:headerComponent}),(0,jsx_runtime_1.jsx)(TbodyHtmlElement,{children:components})]})),totalRows<=pageSize?null:(0,jsx_runtime_1.jsx)("div",{className:paginationContainerClassName,children:(0,jsx_runtime_1.jsx)(Pagination,{})})]})}exports.OrderList=OrderList,exports.default=OrderList;
@@ -102,4 +102,5 @@ export * from './components/stock_transfers/StockTransfer';
102
102
  export * from './components/stock_transfers/StockTransferField';
103
103
  export * from './hooks/useOrderContainer';
104
104
  export * from './hooks/useCommerceLayer';
105
+ export * from './hooks/useCustomerContainer';
105
106
  export * from './typings/errors';
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");tslib_1.__exportStar(require("./components/ExternalFunction"),exports),tslib_1.__exportStar(require("./components/MetadataInput"),exports),tslib_1.__exportStar(require("./components/SubmitButton"),exports),tslib_1.__exportStar(require("./components/addresses/Address"),exports),tslib_1.__exportStar(require("./components/addresses/AddressCountrySelector"),exports),tslib_1.__exportStar(require("./components/addresses/AddressField"),exports),tslib_1.__exportStar(require("./components/addresses/AddressInput"),exports),tslib_1.__exportStar(require("./components/addresses/AddressStateSelector"),exports),tslib_1.__exportStar(require("./components/addresses/AddressesContainer"),exports),tslib_1.__exportStar(require("./components/addresses/AddressesEmpty"),exports),tslib_1.__exportStar(require("./components/addresses/BillingAddressContainer"),exports),tslib_1.__exportStar(require("./components/addresses/BillingAddressForm"),exports),tslib_1.__exportStar(require("./components/addresses/SaveAddressesButton"),exports),tslib_1.__exportStar(require("./components/addresses/ShippingAddressContainer"),exports),tslib_1.__exportStar(require("./components/addresses/ShippingAddressForm"),exports),tslib_1.__exportStar(require("./components/auth/CommerceLayer"),exports),tslib_1.__exportStar(require("./components/customers/CustomerAddressForm"),exports),tslib_1.__exportStar(require("./components/customers/CustomerContainer"),exports),tslib_1.__exportStar(require("./components/customers/CustomerField"),exports),tslib_1.__exportStar(require("./components/customers/CustomerInput"),exports),tslib_1.__exportStar(require("./components/customers/SaveCustomerButton"),exports),tslib_1.__exportStar(require("./components/errors/Errors"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCard"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardContainer"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardCurrencySelector"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardInput"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponCode"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponForm"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponInput"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponRemoveButton"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponSubmit"),exports),tslib_1.__exportStar(require("./components/in_stock_subscriptions/InStockSubscriptionButton"),exports),tslib_1.__exportStar(require("./components/in_stock_subscriptions/InStockSubscriptionsContainer"),exports),tslib_1.__exportStar(require("./components/line_items/LineItem"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemAmount"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemCode"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemField"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemImage"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemName"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemOption"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemOptions"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemQuantity"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemRemoveLink"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemsContainer"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemsCount"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemsEmpty"),exports),tslib_1.__exportStar(require("./components/orders/AddToCartButton"),exports),tslib_1.__exportStar(require("./components/orders/AdjustmentAmount"),exports),tslib_1.__exportStar(require("./components/orders/CartLink"),exports),tslib_1.__exportStar(require("./components/orders/CheckoutLink"),exports),tslib_1.__exportStar(require("./components/orders/DiscountAmount"),exports),tslib_1.__exportStar(require("./components/orders/GiftCardAmount"),exports),tslib_1.__exportStar(require("./components/orders/OrderContainer"),exports),tslib_1.__exportStar(require("./components/orders/OrderList"),exports),tslib_1.__exportStar(require("./components/orders/OrderListEmpty"),exports),tslib_1.__exportStar(require("./components/orders/OrderListRow"),exports),tslib_1.__exportStar(require("./components/orders/OrderNumber"),exports),tslib_1.__exportStar(require("./components/orders/OrderStorage"),exports),tslib_1.__exportStar(require("./components/orders/PaymentMethodAmount"),exports),tslib_1.__exportStar(require("./components/orders/PlaceOrderButton"),exports),tslib_1.__exportStar(require("./components/orders/PlaceOrderContainer"),exports),tslib_1.__exportStar(require("./components/orders/PrivacyAndTermsCheckbox"),exports),tslib_1.__exportStar(require("./components/orders/ShippingAmount"),exports),tslib_1.__exportStar(require("./components/orders/SubTotalAmount"),exports),tslib_1.__exportStar(require("./components/orders/TaxesAmount"),exports),tslib_1.__exportStar(require("./components/orders/TotalAmount"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelField"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelLineItem"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelLineItemField"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelLineItemsCount"),exports),tslib_1.__exportStar(require("./components/parcels/Parcels"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelsCount"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethod"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodName"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodPrice"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodRadioButton"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodsContainer"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSource"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceBrandIcon"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceBrandName"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceDetail"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceEditButton"),exports),tslib_1.__exportStar(require("./components/prices/Price"),exports),tslib_1.__exportStar(require("./components/prices/PricesContainer"),exports),tslib_1.__exportStar(require("./components/shipments/Shipment"),exports),tslib_1.__exportStar(require("./components/shipments/ShipmentField"),exports),tslib_1.__exportStar(require("./components/shipments/ShipmentsContainer"),exports),tslib_1.__exportStar(require("./components/shipments/ShipmentsCount"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethod"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethodName"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethodPrice"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethodRadioButton"),exports),tslib_1.__exportStar(require("./components/skus/AvailabilityContainer"),exports),tslib_1.__exportStar(require("./components/skus/AvailabilityTemplate"),exports),tslib_1.__exportStar(require("./components/skus/DeliveryLeadTime"),exports),tslib_1.__exportStar(require("./components/skus/SkuField"),exports),tslib_1.__exportStar(require("./components/skus/SkuList"),exports),tslib_1.__exportStar(require("./components/skus/SkuListsContainer"),exports),tslib_1.__exportStar(require("./components/skus/Skus"),exports),tslib_1.__exportStar(require("./components/skus/SkusContainer"),exports),tslib_1.__exportStar(require("./components/stock_transfers/StockTransfer"),exports),tslib_1.__exportStar(require("./components/stock_transfers/StockTransferField"),exports),tslib_1.__exportStar(require("./hooks/useOrderContainer"),exports),tslib_1.__exportStar(require("./hooks/useCommerceLayer"),exports),tslib_1.__exportStar(require("./typings/errors"),exports);
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");tslib_1.__exportStar(require("./components/ExternalFunction"),exports),tslib_1.__exportStar(require("./components/MetadataInput"),exports),tslib_1.__exportStar(require("./components/SubmitButton"),exports),tslib_1.__exportStar(require("./components/addresses/Address"),exports),tslib_1.__exportStar(require("./components/addresses/AddressCountrySelector"),exports),tslib_1.__exportStar(require("./components/addresses/AddressField"),exports),tslib_1.__exportStar(require("./components/addresses/AddressInput"),exports),tslib_1.__exportStar(require("./components/addresses/AddressStateSelector"),exports),tslib_1.__exportStar(require("./components/addresses/AddressesContainer"),exports),tslib_1.__exportStar(require("./components/addresses/AddressesEmpty"),exports),tslib_1.__exportStar(require("./components/addresses/BillingAddressContainer"),exports),tslib_1.__exportStar(require("./components/addresses/BillingAddressForm"),exports),tslib_1.__exportStar(require("./components/addresses/SaveAddressesButton"),exports),tslib_1.__exportStar(require("./components/addresses/ShippingAddressContainer"),exports),tslib_1.__exportStar(require("./components/addresses/ShippingAddressForm"),exports),tslib_1.__exportStar(require("./components/auth/CommerceLayer"),exports),tslib_1.__exportStar(require("./components/customers/CustomerAddressForm"),exports),tslib_1.__exportStar(require("./components/customers/CustomerContainer"),exports),tslib_1.__exportStar(require("./components/customers/CustomerField"),exports),tslib_1.__exportStar(require("./components/customers/CustomerInput"),exports),tslib_1.__exportStar(require("./components/customers/SaveCustomerButton"),exports),tslib_1.__exportStar(require("./components/errors/Errors"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCard"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardContainer"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardCurrencySelector"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardInput"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponCode"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponForm"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponInput"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponRemoveButton"),exports),tslib_1.__exportStar(require("./components/gift_cards/GiftCardOrCouponSubmit"),exports),tslib_1.__exportStar(require("./components/in_stock_subscriptions/InStockSubscriptionButton"),exports),tslib_1.__exportStar(require("./components/in_stock_subscriptions/InStockSubscriptionsContainer"),exports),tslib_1.__exportStar(require("./components/line_items/LineItem"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemAmount"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemCode"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemField"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemImage"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemName"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemOption"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemOptions"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemQuantity"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemRemoveLink"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemsContainer"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemsCount"),exports),tslib_1.__exportStar(require("./components/line_items/LineItemsEmpty"),exports),tslib_1.__exportStar(require("./components/orders/AddToCartButton"),exports),tslib_1.__exportStar(require("./components/orders/AdjustmentAmount"),exports),tslib_1.__exportStar(require("./components/orders/CartLink"),exports),tslib_1.__exportStar(require("./components/orders/CheckoutLink"),exports),tslib_1.__exportStar(require("./components/orders/DiscountAmount"),exports),tslib_1.__exportStar(require("./components/orders/GiftCardAmount"),exports),tslib_1.__exportStar(require("./components/orders/OrderContainer"),exports),tslib_1.__exportStar(require("./components/orders/OrderList"),exports),tslib_1.__exportStar(require("./components/orders/OrderListEmpty"),exports),tslib_1.__exportStar(require("./components/orders/OrderListRow"),exports),tslib_1.__exportStar(require("./components/orders/OrderNumber"),exports),tslib_1.__exportStar(require("./components/orders/OrderStorage"),exports),tslib_1.__exportStar(require("./components/orders/PaymentMethodAmount"),exports),tslib_1.__exportStar(require("./components/orders/PlaceOrderButton"),exports),tslib_1.__exportStar(require("./components/orders/PlaceOrderContainer"),exports),tslib_1.__exportStar(require("./components/orders/PrivacyAndTermsCheckbox"),exports),tslib_1.__exportStar(require("./components/orders/ShippingAmount"),exports),tslib_1.__exportStar(require("./components/orders/SubTotalAmount"),exports),tslib_1.__exportStar(require("./components/orders/TaxesAmount"),exports),tslib_1.__exportStar(require("./components/orders/TotalAmount"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelField"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelLineItem"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelLineItemField"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelLineItemsCount"),exports),tslib_1.__exportStar(require("./components/parcels/Parcels"),exports),tslib_1.__exportStar(require("./components/parcels/ParcelsCount"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethod"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodName"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodPrice"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodRadioButton"),exports),tslib_1.__exportStar(require("./components/payment_methods/PaymentMethodsContainer"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSource"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceBrandIcon"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceBrandName"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceDetail"),exports),tslib_1.__exportStar(require("./components/payment_source/PaymentSourceEditButton"),exports),tslib_1.__exportStar(require("./components/prices/Price"),exports),tslib_1.__exportStar(require("./components/prices/PricesContainer"),exports),tslib_1.__exportStar(require("./components/shipments/Shipment"),exports),tslib_1.__exportStar(require("./components/shipments/ShipmentField"),exports),tslib_1.__exportStar(require("./components/shipments/ShipmentsContainer"),exports),tslib_1.__exportStar(require("./components/shipments/ShipmentsCount"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethod"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethodName"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethodPrice"),exports),tslib_1.__exportStar(require("./components/shipping_methods/ShippingMethodRadioButton"),exports),tslib_1.__exportStar(require("./components/skus/AvailabilityContainer"),exports),tslib_1.__exportStar(require("./components/skus/AvailabilityTemplate"),exports),tslib_1.__exportStar(require("./components/skus/DeliveryLeadTime"),exports),tslib_1.__exportStar(require("./components/skus/SkuField"),exports),tslib_1.__exportStar(require("./components/skus/SkuList"),exports),tslib_1.__exportStar(require("./components/skus/SkuListsContainer"),exports),tslib_1.__exportStar(require("./components/skus/Skus"),exports),tslib_1.__exportStar(require("./components/skus/SkusContainer"),exports),tslib_1.__exportStar(require("./components/stock_transfers/StockTransfer"),exports),tslib_1.__exportStar(require("./components/stock_transfers/StockTransferField"),exports),tslib_1.__exportStar(require("./hooks/useOrderContainer"),exports),tslib_1.__exportStar(require("./hooks/useCommerceLayer"),exports),tslib_1.__exportStar(require("./hooks/useCustomerContainer"),exports),tslib_1.__exportStar(require("./typings/errors"),exports);
@@ -1,10 +1,18 @@
1
1
  import { type Dispatch } from 'react';
2
- import { type BaseError } from '../typings/errors';
2
+ import { type CodeErrorType, type BaseError } from '../typings/errors';
3
3
  import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
4
4
  import { type Address, type AddressCreate, type Order } from '@commercelayer/sdk';
5
5
  import { type updateOrder } from './OrderReducer';
6
6
  import { type TCustomerAddress } from './CustomerReducer';
7
7
  import { type TResourceError } from '../components/errors/Errors';
8
+ import { type AddressValuesKeys } from '../context/BillingAddressFormContext';
9
+ import { type AddressInputName } from '../typings/index';
10
+ export type CustomFieldMessageError = (props: {
11
+ field: Extract<AddressValuesKeys, AddressInputName> | string;
12
+ code: Extract<CodeErrorType, 'EMPTY_ERROR' | 'VALIDATION_ERROR'> | undefined;
13
+ message: string | undefined;
14
+ value: string;
15
+ }) => string | null;
8
16
  export type AddressActionType = 'setErrors' | 'setAddress' | 'setShipToDifferentAddress' | 'setCloneAddress' | 'cleanup';
9
17
  export type AddressField = 'city' | 'company' | 'country_code' | 'first_name' | 'last_name' | 'line_1' | 'line_2' | 'phone' | 'state_code' | 'zip_code' | 'billing_info';
10
18
  export type AddressFieldView = AddressField | 'full_address' | 'full_name';
@@ -118,12 +118,12 @@ interface GetCustomerOrdersProps {
118
118
  */
119
119
  pageNumber?: number;
120
120
  /**
121
- * Retrieve a specific subscription or order by number
121
+ * Retrieve a specific subscription or order by id
122
122
  */
123
- number?: string;
123
+ id?: string;
124
124
  }
125
125
  export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
126
- export declare function getCustomerSubscriptions({ number, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
126
+ export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
127
127
  export type TCustomerAddress = AddressCreate & AddressUpdate & Record<string, string | null | undefined>;
128
128
  interface TCreateCustomerAddress {
129
129
  /**
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.customerInitialState=exports.setResourceTrigger=exports.getCustomerInfo=exports.getCustomerPayments=exports.createCustomerAddress=exports.getCustomerSubscriptions=exports.getCustomerOrders=exports.getCustomerPaymentSources=exports.deleteCustomerAddress=exports.getCustomerAddresses=exports.setCustomerEmail=exports.setCustomerErrors=exports.saveCustomerUser=void 0;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({customerEmail,order,updateOrder}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}exports.saveCustomerUser=saveCustomerUser;function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setCustomerErrors=setCustomerErrors;function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}exports.setCustomerEmail=setCustomerEmail;function getCustomerAddresses({config,dispatch,isOrderAvailable}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}exports.getCustomerAddresses=getCustomerAddresses;function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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")}})}exports.deleteCustomerAddress=deleteCustomerAddress;function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}exports.getCustomerPaymentSources=getCustomerPaymentSources;function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerOrders=getCustomerOrders;function getCustomerSubscriptions({number,config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config.accessToken){const{owner}=(0,jwt_1.jwt)(config.accessToken);if(owner?.id){const sdk=(0,getSdk_1.default)(config);if(number!=null){const subscriptions=yield sdk.customers.orders(owner.id,{filters:{order_subscription_number_eq:number},pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}else{const subscriptions=yield sdk.customers.order_subscriptions(owner.id,{pageSize,pageNumber});dispatch({type:"setSubscriptions",payload:{subscriptions}})}}}})}exports.getCustomerSubscriptions=getCustomerSubscriptions;function createCustomerAddress({address,config,dispatch,state}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const upAddress=yield sdk.addresses.update(address),updatedAddresses=(_a=state?.addresses)===null||_a===void 0?void 0:_a.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=yield sdk.addresses.create(address);if(!((_b=state?.customers)===null||_b===void 0)&&_b.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_c=state?.customers)===null||_c===void 0?void 0:_c.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")}}})}exports.createCustomerAddress=createCustomerAddress;function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerPayments=getCustomerPayments;function getCustomerInfo({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerInfo=getCustomerInfo;function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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.setResourceTrigger=setResourceTrigger,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=exports.setResourceTrigger=exports.getCustomerInfo=exports.getCustomerPayments=exports.createCustomerAddress=exports.getCustomerSubscriptions=exports.getCustomerOrders=exports.getCustomerPaymentSources=exports.deleteCustomerAddress=exports.getCustomerAddresses=exports.setCustomerEmail=exports.setCustomerErrors=exports.saveCustomerUser=void 0;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({customerEmail,order,updateOrder}){return tslib_1.__awaiter(this,void 0,void 0,function*(){if(order){const attributes={customer_email:customerEmail,id:order.id};yield updateOrder({id:order.id,attributes})}})}exports.saveCustomerUser=saveCustomerUser;function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}exports.setCustomerErrors=setCustomerErrors;function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}exports.setCustomerEmail=setCustomerEmail;function getCustomerAddresses({config,dispatch,isOrderAvailable}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{const addresses=[];(yield(0,getSdk_1.default)(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=(0,getErrors_1.default)({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}})}exports.getCustomerAddresses=getCustomerAddresses;function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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")}})}exports.deleteCustomerAddress=deleteCustomerAddress;function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}exports.getCustomerPaymentSources=getCustomerPaymentSources;function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerOrders=getCustomerOrders;function getCustomerSubscriptions({id,config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}}})}exports.getCustomerSubscriptions=getCustomerSubscriptions;function createCustomerAddress({address,config,dispatch,state}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){if(config&&address){const sdk=(0,getSdk_1.default)(config),{id}=address;try{if(id){const upAddress=yield sdk.addresses.update(address),updatedAddresses=(_a=state?.addresses)===null||_a===void 0?void 0:_a.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=yield sdk.addresses.create(address);if(!((_b=state?.customers)===null||_b===void 0)&&_b.id&&newAddress?.id){const newCustomerAddress=yield sdk.customer_addresses.create({customer:sdk.customers.relationship((_c=state?.customers)===null||_c===void 0?void 0:_c.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")}}})}exports.createCustomerAddress=createCustomerAddress;function getCustomerPayments({config,dispatch,pageSize=10,pageNumber=1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerPayments=getCustomerPayments;function getCustomerInfo({config,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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}})}}})}exports.getCustomerInfo=getCustomerInfo;function setResourceTrigger({config,dispatch,resource,attribute,id,pageSize=10,pageNumber=1,reloadList=!1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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.setResourceTrigger=setResourceTrigger,exports.customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders","setSubscriptions","setCustomers"],customerReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=customerReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.addressesController=exports.invertedAddressesHandler=exports.countryLockController=exports.shippingAddressController=exports.billingAddressController=void 0;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}){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))if(invertAddresses)billingDisable=!!(billing_address&&(0,validateFormFields_1.fieldsExist)(billing_address));else{let billingInfo=[...AddressReducer_1.addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),billingDisable=!!(billing_address&&(0,validateFormFields_1.fieldsExist)(billing_address,billingInfo))}return billingDisable&&!(0,isEmpty_1.default)(billingAddressId)&&(0,isEmpty_1.default)(billing_address)&&(billingDisable=!1),billingDisable}exports.billingAddressController=billingAddressController;function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1}){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))if(invertAddresses){let billingInfo=[...AddressReducer_1.addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address,billingInfo))}else shipToDifferentAddress&&(shipping_address==null||delete shipping_address.billing_info,shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address)));return shippingDisable&&!(0,isEmpty_1.default)(shippingAddressId)&&(0,isEmpty_1.default)(shipping_address)&&(shippingDisable=!1),shippingDisable}exports.shippingAddressController=shippingAddressController;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}exports.countryLockController=countryLockController;function invertedAddressesHandler({order,billingAddress,billingAddressId,customerEmail,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){const currentShippingAddressRef=(_a=order?.shipping_address)===null||_a===void 0?void 0:_a.reference,orderAttributes={id:order?.id,_billing_address_clone_id:shippingAddressId,_shipping_address_clone_id:shippingAddressId,customer_email:customerEmail};if(currentShippingAddressRef===billingAddressId&&(orderAttributes._billing_address_clone_id=(_b=order?.billing_address)===null||_b===void 0?void 0:_b.id,orderAttributes._shipping_address_clone_id=(_c=order?.shipping_address)===null||_c===void 0?void 0:_c.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})}exports.invertedAddressesHandler=invertedAddressesHandler;function addressesController({billing_address,billingAddressId,shipToDifferentAddress,shipping_address,shippingAddressId,errors,requiresBillingInfo,invertAddresses}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId});return{billingDisable,shippingDisable}}exports.addressesController=addressesController;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.addressesController=exports.invertedAddressesHandler=exports.countryLockController=exports.shippingAddressController=exports.billingAddressController=void 0;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}){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))if(invertAddresses)billingDisable=!!(billing_address&&(0,validateFormFields_1.fieldsExist)(billing_address));else{let billingInfo=[...AddressReducer_1.addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),billingDisable=!!(billing_address&&(0,validateFormFields_1.fieldsExist)(billing_address,billingInfo))}return billingDisable&&!(0,isEmpty_1.default)(billingAddressId)&&(0,isEmpty_1.default)(billing_address)&&(billingDisable=!1),billingDisable}exports.billingAddressController=billingAddressController;function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1}){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))if(invertAddresses){let billingInfo=[...AddressReducer_1.addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address,billingInfo))}else shipToDifferentAddress&&(shipping_address==null||delete shipping_address.billing_info,shippingDisable=!!(shipping_address&&(0,validateFormFields_1.fieldsExist)(shipping_address)));return shippingDisable&&!(0,isEmpty_1.default)(shippingAddressId)&&(0,isEmpty_1.default)(shipping_address)&&(shippingDisable=!1),shippingDisable}exports.shippingAddressController=shippingAddressController;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}exports.countryLockController=countryLockController;function invertedAddressesHandler({order,billingAddress,billingAddressId,customerEmail,shipToDifferentAddress,shippingAddress,shippingAddressId,sdk}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){const currentShippingAddressRef=(_a=order?.shipping_address)===null||_a===void 0?void 0:_a.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=(_b=order?.billing_address)===null||_b===void 0?void 0:_b.id,orderAttributes._shipping_address_clone_id=(_c=order?.shipping_address)===null||_c===void 0?void 0:_c.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})}exports.invertedAddressesHandler=invertedAddressesHandler;function addressesController({billing_address,billingAddressId,shipToDifferentAddress,shipping_address,shippingAddressId,errors,requiresBillingInfo,invertAddresses}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId});return{billingDisable,shippingDisable}}exports.addressesController=addressesController;
@@ -11,7 +11,6 @@ export type ValidateFormFields = <R extends string[]>(fields: HTMLFormControlsCo
11
11
  export type ValidateValue = <V extends string | boolean, N extends string, T extends string, B extends TResourceError>(val: V, name: N, type: T, resource: B) => BaseError | Record<string, any>;
12
12
  export declare const validateValue: ValidateValue;
13
13
  declare const validateFormFields: ValidateFormFields;
14
- export type FieldsExist = (address: AddressCreate, schema?: AddressField[]) => boolean;
15
- export declare const fieldsExist: FieldsExist;
14
+ export declare function fieldsExist(address: AddressCreate, schema?: AddressField[]): boolean;
16
15
  export declare function businessMandatoryField(fieldName: AddressInputName, isBusiness?: boolean): boolean;
17
16
  export default validateFormFields;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.businessMandatoryField=exports.fieldsExist=exports.validateValue=void 0;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),isString_1=tslib_1.__importDefault(require("lodash/isString")),without_1=tslib_1.__importDefault(require("lodash/without")),keys_1=tslib_1.__importDefault(require("lodash/keys")),map_1=tslib_1.__importDefault(require("lodash/map")),AddressReducer_1=require("../reducers/AddressReducer"),EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,validateValue=(val,name,type,resource)=>val?type==="email"&&(0,isString_1.default)(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};exports.validateValue=validateValue;const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return(0,map_1.default)(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=(0,exports.validateValue)(val,v.name,v.type,resourceType);(0,isEmpty_1.default)(error)||errors.push(error),values=Object.assign(Object.assign({},values),{[`${v.name}`]:val})}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?Object.assign(Object.assign({},values),{metadata:Object.assign(Object.assign({},values.metadata),{[`${v.name}`]:val})}):Object.assign(Object.assign({},values),{[`${v.name}`]:val}))}),{errors,values}},fieldsExist=(address,schema=AddressReducer_1.addressFields)=>{if(address.business){const required=(0,without_1.default)(schema,"first_name","last_name","line_2"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=(0,without_1.default)(schema,"line_2","company"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}};exports.fieldsExist=fieldsExist;const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}exports.businessMandatoryField=businessMandatoryField,exports.default=validateFormFields;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.businessMandatoryField=exports.fieldsExist=exports.validateValue=void 0;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),isString_1=tslib_1.__importDefault(require("lodash/isString")),without_1=tslib_1.__importDefault(require("lodash/without")),keys_1=tslib_1.__importDefault(require("lodash/keys")),map_1=tslib_1.__importDefault(require("lodash/map")),AddressReducer_1=require("../reducers/AddressReducer"),EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,validateValue=(val,name,type,resource)=>val?type==="email"&&(0,isString_1.default)(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};exports.validateValue=validateValue;const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return(0,map_1.default)(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=(0,exports.validateValue)(val,v.name,v.type,resourceType);(0,isEmpty_1.default)(error)||errors.push(error),values=Object.assign(Object.assign({},values),{[`${v.name}`]:val})}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?Object.assign(Object.assign({},values),{metadata:Object.assign(Object.assign({},values.metadata),{[`${v.name}`]:val})}):Object.assign(Object.assign({},values),{[`${v.name}`]:val}))}),{errors,values}};function fieldsExist(address,schema=AddressReducer_1.addressFields){if(address.business){const required=(0,without_1.default)(schema,"first_name","last_name","line_2"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=(0,without_1.default)(schema,"line_2","company"),validAddress=(0,keys_1.default)(address).filter(k=>required.includes(k));return required.length>validAddress.length}}exports.fieldsExist=fieldsExist;const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}exports.businessMandatoryField=businessMandatoryField,exports.default=validateFormFields;
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
+ import { type CustomFieldMessageError } from '../../reducers/AddressReducer';
2
3
  type Props = {
3
4
  children: ReactNode;
4
5
  /**
@@ -9,6 +10,10 @@ type Props = {
9
10
  * Define children input and select classnames assigned in case of validation error.
10
11
  */
11
12
  errorClassName?: string;
13
+ /**
14
+ * Callback to customize the error message for a specific field. Called for each error in the form.
15
+ */
16
+ customFieldMessageError?: CustomFieldMessageError;
12
17
  } & Omit<JSX.IntrinsicElements['form'], 'onSubmit'>;
13
18
  /**
14
19
  * Form container for creating or editing an order related billing address or a customer address, depending on the context in use.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext from"../../context/AddressContext";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import{getSaveBillingAddressToAddressBook}from"../../utils/localStorage";export function BillingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm}=useRapidForm(),{setAddressErrors,setAddress,isBusiness}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,order,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),isEmpty(errors)){if(values&&Object.keys(values).length>0){setAddressErrors([],"billing_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("billing_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"billing_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"billing_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;["billing_address_state_code"].includes(fieldName)?values?.state_code?formErrors.push({code,message:message||"",resource:"billing_address",field:fieldName}):delete errors[fieldName]:formErrors.push({code,message:message||"",resource:"billing_address",field:fieldName})}setAddressErrors(formErrors,"billing_address")}const checkboxChecked=ref.current?.querySelector('[name="billing_address_save_to_customer_book"]')?.checked||getSaveBillingAddressToAddressBook();reset&&(!isEmpty(values)||!isEmpty(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"billing_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"billing_address"),setAddress({values:{},resource:"billing_address"})))},[errors,values,reset,include,includeLoaded,isBusiness]);const providerValues={isBusiness,values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("billing_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"billing_address"})},errorClassName,requiresBillingInfo:order?.requires_billing_info||!1,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(BillingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default BillingAddressForm;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext from"../../context/AddressContext";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import BillingAddressFormContext from"../../context/BillingAddressFormContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import{getSaveBillingAddressToAddressBook}from"../../utils/localStorage";export function BillingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,customFieldMessageError,...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm}=useRapidForm(),{setAddressErrors,setAddress,isBusiness}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,order,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),isEmpty(errors)){if(values&&Object.keys(values).length>0){setAddressErrors([],"billing_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("billing_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"billing_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"billing_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;if(["billing_address_state_code"].includes(fieldName))values?.state_code?formErrors.push({code,message:message||"",resource:"billing_address",field:fieldName}):delete errors[fieldName];else{const customMessage=customFieldMessageError!=null?customFieldMessageError({field:fieldName,code,message,value:values[fieldName].value}):null;formErrors.push({code,message:customMessage??message??"",resource:"billing_address",field:fieldName})}}setAddressErrors(formErrors,"billing_address")}const checkboxChecked=ref.current?.querySelector('[name="billing_address_save_to_customer_book"]')?.checked||getSaveBillingAddressToAddressBook();reset&&(!isEmpty(values)||!isEmpty(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"billing_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"billing_address"),setAddress({values:{},resource:"billing_address"})))},[errors,values,reset,include,includeLoaded,isBusiness]);const providerValues={isBusiness,values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("billing_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"billing_address"})},errorClassName,requiresBillingInfo:order?.requires_billing_info||!1,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(BillingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default BillingAddressForm;
@@ -1,8 +1,13 @@
1
1
  import { type ReactNode } from 'react';
2
+ import { type CustomFieldMessageError } from '../../reducers/AddressReducer';
2
3
  interface Props extends Omit<JSX.IntrinsicElements['form'], 'onSubmit'> {
3
4
  children: ReactNode;
4
5
  reset?: boolean;
5
6
  errorClassName?: string;
7
+ /**
8
+ * Callback to customize the error message for a specific field. Called for each error in the form.
9
+ */
10
+ customFieldMessageError?: CustomFieldMessageError;
6
11
  }
7
12
  /**
8
13
  * Form container for creating or editing an order related shipping address.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext from"../../context/AddressContext";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import{getSaveShippingAddressToAddressBook}from"../../utils/localStorage";export function ShippingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm}=useRapidForm(),{setAddressErrors,setAddress,shipToDifferentAddress,isBusiness,invertAddresses}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address"}),isEmpty(errors)){if(!isEmpty(values)&&(shipToDifferentAddress||invertAddresses)){setAddressErrors([],"shipping_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("shipping_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"shipping_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;["shipping_address_state_code"].includes(fieldName)?isEmpty(values.state_code)?delete errors[fieldName]:formErrors.push({code,message:message||"",resource:"shipping_address",field:fieldName}):formErrors.push({code,message:message||"",resource:"shipping_address",field:fieldName})}(shipToDifferentAddress||invertAddresses)&&setAddressErrors(formErrors,"shipping_address")}const checkboxChecked=ref.current?.querySelector('[name="shipping_address_save_to_customer_book"]')?.checked||getSaveShippingAddressToAddressBook();reset&&(!isEmpty(values)||!isEmpty(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"shipping_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"shipping_address"),setAddress({values:{},resource:"shipping_address"})))},[values,errors,shipToDifferentAddress,reset,include,includeLoaded,isBusiness]);const providerValues={values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("shipping_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})},errorClassName,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(ShippingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default ShippingAddressForm;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import AddressesContext from"../../context/AddressContext";import{useRapidForm}from"rapid-form";import{useContext,useEffect,useRef}from"react";import ShippingAddressFormContext from"../../context/ShippingAddressFormContext";import isEmpty from"lodash/isEmpty";import OrderContext from"../../context/OrderContext";import{getSaveShippingAddressToAddressBook}from"../../utils/localStorage";export function ShippingAddressForm(props){const{children,errorClassName,autoComplete="on",reset=!1,customFieldMessageError,...p}=props,{validation,values,errors,reset:resetForm,setValue:setValueForm}=useRapidForm(),{setAddressErrors,setAddress,shipToDifferentAddress,isBusiness,invertAddresses}=useContext(AddressesContext),{saveAddressToCustomerAddressBook,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),ref=useRef(null);useEffect(()=>{if(include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address"}),isEmpty(errors)){if(!isEmpty(values)&&(shipToDifferentAddress||invertAddresses)){setAddressErrors([],"shipping_address");for(const name in values){const field=values[name];(field?.value||field?.required===!1&&field?.type!=="checkbox")&&(values[name.replace("shipping_address_","")]=field.value,delete values[name]),field?.type==="checkbox"&&(delete values[name],saveAddressToCustomerAddressBook({type:"shipping_address",value:field.checked}))}setAddress({values:{...values,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})}}else{const formErrors=[];for(const fieldName in errors){const code=errors[fieldName]?.code,message=errors[fieldName]?.message;if(["shipping_address_state_code"].includes(fieldName))isEmpty(values.state_code)?delete errors[fieldName]:formErrors.push({code,message:message||"",resource:"shipping_address",field:fieldName});else{const customMessage=customFieldMessageError!=null?customFieldMessageError({field:fieldName,code,message,value:values[fieldName].value}):null;formErrors.push({code,message:customMessage??message??"",resource:"shipping_address",field:fieldName})}}(shipToDifferentAddress||invertAddresses)&&setAddressErrors(formErrors,"shipping_address")}const checkboxChecked=ref.current?.querySelector('[name="shipping_address_save_to_customer_book"]')?.checked||getSaveShippingAddressToAddressBook();reset&&(!isEmpty(values)||!isEmpty(errors)||checkboxChecked)&&(saveAddressToCustomerAddressBook&&saveAddressToCustomerAddressBook({type:"shipping_address",value:!1}),ref&&(ref.current?.reset(),resetForm({target:ref.current}),setAddressErrors([],"shipping_address"),setAddress({values:{},resource:"shipping_address"})))},[values,errors,shipToDifferentAddress,reset,include,includeLoaded,isBusiness]);const providerValues={values,validation,setValue:(name,value)=>{setValueForm(name,value);const field={[name.replace("shipping_address_","")]:value};setAddress({values:{...values,...field,...isBusiness&&{business:isBusiness}},resource:"shipping_address"})},errorClassName,errors,resetField:name=>{resetForm({currentTarget:ref.current},name)}};return _jsx(ShippingAddressFormContext.Provider,{value:providerValues,children:_jsx("form",{ref,autoComplete,...p,children})})}export default ShippingAddressForm;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize})},getCustomerSubscriptions:async({pageNumber,pageSize,number})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize,number})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useReducer,useMemo}from"react";import customerReducer,{customerInitialState,getCustomerAddresses,getCustomerOrders,getCustomerPaymentSources,setCustomerEmail,setCustomerErrors,deleteCustomerAddress,createCustomerAddress,saveCustomerUser,getCustomerPayments,getCustomerSubscriptions,getCustomerInfo,setResourceTrigger}from"../../reducers/CustomerReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import{isGuestToken}from"../../utils/isGuestToken";export function CustomerContainer(props){const{children,isGuest}=props,[state,dispatch]=useReducer(customerReducer,customerInitialState),{order,addResourceToInclude,include,updateOrder,includeLoaded,withoutIncludes}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;include?.includes("available_customer_payment_sources.payment_source")?includeLoaded?.["available_customer_payment_sources.payment_source"]||addResourceToInclude({newResourceLoaded:{"available_customer_payment_sources.payment_source":!0,"available_customer_payment_sources.payment_method":!0}}):addResourceToInclude({newResource:["available_customer_payment_sources.payment_source","available_customer_payment_sources.payment_method"]})}},[config.accessToken,include?.length,Object.keys(includeLoaded??{}).length]),useEffect(()=>{if(config.accessToken){if(isGuest??isGuestToken(config.accessToken))return;if(state.customers==null&&getCustomerInfo({config,dispatch}),state.addresses==null&&getCustomerAddresses({config,dispatch,isOrderAvailable:withoutIncludes!=null}),order?.available_customer_payment_sources&&getCustomerPaymentSources({dispatch,order}),config.accessToken&&order==null&&include==null&&includeLoaded==null&&withoutIncludes===void 0){async function getCustomerData(){await getCustomerOrders({config,dispatch}),await getCustomerSubscriptions({config,dispatch}),await getCustomerPayments({config,dispatch})}getCustomerData()}}},[config.accessToken,order?.payment_source!=null,isGuest]);const contextValue=useMemo(()=>({isGuest,...state,saveCustomerUser:async customerEmail=>{await saveCustomerUser({config,customerEmail,dispatch,updateOrder,order})},setCustomerErrors:errors=>{setCustomerErrors(errors,dispatch)},setCustomerEmail:customerEmail=>{setCustomerEmail(customerEmail,dispatch)},getCustomerPaymentSources:()=>{getCustomerPaymentSources({dispatch,order})},deleteCustomerAddress:async({customerAddressId})=>{await deleteCustomerAddress({customerAddressId,dispatch,config,addresses:state.addresses})},setResourceTrigger:async props2=>await setResourceTrigger({...props2,dispatch,config}),createCustomerAddress:async address=>{await createCustomerAddress({address,config,dispatch,state})},getCustomerOrders:async({pageNumber,pageSize})=>{await getCustomerOrders({config,dispatch,pageNumber,pageSize})},getCustomerSubscriptions:async({pageNumber,pageSize,id})=>{await getCustomerSubscriptions({config,dispatch,pageNumber,pageSize,id})}}),[state,isGuest]);return _jsx(CustomerContext.Provider,{value:contextValue,children})}export default CustomerContainer;
@@ -26,10 +26,10 @@ type SubscriptionFields = {
26
26
  /**
27
27
  * Subscriptions id - Use to fetch subscriptions and shows its orders
28
28
  */
29
- number?: string;
29
+ id?: string;
30
30
  type?: 'subscriptions';
31
31
  } | {
32
- number?: never;
32
+ id?: never;
33
33
  type?: 'orders';
34
34
  };
35
35
  type Props = {
@@ -78,5 +78,5 @@ type Props = {
78
78
  */
79
79
  rowTrClassName?: string;
80
80
  } & Omit<JSX.IntrinsicElements['table'], 'children'> & PaginationProps & SubscriptionFields;
81
- export declare function OrderList({ number, type, children, columns, loadingElement, showActions, showPagination, sortBy, pageSize, paginationContainerClassName, actionsComponent, actionsContainerClassName, theadClassName, rowTrClassName, ...p }: Props): JSX.Element;
81
+ export declare function OrderList({ id, type, children, columns, loadingElement, showActions, showPagination, sortBy, pageSize, paginationContainerClassName, actionsComponent, actionsContainerClassName, theadClassName, rowTrClassName, ...p }: Props): JSX.Element;
82
82
  export default OrderList;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useReactTable,getCoreRowModel,getPaginationRowModel,getSortedRowModel,flexRender}from"@tanstack/react-table";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({number,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),[sorting,setSorting]=useState(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=useState({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=useContext(CustomerContext);useEffect(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,number})},[pageIndex,currentPageSize,number!=null]);const data=useMemo(()=>type==="subscriptions"?subscriptions??[]:orders??[],[orders,subscriptions]),cols=useMemo(()=>columns,[columns]),pagination=useMemo(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=orders?.pageCount??subscriptions?.pageCount??-1,table=useReactTable({data,columns:cols,getSortedRowModel:getSortedRowModel(),getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),manualPagination:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";useEffect(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:columns[k]?.className,children:_jsxs("span",{className:`${columns[k]?.titleClassName??""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[flexRender(header.column.columnDef.header,header.getContext()),{asc:sortAscIcon,desc:sortDescIcon}[header.column.getIsSorted()]??null]})},header.id)});return _jsx(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return _jsx(TrHtmlElement,{className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=orders?.meta.recordCount??subscriptions?.meta.recordCount??0,Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?_jsx(_Fragment,{children:LoadingComponent}):(type==="orders"?orders:subscriptions)?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{children:components})]}),totalRows<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
2
+ import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo,useState,useEffect}from"react";import CustomerContext from"../../context/CustomerContext";import OrderListChildrenContext from"../../context/OrderListChildrenContext";import OrderListPagination from"../../context/OrderListPaginationContext";import{useReactTable,getCoreRowModel,getPaginationRowModel,getSortedRowModel,flexRender}from"@tanstack/react-table";import{sortDescIcon,sortAscIcon}from"../../utils/icons";import filterChildren from"../../utils/filterChildren";const rowComponents=["OrderListRow","OrderListEmpty"],paginationComponents=["OrderListPaginationInfo","OrderListPaginationButtons"];export function OrderList({id,type="orders",children,columns,loadingElement,showActions=!1,showPagination=!1,sortBy=[{id:"number",desc:!0}],pageSize=10,paginationContainerClassName,actionsComponent,actionsContainerClassName,theadClassName,rowTrClassName,...p}){const[loading,setLoading]=useState(!0),[sorting,setSorting]=useState(sortBy),[{pageIndex,pageSize:currentPageSize},setPagination]=useState({pageIndex:0,pageSize}),{orders,subscriptions,getCustomerOrders,getCustomerSubscriptions}=useContext(CustomerContext);useEffect(()=>{type==="orders"&&getCustomerOrders!=null&&getCustomerOrders({pageNumber:pageIndex+1,pageSize:currentPageSize}),type==="subscriptions"&&getCustomerSubscriptions!=null&&getCustomerSubscriptions({pageNumber:pageIndex+1,pageSize:currentPageSize,id})},[pageIndex,currentPageSize,id!=null]);const data=useMemo(()=>type==="subscriptions"?subscriptions??[]:orders??[],[orders,subscriptions]),cols=useMemo(()=>columns,[columns]),pagination=useMemo(()=>({pageIndex,pageSize:currentPageSize}),[pageIndex,currentPageSize]),pageCount=orders?.pageCount??subscriptions?.pageCount??-1,table=useReactTable({data,columns:cols,getSortedRowModel:getSortedRowModel(),getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),manualPagination:!0,pageCount,state:{sorting,pagination},onSortingChange:setSorting,onPaginationChange:setPagination}),TableHtmlElement="table",TheadHtmlElement="thead",TbodyHtmlElement="tbody",ThHtmlElement="th",TrHtmlElement="tr";useEffect(()=>(type==="orders"&&orders!=null&&setLoading(!1),type==="subscriptions"&&subscriptions!=null&&setLoading(!1),()=>{setLoading(!0)}),[orders,subscriptions]);const LoadingComponent=loadingElement||_jsx("div",{children:"Loading..."}),headerComponent=table.getHeaderGroups().map(headerGroup=>{const columnsComponents=headerGroup.headers.map((header,k)=>{const sortLabel=header.column.getIsSorted()!==!1?header.column.getIsSorted():"";return _jsx(ThHtmlElement,{"data-testid":`thead-${k}`,"data-sort":`${sortLabel||""}`,className:columns[k]?.className,children:_jsxs("span",{className:`${columns[k]?.titleClassName??""} ${header.column.getCanSort()?"cursor-pointer select-none":""}`,onClick:header.column.getToggleSortingHandler(),children:[flexRender(header.column.columnDef.header,header.getContext()),{asc:sortAscIcon,desc:sortDescIcon}[header.column.getIsSorted()]??null]})},header.id)});return _jsx(TrHtmlElement,{children:columnsComponents},headerGroup.id)}),rowsComponents=filterChildren({children,filterBy:rowComponents,componentName:"OrderList"}),components=table.getRowModel().rows.map(row=>{const childProps={type,orders:type==="orders"?orders:subscriptions,order:row.original,row,showActions,actionsComponent,actionsContainerClassName};return _jsx(TrHtmlElement,{className:rowTrClassName,children:_jsx(OrderListChildrenContext.Provider,{value:childProps,children:rowsComponents})},row.id)}),pagComponents=filterChildren({children,filterBy:paginationComponents,componentName:"OrderList"}),totalRows=type==="orders"?orders?.meta.recordCount??0:subscriptions?.meta.recordCount??0,Pagination=()=>showPagination?_jsx(OrderListPagination.Provider,{value:{canNextPage:table.getCanNextPage(),canPreviousPage:table.getCanPreviousPage(),gotoPage:table.setPageIndex,nextPage:table.nextPage,pageCount:table.getPageCount(),pageIndex:table.getState().pagination.pageIndex,pageOptions:table.getPageOptions(),pageSize:table.getState().pagination.pageSize,previousPage:table.previousPage,setPageSize:table.setPageSize,totalRows},children:pagComponents}):null;return loading&&(orders==null||subscriptions==null)?_jsx(_Fragment,{children:LoadingComponent}):(type==="orders"?orders:subscriptions)?.length===0?_jsxs(OrderListChildrenContext.Provider,{value:{orders:type==="orders"?orders:subscriptions},children:[rowsComponents,_jsx(Pagination,{})]}):_jsxs(_Fragment,{children:[_jsxs(TableHtmlElement,{...p,children:[_jsx(TheadHtmlElement,{className:theadClassName,children:headerComponent}),_jsx(TbodyHtmlElement,{children:components})]}),totalRows<=pageSize?null:_jsx("div",{className:paginationContainerClassName,children:_jsx(Pagination,{})})]})}export default OrderList;
@@ -102,4 +102,5 @@ export * from './components/stock_transfers/StockTransfer';
102
102
  export * from './components/stock_transfers/StockTransferField';
103
103
  export * from './hooks/useOrderContainer';
104
104
  export * from './hooks/useCommerceLayer';
105
+ export * from './hooks/useCustomerContainer';
105
106
  export * from './typings/errors';
package/lib/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export*from"./components/ExternalFunction";export*from"./components/MetadataInput";export*from"./components/SubmitButton";export*from"./components/addresses/Address";export*from"./components/addresses/AddressCountrySelector";export*from"./components/addresses/AddressField";export*from"./components/addresses/AddressInput";export*from"./components/addresses/AddressStateSelector";export*from"./components/addresses/AddressesContainer";export*from"./components/addresses/AddressesEmpty";export*from"./components/addresses/BillingAddressContainer";export*from"./components/addresses/BillingAddressForm";export*from"./components/addresses/SaveAddressesButton";export*from"./components/addresses/ShippingAddressContainer";export*from"./components/addresses/ShippingAddressForm";export*from"./components/auth/CommerceLayer";export*from"./components/customers/CustomerAddressForm";export*from"./components/customers/CustomerContainer";export*from"./components/customers/CustomerField";export*from"./components/customers/CustomerInput";export*from"./components/customers/SaveCustomerButton";export*from"./components/errors/Errors";export*from"./components/gift_cards/GiftCard";export*from"./components/gift_cards/GiftCardContainer";export*from"./components/gift_cards/GiftCardCurrencySelector";export*from"./components/gift_cards/GiftCardInput";export*from"./components/gift_cards/GiftCardOrCouponCode";export*from"./components/gift_cards/GiftCardOrCouponForm";export*from"./components/gift_cards/GiftCardOrCouponInput";export*from"./components/gift_cards/GiftCardOrCouponRemoveButton";export*from"./components/gift_cards/GiftCardOrCouponSubmit";export*from"./components/in_stock_subscriptions/InStockSubscriptionButton";export*from"./components/in_stock_subscriptions/InStockSubscriptionsContainer";export*from"./components/line_items/LineItem";export*from"./components/line_items/LineItemAmount";export*from"./components/line_items/LineItemCode";export*from"./components/line_items/LineItemField";export*from"./components/line_items/LineItemImage";export*from"./components/line_items/LineItemName";export*from"./components/line_items/LineItemOption";export*from"./components/line_items/LineItemOptions";export*from"./components/line_items/LineItemQuantity";export*from"./components/line_items/LineItemRemoveLink";export*from"./components/line_items/LineItemsContainer";export*from"./components/line_items/LineItemsCount";export*from"./components/line_items/LineItemsEmpty";export*from"./components/orders/AddToCartButton";export*from"./components/orders/AdjustmentAmount";export*from"./components/orders/CartLink";export*from"./components/orders/CheckoutLink";export*from"./components/orders/DiscountAmount";export*from"./components/orders/GiftCardAmount";export*from"./components/orders/OrderContainer";export*from"./components/orders/OrderList";export*from"./components/orders/OrderListEmpty";export*from"./components/orders/OrderListRow";export*from"./components/orders/OrderNumber";export*from"./components/orders/OrderStorage";export*from"./components/orders/PaymentMethodAmount";export*from"./components/orders/PlaceOrderButton";export*from"./components/orders/PlaceOrderContainer";export*from"./components/orders/PrivacyAndTermsCheckbox";export*from"./components/orders/ShippingAmount";export*from"./components/orders/SubTotalAmount";export*from"./components/orders/TaxesAmount";export*from"./components/orders/TotalAmount";export*from"./components/parcels/ParcelField";export*from"./components/parcels/ParcelLineItem";export*from"./components/parcels/ParcelLineItemField";export*from"./components/parcels/ParcelLineItemsCount";export*from"./components/parcels/Parcels";export*from"./components/parcels/ParcelsCount";export*from"./components/payment_methods/PaymentMethod";export*from"./components/payment_methods/PaymentMethodName";export*from"./components/payment_methods/PaymentMethodPrice";export*from"./components/payment_methods/PaymentMethodRadioButton";export*from"./components/payment_methods/PaymentMethodsContainer";export*from"./components/payment_source/PaymentSource";export*from"./components/payment_source/PaymentSourceBrandIcon";export*from"./components/payment_source/PaymentSourceBrandName";export*from"./components/payment_source/PaymentSourceDetail";export*from"./components/payment_source/PaymentSourceEditButton";export*from"./components/prices/Price";export*from"./components/prices/PricesContainer";export*from"./components/shipments/Shipment";export*from"./components/shipments/ShipmentField";export*from"./components/shipments/ShipmentsContainer";export*from"./components/shipments/ShipmentsCount";export*from"./components/shipping_methods/ShippingMethod";export*from"./components/shipping_methods/ShippingMethodName";export*from"./components/shipping_methods/ShippingMethodPrice";export*from"./components/shipping_methods/ShippingMethodRadioButton";export*from"./components/skus/AvailabilityContainer";export*from"./components/skus/AvailabilityTemplate";export*from"./components/skus/DeliveryLeadTime";export*from"./components/skus/SkuField";export*from"./components/skus/SkuList";export*from"./components/skus/SkuListsContainer";export*from"./components/skus/Skus";export*from"./components/skus/SkusContainer";export*from"./components/stock_transfers/StockTransfer";export*from"./components/stock_transfers/StockTransferField";export*from"./hooks/useOrderContainer";export*from"./hooks/useCommerceLayer";export*from"./typings/errors";
2
+ export*from"./components/ExternalFunction";export*from"./components/MetadataInput";export*from"./components/SubmitButton";export*from"./components/addresses/Address";export*from"./components/addresses/AddressCountrySelector";export*from"./components/addresses/AddressField";export*from"./components/addresses/AddressInput";export*from"./components/addresses/AddressStateSelector";export*from"./components/addresses/AddressesContainer";export*from"./components/addresses/AddressesEmpty";export*from"./components/addresses/BillingAddressContainer";export*from"./components/addresses/BillingAddressForm";export*from"./components/addresses/SaveAddressesButton";export*from"./components/addresses/ShippingAddressContainer";export*from"./components/addresses/ShippingAddressForm";export*from"./components/auth/CommerceLayer";export*from"./components/customers/CustomerAddressForm";export*from"./components/customers/CustomerContainer";export*from"./components/customers/CustomerField";export*from"./components/customers/CustomerInput";export*from"./components/customers/SaveCustomerButton";export*from"./components/errors/Errors";export*from"./components/gift_cards/GiftCard";export*from"./components/gift_cards/GiftCardContainer";export*from"./components/gift_cards/GiftCardCurrencySelector";export*from"./components/gift_cards/GiftCardInput";export*from"./components/gift_cards/GiftCardOrCouponCode";export*from"./components/gift_cards/GiftCardOrCouponForm";export*from"./components/gift_cards/GiftCardOrCouponInput";export*from"./components/gift_cards/GiftCardOrCouponRemoveButton";export*from"./components/gift_cards/GiftCardOrCouponSubmit";export*from"./components/in_stock_subscriptions/InStockSubscriptionButton";export*from"./components/in_stock_subscriptions/InStockSubscriptionsContainer";export*from"./components/line_items/LineItem";export*from"./components/line_items/LineItemAmount";export*from"./components/line_items/LineItemCode";export*from"./components/line_items/LineItemField";export*from"./components/line_items/LineItemImage";export*from"./components/line_items/LineItemName";export*from"./components/line_items/LineItemOption";export*from"./components/line_items/LineItemOptions";export*from"./components/line_items/LineItemQuantity";export*from"./components/line_items/LineItemRemoveLink";export*from"./components/line_items/LineItemsContainer";export*from"./components/line_items/LineItemsCount";export*from"./components/line_items/LineItemsEmpty";export*from"./components/orders/AddToCartButton";export*from"./components/orders/AdjustmentAmount";export*from"./components/orders/CartLink";export*from"./components/orders/CheckoutLink";export*from"./components/orders/DiscountAmount";export*from"./components/orders/GiftCardAmount";export*from"./components/orders/OrderContainer";export*from"./components/orders/OrderList";export*from"./components/orders/OrderListEmpty";export*from"./components/orders/OrderListRow";export*from"./components/orders/OrderNumber";export*from"./components/orders/OrderStorage";export*from"./components/orders/PaymentMethodAmount";export*from"./components/orders/PlaceOrderButton";export*from"./components/orders/PlaceOrderContainer";export*from"./components/orders/PrivacyAndTermsCheckbox";export*from"./components/orders/ShippingAmount";export*from"./components/orders/SubTotalAmount";export*from"./components/orders/TaxesAmount";export*from"./components/orders/TotalAmount";export*from"./components/parcels/ParcelField";export*from"./components/parcels/ParcelLineItem";export*from"./components/parcels/ParcelLineItemField";export*from"./components/parcels/ParcelLineItemsCount";export*from"./components/parcels/Parcels";export*from"./components/parcels/ParcelsCount";export*from"./components/payment_methods/PaymentMethod";export*from"./components/payment_methods/PaymentMethodName";export*from"./components/payment_methods/PaymentMethodPrice";export*from"./components/payment_methods/PaymentMethodRadioButton";export*from"./components/payment_methods/PaymentMethodsContainer";export*from"./components/payment_source/PaymentSource";export*from"./components/payment_source/PaymentSourceBrandIcon";export*from"./components/payment_source/PaymentSourceBrandName";export*from"./components/payment_source/PaymentSourceDetail";export*from"./components/payment_source/PaymentSourceEditButton";export*from"./components/prices/Price";export*from"./components/prices/PricesContainer";export*from"./components/shipments/Shipment";export*from"./components/shipments/ShipmentField";export*from"./components/shipments/ShipmentsContainer";export*from"./components/shipments/ShipmentsCount";export*from"./components/shipping_methods/ShippingMethod";export*from"./components/shipping_methods/ShippingMethodName";export*from"./components/shipping_methods/ShippingMethodPrice";export*from"./components/shipping_methods/ShippingMethodRadioButton";export*from"./components/skus/AvailabilityContainer";export*from"./components/skus/AvailabilityTemplate";export*from"./components/skus/DeliveryLeadTime";export*from"./components/skus/SkuField";export*from"./components/skus/SkuList";export*from"./components/skus/SkuListsContainer";export*from"./components/skus/Skus";export*from"./components/skus/SkusContainer";export*from"./components/stock_transfers/StockTransfer";export*from"./components/stock_transfers/StockTransferField";export*from"./hooks/useOrderContainer";export*from"./hooks/useCommerceLayer";export*from"./hooks/useCustomerContainer";export*from"./typings/errors";
@@ -1,10 +1,18 @@
1
1
  import { type Dispatch } from 'react';
2
- import { type BaseError } from '../typings/errors';
2
+ import { type CodeErrorType, type BaseError } from '../typings/errors';
3
3
  import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
4
4
  import { type Address, type AddressCreate, type Order } from '@commercelayer/sdk';
5
5
  import { type updateOrder } from './OrderReducer';
6
6
  import { type TCustomerAddress } from './CustomerReducer';
7
7
  import { type TResourceError } from '../components/errors/Errors';
8
+ import { type AddressValuesKeys } from '../context/BillingAddressFormContext';
9
+ import { type AddressInputName } from '../typings/index';
10
+ export type CustomFieldMessageError = (props: {
11
+ field: Extract<AddressValuesKeys, AddressInputName> | string;
12
+ code: Extract<CodeErrorType, 'EMPTY_ERROR' | 'VALIDATION_ERROR'> | undefined;
13
+ message: string | undefined;
14
+ value: string;
15
+ }) => string | null;
8
16
  export type AddressActionType = 'setErrors' | 'setAddress' | 'setShipToDifferentAddress' | 'setCloneAddress' | 'cleanup';
9
17
  export type AddressField = 'city' | 'company' | 'country_code' | 'first_name' | 'last_name' | 'line_1' | 'line_2' | 'phone' | 'state_code' | 'zip_code' | 'billing_info';
10
18
  export type AddressFieldView = AddressField | 'full_address' | 'full_name';
@@ -118,12 +118,12 @@ interface GetCustomerOrdersProps {
118
118
  */
119
119
  pageNumber?: number;
120
120
  /**
121
- * Retrieve a specific subscription or order by number
121
+ * Retrieve a specific subscription or order by id
122
122
  */
123
- number?: string;
123
+ id?: string;
124
124
  }
125
125
  export declare function getCustomerOrders({ config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
126
- export declare function getCustomerSubscriptions({ number, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
126
+ export declare function getCustomerSubscriptions({ id, config, dispatch, pageSize, pageNumber }: GetCustomerOrdersProps): Promise<void>;
127
127
  export type TCustomerAddress = AddressCreate & AddressUpdate & Record<string, string | null | undefined>;
128
128
  interface TCreateCustomerAddress {
129
129
  /**
@@ -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.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=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({number,config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=jwt(config.accessToken);if(owner?.id){const sdk=getSdk(config);if(number!=null){const subscriptions=await sdk.customers.orders(owner.id,{filters:{order_subscription_number_eq:number},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";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch,isOrderAvailable}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&(customerAddress.id!==customerAddress.address.reference&&!isOrderAvailable&&(customerAddress.address.reference=customerAddress.id),addresses.push(customerAddress.address))}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch,pageSize=10,pageNumber=1}){if(config.accessToken){const{owner}=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;
@@ -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}){let billingDisable=invertAddresses?!!(!shippingDisable&&shipToDifferentAddress):!isEmpty(errors)||isEmpty(billing_address);if(isEmpty(errors)&&!isEmpty(billing_address))if(invertAddresses)billingDisable=!!(billing_address&&fieldsExist(billing_address));else{let billingInfo=[...addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),billingDisable=!!(billing_address&&fieldsExist(billing_address,billingInfo))}return billingDisable&&!isEmpty(billingAddressId)&&isEmpty(billing_address)&&(billingDisable=!1),billingDisable}export function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1}){let shippingDisable=invertAddresses?!isEmpty(errors)||isEmpty(shipping_address):!!(!billingDisable&&shipToDifferentAddress);if(isEmpty(errors)&&!isEmpty(shipping_address))if(invertAddresses){let billingInfo=[...addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),shippingDisable=!!(shipping_address&&fieldsExist(shipping_address,billingInfo))}else shipToDifferentAddress&&(delete shipping_address?.billing_info,shippingDisable=!!(shipping_address&&fieldsExist(shipping_address)));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===billingAddressId&&(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}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId});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}){let billingDisable=invertAddresses?!!(!shippingDisable&&shipToDifferentAddress):!isEmpty(errors)||isEmpty(billing_address);if(isEmpty(errors)&&!isEmpty(billing_address))if(invertAddresses)billingDisable=!!(billing_address&&fieldsExist(billing_address));else{let billingInfo=[...addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),billingDisable=!!(billing_address&&fieldsExist(billing_address,billingInfo))}return billingDisable&&!isEmpty(billingAddressId)&&isEmpty(billing_address)&&(billingDisable=!1),billingDisable}export function shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses=!1,requiresBillingInfo=!1}){let shippingDisable=invertAddresses?!isEmpty(errors)||isEmpty(shipping_address):!!(!billingDisable&&shipToDifferentAddress);if(isEmpty(errors)&&!isEmpty(shipping_address))if(invertAddresses){let billingInfo=[...addressFields];requiresBillingInfo&&(billingInfo=[...billingInfo,"billing_info"]),shippingDisable=!!(shipping_address&&fieldsExist(shipping_address,billingInfo))}else shipToDifferentAddress&&(delete shipping_address?.billing_info,shippingDisable=!!(shipping_address&&fieldsExist(shipping_address)));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}){if(invertAddresses){const shippingDisable2=shippingAddressController({errors,shipToDifferentAddress,shipping_address,shippingAddressId,invertAddresses,requiresBillingInfo}),billingDisable2=billingAddressController({shippingDisable:shippingDisable2,billing_address,billingAddressId,errors,requiresBillingInfo,invertAddresses});return{shippingDisable:shippingDisable2,billingDisable:billingDisable2}}const billingDisable=billingAddressController({billing_address,billingAddressId,errors,requiresBillingInfo}),shippingDisable=shippingAddressController({billingDisable,errors,shipToDifferentAddress,shipping_address,shippingAddressId});return{billingDisable,shippingDisable}}
@@ -11,7 +11,6 @@ export type ValidateFormFields = <R extends string[]>(fields: HTMLFormControlsCo
11
11
  export type ValidateValue = <V extends string | boolean, N extends string, T extends string, B extends TResourceError>(val: V, name: N, type: T, resource: B) => BaseError | Record<string, any>;
12
12
  export declare const validateValue: ValidateValue;
13
13
  declare const validateFormFields: ValidateFormFields;
14
- export type FieldsExist = (address: AddressCreate, schema?: AddressField[]) => boolean;
15
- export declare const fieldsExist: FieldsExist;
14
+ export declare function fieldsExist(address: AddressCreate, schema?: AddressField[]): boolean;
16
15
  export declare function businessMandatoryField(fieldName: AddressInputName, isBusiness?: boolean): boolean;
17
16
  export default validateFormFields;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import isEmpty from"lodash/isEmpty";import isString from"lodash/isString";import without from"lodash/without";import keys from"lodash/keys";import map from"lodash/map";import{addressFields}from"../reducers/AddressReducer";const EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;export const validateValue=(val,name,type,resource)=>val?type==="email"&&isString(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return map(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=validateValue(val,v.name,v.type,resourceType);isEmpty(error)||errors.push(error),values={...values,[`${v.name}`]:val}}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?{...values,metadata:{...values.metadata,[`${v.name}`]:val}}:{...values,[`${v.name}`]:val})}),{errors,values}};export const fieldsExist=(address,schema=addressFields)=>{if(address.business){const required=without(schema,"first_name","last_name","line_2"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=without(schema,"line_2","company"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}};const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];export function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}export default validateFormFields;
2
+ import isEmpty from"lodash/isEmpty";import isString from"lodash/isString";import without from"lodash/without";import keys from"lodash/keys";import map from"lodash/map";import{addressFields}from"../reducers/AddressReducer";const EMAIL_PATTERN=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;export const validateValue=(val,name,type,resource)=>val?type==="email"&&isString(val)&&!val.match(EMAIL_PATTERN)?{field:name,code:"VALIDATION_ERROR",message:"please enter a valid format",resource}:{}:{field:name,code:"VALIDATION_ERROR",message:`${name} - is required`,resource};const validateFormFields=(fields,required,resourceType)=>{const errors=[];let values={metadata:{}};return map(fields,v=>{const val="checked"in v||(v.value==="on"?!1:v.value),attrName=v.getAttribute("name");if(attrName&&required.includes(attrName)||v.required){const error=validateValue(val,v.name,v.type,resourceType);isEmpty(error)||errors.push(error),values={...values,[`${v.name}`]:val}}v.getAttribute("name")&&(values=!!v.getAttribute("data-metadata")?{...values,metadata:{...values.metadata,[`${v.name}`]:val}}:{...values,[`${v.name}`]:val})}),{errors,values}};export function fieldsExist(address,schema=addressFields){if(address.business){const required=without(schema,"first_name","last_name","line_2"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}else{const required=without(schema,"line_2","company"),validAddress=keys(address).filter(k=>required.includes(k));return required.length>validAddress.length}}const businessOptionalFields=["billing_address_first_name","billing_address_last_name","shipping_address_first_name","shipping_address_last_name","first_name","last_name"],customerOptionalFields=["billing_address_company","shipping_address_company","company"];export function businessMandatoryField(fieldName,isBusiness){return!(isBusiness&&businessOptionalFields.includes(fieldName)||!isBusiness&&customerOptionalFields.includes(fieldName))}export default validateFormFields;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.9.0",
3
+ "version": "4.10.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",
@@ -208,12 +208,12 @@
208
208
  "vitest": "^1.2.2"
209
209
  },
210
210
  "peerDependencies": {
211
- "react": "^18.0.0"
211
+ "react": ">=18.0.0"
212
212
  },
213
213
  "scripts": {
214
214
  "lint": "eslint src --ext .ts,.tsx",
215
215
  "lint:fix": "eslint src --ext .ts,.tsx --fix",
216
- "test": "pnpm lint && vitest run --silent",
216
+ "test": "pnpm audit --audit-level high && (pnpm audit || exit 0) && pnpm lint && vitest run --silent",
217
217
  "coverage": "vitest run --coverage",
218
218
  "test:e2e": "NODE_ENV=test playwright test",
219
219
  "test:e2e:coverage": "nyc pnpm test:e2e && pnpm coverage:report",