@shopgate/engage
Version:
Shopgate's ENGAGE library.
22 lines • 17.6 kB
JavaScript
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 _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;}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);}import React,{useMemo,useState,useCallback,useEffect}from'react';import PropTypes from'prop-types';import pickBy from'lodash/pickBy';import identity from'lodash/identity';import appConfig from'@shopgate/pwa-common/helpers/config';import{useFormState}from'@shopgate/engage/core/hooks/useFormState';import{useScrollTo}from'@shopgate/engage/core/hooks/useScrollTo';import{LoadingProvider,i18n,useAsyncMemo,useRoute,SHOP_SETTING_REGISTRATION_MODE_EXTENDED}from'@shopgate/engage/core';import{ADDRESS_TYPE_SHIPPING,ADDRESS_TYPE_PICKUP}from'@shopgate/engage/checkout';import{extractDefaultValues}from"../../account/helper/form";import{GUEST_CHECKOUT_PATTERN,GUEST_CHECKOUT_PAYMENT_PATTERN}from"../../checkout/constants/routes";import Context from"./GuestRegistrationProvider.context";import{generateBillingConstraints,generateShippingConstraints,generatePickupConstraints,generateSelfPickupConstraints,generateExtraConstraints}from"./GuestRegistrationProvider.constraints";import{MARKETING_OPT_IN_DEFAULT,ELEMENT_ID_SHIPPING_CONTACT,ELEMENT_ID_SHIPPING_CONTACT_TOGGLE,ELEMENT_ID_PICKUP_CONTACT}from"../constants";import connect from"./GuestRegistrationProvider.connector";var initialAddressFormState={firstName:'',lastName:'',company:'',address1:'',address2:'',city:'',country:'',postalCode:'',mobile:''};var initialBillingFormState=_extends({},initialAddressFormState);var initialShippingFormState=_extends({},initialAddressFormState);var initialPickupFormState={pickupPerson:'me',firstName:'',lastName:'',mobile:'',emailAddress:''};var initialOptInFormState={marketingOptIn:MARKETING_OPT_IN_DEFAULT};/**
* Converts validation errors into errors for form builder.
* @param {Object} validationErrors The validation errors.
* @returns {Array}
*/var convertValidationErrors=function convertValidationErrors(validationErrors){return Object.keys(validationErrors).map(function(key){return{path:key,message:i18n.text(validationErrors[key])};});};/**
* @param {Object} props The provider props
* @returns {JSX}
*/var GuestRegistrationProvider=function GuestRegistrationProvider(_ref){var children=_ref.children,formContainerRef=_ref.formContainerRef,isDataReady=_ref.isDataReady,userLocation=_ref.userLocation,customerAttributes=_ref.customerAttributes,billingAddress=_ref.billingAddress,shippingAddress=_ref.shippingAddress,pickupAddress=_ref.pickupAddress,customer=_ref.customer,billingPickupEquals=_ref.billingPickupEquals,billingShippingEquals=_ref.billingShippingEquals,numberOfAddressLines=_ref.numberOfAddressLines,cartHasDirectShipItems=_ref.cartHasDirectShipItems,orderReserveOnly=_ref.orderReserveOnly,orderNeedsPayment=_ref.orderNeedsPayment,isShippingAddressSelectionEnabled=_ref.isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled=_ref.isPickupContactSelectionEnabled,shopSettings=_ref.shopSettings,submitGuestRegistration=_ref.submitGuestRegistration,prepareCheckout=_ref.prepareCheckout,isLastStackEntry=_ref.isLastStackEntry,historyPop=_ref.historyPop,historyPush=_ref.historyPush;var _useScrollTo=useScrollTo(formContainerRef),scrollTo=_useScrollTo.scrollTo;var isShippingFormEnabled=useMemo(function(){return cartHasDirectShipItems;},[cartHasDirectShipItems]);var getIsShippingFormVisible=useCallback(function(){return isShippingFormEnabled&&!!shippingAddress&&!billingShippingEquals;},[billingShippingEquals,isShippingFormEnabled,shippingAddress]);var _useState=useState(false),_useState2=_slicedToArray(_useState,2),isLocked=_useState2[0],setIsLocked=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),isBillingFormSubmitted=_useState4[0],setIsBillingFormSubmitted=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isShippingFormSubmitted=_useState6[0],setIsShippingFormSubmitted=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),isExtraFormSubmitted=_useState8[0],setIsExtraFormSubmitted=_useState8[1];var _useState9=useState(false),_useState10=_slicedToArray(_useState9,2),isPickupFormSubmitted=_useState10[0],setIsPickupFormSubmitted=_useState10[1];var _useState11=useState(null),_useState12=_slicedToArray(_useState11,2),billingFormRequestErrors=_useState12[0],setBillingFormRequestErrors=_useState12[1];var _useState13=useState(null),_useState14=_slicedToArray(_useState13,2),shippingFormRequestErrors=_useState14[0],setShippingFormRequestErrors=_useState14[1];var _useState15=useState(null),_useState16=_slicedToArray(_useState15,2),pickupFormRequestErrors=_useState16[0],setPickupFormRequestErrors=_useState16[1];var _useState17=useState(null),_useState18=_slicedToArray(_useState17,2),extraFormRequestErrors=_useState18[0],setExtraFormRequestErrors=_useState18[1];var _useState19=useState(getIsShippingFormVisible()),_useState20=_slicedToArray(_useState19,2),isShippingFormVisible=_useState20[0],setIsShippingFormVisible=_useState20[1];var _useState21=useState(generateSelfPickupConstraints()),_useState22=_slicedToArray(_useState21,2),pickupConstraints=_useState22[0],setPickupConstraints=_useState22[1];var _useRoute=useRoute(),_useRoute$query$edit=_useRoute.query.edit,guestRegistrationEditMode=_useRoute$query$edit===void 0?null:_useRoute$query$edit;// Initialize checkout process.
var _useAsyncMemo=useAsyncMemo(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(!guestRegistrationEditMode){_context.next=2;break;}return _context.abrupt("return",true);case 2:_context.prev=2;setIsLocked(true);_context.next=6;return prepareCheckout({initializePayment:false,initializeOrder:!!isLastStackEntry});case 6:setIsLocked(false);return _context.abrupt("return",true);case 10:_context.prev=10;_context.t0=_context["catch"](2);setIsLocked(false);return _context.abrupt("return",false);case 14:case"end":return _context.stop();}},_callee,null,[[2,10]]);})),[],false),_useAsyncMemo2=_slicedToArray(_useAsyncMemo,1),isInitialized=_useAsyncMemo2[0];useEffect(function(){setIsShippingFormVisible(getIsShippingFormVisible());},[getIsShippingFormVisible,setIsShippingFormVisible]);// Determine values to prefill some form fields
var userCountry=useMemo(function(){return(userLocation===null||userLocation===void 0?void 0:userLocation.country)||(appConfig===null||appConfig===void 0?void 0:appConfig.marketId)||null;},[userLocation]);var userRegion=useMemo(function(){return(userLocation===null||userLocation===void 0?void 0:userLocation.region)||null;},[userLocation]);// ===== billing form =====
var defaultBillingFormState=useMemo(function(){return _extends({},initialBillingFormState,{country:userCountry,region:userRegion},pickBy(billingAddress||{},identity));},[billingAddress,userCountry,userRegion]);var billingConstraints=useMemo(function(){return generateBillingConstraints(orderReserveOnly);},[orderReserveOnly]);var handleBillingFormSubmit=useCallback(function(){setIsBillingFormSubmitted(true);},[setIsBillingFormSubmitted]);var billingFormState=useFormState(defaultBillingFormState,handleBillingFormSubmit,billingConstraints,formContainerRef);// ===== shipping form =====
var defaultShippingFormState=useMemo(function(){return _extends({},initialShippingFormState,{country:userCountry,region:userRegion},!billingShippingEquals?pickBy(shippingAddress||{},identity):{});},[billingShippingEquals,shippingAddress,userCountry,userRegion]);var shippingConstraints=useMemo(function(){return isShippingFormVisible?generateShippingConstraints():{};},[isShippingFormVisible]);var handleShippingFormSubmit=useCallback(function(){setIsShippingFormSubmitted(true);},[setIsShippingFormSubmitted]);var shippingFormState=useFormState(defaultShippingFormState,handleShippingFormSubmit,shippingConstraints,formContainerRef);// ===== pickup contact form =====
var defaultPickupFormState=useMemo(function(){return _extends({},initialPickupFormState,{},!billingPickupEquals?pickBy(pickupAddress||{},identity):{},{pickupPerson:billingPickupEquals?'me':'someoneElse'});},[billingPickupEquals,pickupAddress]);var handlePickupFormSubmit=useCallback(function(){setIsPickupFormSubmitted(true);},[]);var pickupFormState=useFormState(defaultPickupFormState,handlePickupFormSubmit,pickupConstraints,formContainerRef);useEffect(function(){setPickupConstraints(pickupFormState.values.pickupPerson==='me'?generateSelfPickupConstraints():generatePickupConstraints());},[pickupFormState.values.pickupPerson]);// ===== extra form =====
var defaultExtraFormState=useMemo(function(){return _extends({},initialOptInFormState,{},extractDefaultValues((customer===null||customer===void 0?void 0:customer.attributes)||[]));},[customer]);var extraConstraints=useMemo(function(){return generateExtraConstraints(customerAttributes);},[customerAttributes]);var handleExtraFormSubmit=useCallback(function(){setIsExtraFormSubmitted(true);},[]);var extraFormState=useFormState(defaultExtraFormState,handleExtraFormSubmit,extraConstraints,formContainerRef);var handleSubmit=useCallback(function(){billingFormState.handleSubmit();shippingFormState.handleSubmit();pickupFormState.handleSubmit();extraFormState.handleSubmit();},[billingFormState,extraFormState,pickupFormState,shippingFormState]);useEffect(function(){if(!isBillingFormSubmitted||!isShippingFormSubmitted||!isPickupFormSubmitted||!isExtraFormSubmitted){return;}// Break the process when one of the forms has validation errors from the constraints
if(!billingFormState.valid||!shippingFormState.valid||!pickupFormState.valid||!extraFormState.valid){setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsPickupFormSubmitted(false);setIsExtraFormSubmitted(false);}/** Async wrapper for submit registration */var fn=/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var response,_ref4,errors;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:setIsLocked(true);_context2.prev=1;_context2.next=4;return submitGuestRegistration(_extends({billingFormData:billingFormState.values},isShippingFormVisible?{shippingFormData:shippingFormState.values}:{},{},isPickupContactSelectionEnabled?{pickupFormData:pickupFormState.values}:{},{extraFormData:extraFormState.values,processShipping:isShippingAddressSelectionEnabled}));case 4:response=_context2.sent;_context2.next=11;break;case 7:_context2.prev=7;_context2.t0=_context2["catch"](1);setIsLocked(false);return _context2.abrupt("return");case 11:_ref4=response||{},errors=_ref4.errors;if(errors){_context2.next=17;break;}setIsLocked(false);LoadingProvider.setLoading(GUEST_CHECKOUT_PAYMENT_PATTERN);if(guestRegistrationEditMode){historyPop();}else{historyPush({pathname:GUEST_CHECKOUT_PAYMENT_PATTERN});}return _context2.abrupt("return");case 17:// Updated the request validation errors
setBillingFormRequestErrors((errors===null||errors===void 0?void 0:errors.billingFormData)||null);setShippingFormRequestErrors((errors===null||errors===void 0?void 0:errors.shippingFormData)||null);setPickupFormRequestErrors((errors===null||errors===void 0?void 0:errors.pickupFormData)||null);setExtraFormRequestErrors((errors===null||errors===void 0?void 0:errors.extraFormData)||null);// Release forms for additional submits
setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsPickupFormSubmitted(false);setIsExtraFormSubmitted(false);setIsLocked(false);case 26:case"end":return _context2.stop();}},_callee2,null,[[1,7]]);}));return function fn(){return _ref3.apply(this,arguments);};}();fn();/* eslint-disable react-hooks/exhaustive-deps */},[isBillingFormSubmitted,isShippingFormSubmitted,isPickupFormSubmitted,isExtraFormSubmitted]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){billingFormState.scrollToError();},[billingFormRequestErrors,shippingFormRequestErrors,pickupFormRequestErrors,billingFormState.scrollToError]);/* eslint-enable react-hooks/exhaustive-deps */useEffect(function(){if(isLocked){LoadingProvider.setLoading(GUEST_CHECKOUT_PATTERN);return;}LoadingProvider.unsetLoading(GUEST_CHECKOUT_PATTERN);},[isLocked]);useEffect(function(){var timer=setTimeout(function(){if(!guestRegistrationEditMode){return;}var scrollToElement;if(guestRegistrationEditMode===ADDRESS_TYPE_SHIPPING){if(isShippingFormVisible){scrollToElement=ELEMENT_ID_SHIPPING_CONTACT;}else{scrollToElement=ELEMENT_ID_SHIPPING_CONTACT_TOGGLE;}}else if(guestRegistrationEditMode===ADDRESS_TYPE_PICKUP){scrollToElement=ELEMENT_ID_PICKUP_CONTACT;}if(scrollToElement){scrollTo("#".concat(scrollToElement));}},500);return function(){return clearTimeout(timer);};/* eslint-disable react-hooks/exhaustive-deps */},[]);/* eslint-enable react-hooks/exhaustive-deps */var value=useMemo(function(){return{isShippingFormEnabled:isShippingFormEnabled,isShippingFormVisible:isShippingFormVisible,setIsShippingFormVisible:setIsShippingFormVisible,orderReserveOnly:orderReserveOnly,orderNeedsPayment:orderNeedsPayment,guestRegistrationEditMode:guestRegistrationEditMode,defaultBillingFormState:defaultBillingFormState,updateBillingForm:billingFormState.setValues,defaultShippingFormState:defaultShippingFormState,updateShippingForm:shippingFormState.setValues,defaultPickupFormState:defaultPickupFormState,updatePickupForm:pickupFormState.setValues,defaultExtraFormState:defaultExtraFormState,updateExtraForm:extraFormState.setValues,billingFormValidationErrors:convertValidationErrors(billingFormState.validationErrors||billingFormRequestErrors||{}),shippingFormValidationErrors:convertValidationErrors(shippingFormState.validationErrors||shippingFormRequestErrors||{}),pickupFormValidationErrors:convertValidationErrors(pickupFormState.validationErrors||pickupFormRequestErrors||{}),extraFormValidationErrors:convertValidationErrors(extraFormState.validationErrors||extraFormRequestErrors||{}),isShippingAddressSelectionEnabled:isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled:isPickupContactSelectionEnabled,customerAttributes:customerAttributes,numberOfAddressLines:numberOfAddressLines,userLocation:userLocation,supportedCountries:shopSettings.supportedCountries,countrySortOrder:shopSettings.countrySortOrder,isLocked:isLocked,handleSubmit:handleSubmit,/**
* Handling of registrationMode "simple" is not implemented for checkout. But since
* the guest registration is actually an order update and not a real registration, we
* hardcode the registration mode here, since the provider value will be used inside
* the shared form components.
*/registrationMode:SHOP_SETTING_REGISTRATION_MODE_EXTENDED,isBillingAddressSelectionEnabled:true};},[isShippingFormEnabled,isShippingFormVisible,defaultBillingFormState,billingFormState.setValues,billingFormState.validationErrors,defaultShippingFormState,shippingFormState.setValues,shippingFormState.validationErrors,defaultExtraFormState,extraFormState.setValues,extraFormState.validationErrors,extraFormRequestErrors,defaultPickupFormState,pickupFormState.setValues,pickupFormState.validationErrors,billingFormRequestErrors,shippingFormRequestErrors,pickupFormRequestErrors,orderReserveOnly,orderNeedsPayment,guestRegistrationEditMode,isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled,customerAttributes,numberOfAddressLines,userLocation,shopSettings.supportedCountries,shopSettings.countrySortOrder,isLocked,handleSubmit]);if(!isDataReady||!isInitialized){return null;}return React.createElement(Context.Provider,{value:value},children);};GuestRegistrationProvider.defaultProps={children:null,customer:null,formContainerRef:null,billingAddress:null,shippingAddress:null,pickupAddress:null,billingPickupEquals:true,billingShippingEquals:true,cartHasDirectShipItems:false,orderReserveOnly:false,orderNeedsPayment:false,numberOfAddressLines:null,isShippingAddressSelectionEnabled:false,isPickupContactSelectionEnabled:false};export default connect(GuestRegistrationProvider);