UNPKG

@shopgate/engage

Version:
22 lines • 11.6 kB
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance");}function _iterableToArrayLimit(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}import React,{createContext,useMemo,useEffect,useContext,useCallback,useState}from'react';import PropTypes from'prop-types';import{connect}from'react-redux';import{getShopSettings}from'@shopgate/engage/core/config';import{getPreferredLocationAddress}from'@shopgate/engage/locations/selectors';import{useRoute,i18n,historyPush,EVALIDATION}from'@shopgate/engage/core';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';import{useFormState as useForm,convertValidationErrors}from'@shopgate/engage/core/hooks/useFormState';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{LoadingProvider,ToastProvider}from'@shopgate/pwa-common/providers';import UIEvents from'@shopgate/pwa-core/emitters/ui';import{CHECKOUT_ADDRESS_BOOK_CONTACT_PATTERN,useAddressBook}from'@shopgate/engage/checkout';import{PROFILE_ADDRESS_PATH}from"../../constants/routes";import{fetchCustomerContacts}from"../../actions/fetchContacts";import{fetchCustomerData}from"../../actions/fetchCustomer";import{updateCustomerData}from"../../actions/updateCustomer";import{deleteCustomerContact}from"../../actions/deleteContact";import{deleteCustomer as deleteCustomerAction}from"../../actions/deleteCustomer";import{getContacts}from"../../selectors/contacts";import{getCustomer}from"../../selectors/customer";import{extractAttributes,extractDefaultValues,convertPipelineValidationErrors}from"../../helper/form";import createConstraints from"./Profile.constraints";var ProfileContext=createContext();/** * @returns {Array} */export var useProfileContext=function useProfileContext(){return useContext(ProfileContext);};/** * @param {Object} state State. * @returns {Object} */var mapStateToProps=function mapStateToProps(state){return{contacts:getContacts(state),customer:getCustomer(state),merchantCustomerAttributes:getMerchantCustomerAttributes(state),shopSettings:getShopSettings(state),userLocation:getPreferredLocationAddress(state)};};/** * @param {Function} dispatch Dispatch. * @returns {Object} */var mapDispatchToProps=function mapDispatchToProps(dispatch){return{fetchContacts:function fetchContacts(){return dispatch(fetchCustomerContacts());},deleteContact:function deleteContact(customerId){return dispatch(deleteCustomerContact(customerId));},deleteCustomer:function deleteCustomer(){return dispatch(deleteCustomerAction());},fetchCustomer:function fetchCustomer(){return dispatch(fetchCustomerData());},updateCustomer:function updateCustomer(customer){return dispatch(updateCustomerData(customer));},showDialog:function showDialog(props){return dispatch(showModal(props));},push:function push(props){return dispatch(historyPush(props));}};};/** * @returns {JSX} */var ProfileProvider=function ProfileProvider(_ref){var fetchContacts=_ref.fetchContacts,deleteContact=_ref.deleteContact,fetchCustomer=_ref.fetchCustomer,updateCustomer=_ref.updateCustomer,deleteCustomer=_ref.deleteCustomer,push=_ref.push,showDialog=_ref.showDialog,contacts=_ref.contacts,customer=_ref.customer,merchantCustomerAttributes=_ref.merchantCustomerAttributes,children=_ref.children,shopSettings=_ref.shopSettings,userLocation=_ref.userLocation,formContainerRef=_ref.formContainerRef;// Route var _useRoute=useRoute(),pathname=_useRoute.pathname;var _useAddressBook=useAddressBook(),isCheckout=_useAddressBook.isCheckout,type=_useAddressBook.type,deleteContactFromOrder=_useAddressBook.deleteContactFromOrder;var _useState=useState(null),_useState2=_slicedToArray(_useState,2),requestErrors=_useState2[0],setRequestErrors=_useState2[1];// Default state. var defaultState=useMemo(function(){return customer?_extends({},customer,{marketingOptIn:customer.settings.marketingOptIn||false},extractDefaultValues(customer.attributes)):null;},[customer]);// Saving the form. var saveForm=useCallback(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(values){var attributes,validationErrors,code,errors,converted,_converted$validation;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:LoadingProvider.setLoading(pathname);attributes=extractAttributes(merchantCustomerAttributes,values);_context.prev=2;_context.next=5;return updateCustomer(_extends({firstName:values.firstName},values.middleName?{middleName:values.middleName}:{},{lastName:values.lastName,emailAddress:values.emailAddress,settings:{marketingOptIn:values.marketingOptIn},attributes:attributes}));case 5:_context.next=7;return fetchCustomer();case 7:UIEvents.emit(ToastProvider.ADD,{id:'account.profile.form.success',message:'account.profile.form.success'});_context.next=15;break;case 10:_context.prev=10;_context.t0=_context["catch"](2);code=_context.t0.code,errors=_context.t0.errors;if(code===EVALIDATION){converted=convertPipelineValidationErrors(errors,attributes);if((converted===null||converted===void 0?void 0:converted.validation)&&Object.keys(converted.validation).length>0){validationErrors=converted===null||converted===void 0?void 0:(_converted$validation=converted.validation)===null||_converted$validation===void 0?void 0:_converted$validation.attributes;}}UIEvents.emit(ToastProvider.ADD,{id:'account.profile.form.error',message:'account.profile.form.error'});case 15:setRequestErrors(validationErrors||null);LoadingProvider.unsetLoading(pathname);case 17:case"end":return _context.stop();}},_callee,null,[[2,10]]);}));return function(_x){return _ref2.apply(this,arguments);};}(),[fetchCustomer,merchantCustomerAttributes,pathname,updateCustomer]);// Hold profile form state. var constraints=useMemo(function(){return createConstraints(merchantCustomerAttributes);},[merchantCustomerAttributes]);var formState=useForm(defaultState,saveForm,constraints,formContainerRef,120);var validationErrors=useMemo(function(){return convertValidationErrors(formState.validationErrors||requestErrors||{});},[formState.validationErrors,requestErrors]);useEffect(function(){formState.scrollToError();// eslint-disable-next-line react-hooks/exhaustive-deps },[formState.scrollToError,requestErrors]);/** * Executes callback with confirmation beforehand. * @param {string} message String */var confirmation=/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(message){var confirmed;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=2;return showDialog({title:i18n.text('account.profile.confirm.title'),message:i18n.text(message),confirm:i18n.text('account.profile.confirm.confirm')});case 2:confirmed=_context2.sent;return _context2.abrupt("return",!!confirmed);case 4:case"end":return _context2.stop();}},_callee2);}));return function confirmation(_x2){return _ref3.apply(this,arguments);};}();// Deletes a contact. /* eslint-disable react-hooks/exhaustive-deps */var deleteContactWrapper=useCallback(/*#__PURE__*/function(){var _ref4=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(contactId){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=2;return confirmation('account.profile.confirm.messageContact');case 2:if(_context3.sent){_context3.next=4;break;}return _context3.abrupt("return");case 4:LoadingProvider.setLoading(pathname);_context3.prev=5;_context3.next=8;return deleteContact(contactId);case 8:_context3.next=10;return fetchContacts();case 10:if(!deleteContactFromOrder){_context3.next=13;break;}_context3.next=13;return deleteContactFromOrder(contactId);case 13:_context3.next=17;break;case 15:_context3.prev=15;_context3.t0=_context3["catch"](5);case 17:LoadingProvider.unsetLoading(pathname);case 18:case"end":return _context3.stop();}},_callee3,null,[[5,15]]);}));return function(_x3){return _ref4.apply(this,arguments);};}(),[deleteContact,fetchContacts,pathname]);var deleteCustomerWrapper=useCallback(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=2;return confirmation('account.profile.confirm.messageCustomer');case 2:if(_context4.sent){_context4.next=4;break;}return _context4.abrupt("return");case 4:LoadingProvider.setLoading(pathname);_context4.prev=5;_context4.next=8;return deleteCustomer();case 8:_context4.next=12;break;case 10:_context4.prev=10;_context4.t0=_context4["catch"](5);case 12:LoadingProvider.unsetLoading(pathname);case 13:case"end":return _context4.stop();}},_callee4,null,[[5,10]]);})),[deleteContact,fetchContacts,pathname]);/* eslint-enable react-hooks/exhaustive-deps */var editContact=useCallback(function(contact){var editPathname=isCheckout?"".concat(CHECKOUT_ADDRESS_BOOK_CONTACT_PATTERN).replace(':type',type):PROFILE_ADDRESS_PATH;push({pathname:editPathname,state:{contact:contact}});},[isCheckout,push,type]);// Store context value. var contextValue=useMemo(function(){return{contacts:contacts,validationErrors:validationErrors,merchantCustomerAttributes:merchantCustomerAttributes,customer:defaultState,isCheckout:isCheckout,supportedCountries:shopSettings.supportedCountries,countrySortOrder:shopSettings.countrySortOrder,userLocation:userLocation,formState:formState,saveForm:formState.handleSubmit,editContact:editContact,deleteContact:deleteContactWrapper,deleteCustomer:deleteCustomerWrapper};},[userLocation,shopSettings.supportedCountries,shopSettings.countrySortOrder,contacts,merchantCustomerAttributes,isCheckout,defaultState,deleteContactWrapper,deleteCustomerWrapper,editContact,formState,validationErrors]);// Fetch all required data for the profile page. useEffect(function(){fetchContacts();fetchCustomer();},[fetchContacts,fetchCustomer]);if(!customer){return null;}return React.createElement(ProfileContext.Provider,{value:contextValue},children);};ProfileProvider.defaultProps={customer:null,formContainerRef:null};export default connect(mapStateToProps,mapDispatchToProps)(ProfileProvider);