@shopgate/engage
Version:
Shopgate's ENGAGE library.
27 lines • 17 kB
JavaScript
import _regeneratorRuntime from"@babel/runtime/regenerator";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 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);});};}import{getProductsResult,productIsReady$,productsReceived$,productsReceivedCached$,RECEIVE_PRODUCTS_CACHED,variantDidChange$}from'@shopgate/engage/product';import{ToastProvider,appDidStart$,routeWillEnter$,UIEvents,getCurrentRoute,hex2bin,getThemeSettings,getCurrentSearchQuery,i18n,appWillInit$,appInitialization}from'@shopgate/engage/core';import{cartReceived$,fetchCart,cartDidEnter$,getCartItems}from'@shopgate/engage/cart';import{userDidLogin$}from'@shopgate/engage/user';import{receiveFavoritesWhileVisible$}from'@shopgate/pwa-common-commerce/favorites/streams';import{getFavoritesProductsIds,isFetching}from'@shopgate/pwa-common-commerce/favorites/selectors';import{categoryDidBackEnter$}from'@shopgate/pwa-common-commerce/category/streams';import{searchDidBackEntered$}from'@shopgate/pwa-common-commerce/search/streams';import{hasNewServices}from'@shopgate/engage/core/helpers';import{cookieConsentInitialized$}from'@shopgate/engage/tracking/streams';import{getUserSearch,getStoreFinderSearch,getPreferredLocation,getIsPending,getProductAlternativeLocationParams,getProductAlternativeLocations,makeGetLocation}from"./selectors";import{fetchDefaultLocation,fetchLocations,fetchProductLocations,sendDefaultLocationCode,setPending,setUserGeolocation}from"./actions";import{setShowInventoryInLists,showInventoryInLists}from"./helpers";import fetchInventories from"./actions/fetchInventories";import{EVENT_SET_OPEN}from"./providers/FulfillmentProvider";import fetchProductInventories from"./actions/fetchProductInventories";import{submitReservationSuccess$,userSearchChanged$,storeFinderWillEnter$,preferredLocationDidUpdate$,preferredLocationDidUpdateOnPDP$,provideAlternativeLocation$,preferredLocationDidUpdateGlobalOnWishlist$,storeDetailPageWillEnter$}from"./locations.streams";import selectLocation from"./action-creators/selectLocation";import{NEARBY_LOCATIONS_RADIUS,SET_STORE_FINDER_SEARCH_RADIUS,NEARBY_LOCATIONS_LIMIT}from"./constants";import selectGlobalLocation from"./action-creators/selectGlobalLocation";var initialLocationsResolve;var initialLocationsReject;var initialLocationsPromise=new Promise(function(resolve,reject){initialLocationsResolve=resolve;initialLocationsReject=reject;});/**
* Sets a location once the location has been validated.
* @param {string} locationCode Location code
* @param {Function} dispatch Redux dispatch function
* @returns {Promise}
*/var setLocationOnceAvailable=/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(locationCode,dispatch){var _ref3,initialLocations;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.prev=0;_context.next=3;return initialLocationsPromise;case 3:_ref3=_context.sent;initialLocations=_ref3.locations;if(initialLocations.some(function(l){return l.code===locationCode;})){_context.next=7;break;}return _context.abrupt("return");case 7:dispatch(selectLocation({code:locationCode}));requestAnimationFrame(function(){dispatch(setPending(false));});_context.next=13;break;case 11:_context.prev=11;_context.t0=_context["catch"](0);case 13:case"end":return _context.stop();}},_callee,null,[[0,11]]);}));return function setLocationOnceAvailable(_x,_x2){return _ref.apply(this,arguments);};}();/**
* Locations subscriptions.
* @param {Function} subscribe The subscribe function.
*/function locationsSubscriber(subscribe){subscribe(appWillInit$,function(){appInitialization.set('location',/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4){var dispatch;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:dispatch=_ref4.dispatch;if(!hasNewServices()){_context2.next=4;break;}_context2.next=4;return dispatch(fetchDefaultLocation());case 4:case"end":return _context2.stop();}},_callee2);}));return function(_x3){return _ref5.apply(this,arguments);};}());});subscribe(preferredLocationDidUpdate$,function(_ref6){var dispatch=_ref6.dispatch,getState=_ref6.getState,action=_ref6.action,events=_ref6.events;var preferredLocation=getPreferredLocation(getState());if(preferredLocation){dispatch(sendDefaultLocationCode(preferredLocation.code));}var _action$location=action.location,location=_action$location===void 0?{}:_action$location,showToast=action.showToast;if(showToast){events.emit(ToastProvider.ADD,{id:'location.changed',message:i18n.text('location.preferredLocationChanged',{storeName:location===null||location===void 0?void 0:location.name})});}});subscribe(cookieConsentInitialized$,/*#__PURE__*/function(){var _ref8=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref7){var dispatch,getState,userSearch,_ref10,locations,preferredLocation,code,hasLocation,_ref12,preferredLocationDefault,locationToPreselect;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:dispatch=_ref7.dispatch,getState=_ref7.getState;if(hasNewServices()){_context3.next=3;break;}return _context3.abrupt("return");case 3:// Fetch merchants locations.
userSearch=getUserSearch(getState());_context3.prev=4;_context3.next=7;return dispatch(fetchLocations(userSearch));case 7:_ref10=_context3.sent;locations=_ref10.locations;preferredLocation=getPreferredLocation(getState());if(!preferredLocation){_context3.next=16;break;}code=preferredLocation.code;// Check if the preferred location is included within the fetched locations
hasLocation=!!locations.find(function(location){return location.code===code;});if(hasLocation){_context3.next=16;break;}_context3.next=16;return dispatch(fetchLocations({codes:[code]}));case 16:// Preset preferredLocation if configured
_ref12=getThemeSettings('@shopgate/engage/locations')||{},preferredLocationDefault=_ref12.preferredLocationDefault;if(preferredLocationDefault){// check if there is already a preferredLocation for the user, if not set one
if(!preferredLocation){locationToPreselect=locations.find(function(l){return l.code===preferredLocationDefault;});if(locationToPreselect){dispatch(selectLocation({code:preferredLocationDefault}));}}}initialLocationsResolve(locations);_context3.next=24;break;case 21:_context3.prev=21;_context3.t0=_context3["catch"](4);initialLocationsReject(_context3.t0);case 24:UIEvents.addListener(EVENT_SET_OPEN,function(){var route=getCurrentRoute(getState());if(!route.params.productId&&!route.state.productId){return;}var productId=route.state.productId||hex2bin(route.params.productId);if(productId){dispatch(fetchProductLocations(productId,getUserSearch(getState())));}});case 25:case"end":return _context3.stop();}},_callee3,null,[[4,21]]);}));return function(_x4){return _ref8.apply(this,arguments);};}());subscribe(userSearchChanged$,/*#__PURE__*/function(){var _ref14=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_ref13){var dispatch,getState,action,productId,isStoreFinder,silent,state,userSearch,storeFinderSearch;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:dispatch=_ref13.dispatch,getState=_ref13.getState,action=_ref13.action;productId=action.productId,isStoreFinder=action.isStoreFinder,silent=action.silent;if(!(silent===true)){_context4.next=4;break;}return _context4.abrupt("return");case 4:state=getState();userSearch=getUserSearch(state);if(!(isStoreFinder||action.type===SET_STORE_FINDER_SEARCH_RADIUS)){_context4.next=12;break;}storeFinderSearch=getStoreFinderSearch(state);_context4.next=10;return dispatch(fetchLocations(_extends({},userSearch,{},storeFinderSearch,{enableInLocationFinder:true})));case 10:_context4.next=19;break;case 12:if(productId){_context4.next=17;break;}_context4.next=15;return dispatch(fetchLocations(userSearch));case 15:_context4.next=19;break;case 17:_context4.next=19;return dispatch(fetchProductLocations(productId,userSearch));case 19:case"end":return _context4.stop();}},_callee4);}));return function(_x5){return _ref14.apply(this,arguments);};}());var productInventoryNeedsUpdate$=productIsReady$.merge(variantDidChange$).merge(preferredLocationDidUpdateOnPDP$).debounceTime(200);subscribe(productInventoryNeedsUpdate$,function(_ref15){var action=_ref15.action,dispatch=_ref15.dispatch,getState=_ref15.getState;var productData=action.productData;// Skip if no fulfillment methods are set.
if(!productData||!productData.fulfillmentMethods||productData.fulfillmentMethods.length===0){return;}var state=getState();var preferredLocation=getPreferredLocation(state);if(!preferredLocation){return;}// Fetch inventories for this specific product.
dispatch(fetchProductInventories(action.productData.id,{locationCodes:[preferredLocation.code]}));});// Core config and cart subscriptions
var fetchCart$=cartDidEnter$.switchMap(function(){return submitReservationSuccess$.first();}).delay(500);subscribe(fetchCart$,function(_ref16){var dispatch=_ref16.dispatch;dispatch(fetchCart());});subscribe(storeFinderWillEnter$,/*#__PURE__*/function(){var _ref18=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(_ref17){var dispatch,getState,state,userSearch,storeFinderSearch;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:dispatch=_ref17.dispatch,getState=_ref17.getState;state=getState();// Fetch merchants locations.
userSearch=getUserSearch(state);storeFinderSearch=getStoreFinderSearch(state);_context5.next=6;return dispatch(fetchLocations(_extends({},userSearch,{},storeFinderSearch,{enableInLocationFinder:true})));case 6:case"end":return _context5.stop();}},_callee5);}));return function(_x6){return _ref18.apply(this,arguments);};}());/**
* Makes sure that the active location is switched after logging in
* to a location that is also available in the cart.
* Avoids having a selected location that differs from the cart
*/var afterCartMerge$=userDidLogin$.mergeMap(function(){return cartReceived$.first();});subscribe(afterCartMerge$,/*#__PURE__*/function(){var _ref20=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(_ref19){var _cartItems$,_cartItems$$fulfillme,_cartItems$$fulfillme2;var dispatch,getState,state,cartItems,preferredLocation,activeCartLocation,firstLocationCode;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:dispatch=_ref19.dispatch,getState=_ref19.getState;state=getState();cartItems=getCartItems(state);preferredLocation=getPreferredLocation(state,{});if(cartItems===null||cartItems===void 0?void 0:cartItems.length){_context6.next=6;break;}return _context6.abrupt("return");case 6:activeCartLocation=cartItems.find(function(item){var _item$fulfillment,_item$fulfillment$loc;return((_item$fulfillment=item.fulfillment)===null||_item$fulfillment===void 0?void 0:(_item$fulfillment$loc=_item$fulfillment.location)===null||_item$fulfillment$loc===void 0?void 0:_item$fulfillment$loc.code)===(preferredLocation===null||preferredLocation===void 0?void 0:preferredLocation.code);});if(!activeCartLocation){_context6.next=9;break;}return _context6.abrupt("return");case 9:firstLocationCode=(_cartItems$=cartItems[0])===null||_cartItems$===void 0?void 0:(_cartItems$$fulfillme=_cartItems$.fulfillment)===null||_cartItems$$fulfillme===void 0?void 0:(_cartItems$$fulfillme2=_cartItems$$fulfillme.location)===null||_cartItems$$fulfillme2===void 0?void 0:_cartItems$$fulfillme2.code;if(firstLocationCode){_context6.next=12;break;}return _context6.abrupt("return");case 12:dispatch(selectLocation({code:firstLocationCode}));dispatch(selectGlobalLocation({code:firstLocationCode}));case 14:case"end":return _context6.stop();}},_callee6);}));return function(_x7){return _ref20.apply(this,arguments);};}());/**
* Handles an added store url parameter that will set the default store location
*/subscribe(routeWillEnter$,function(_ref21){var action=_ref21.action,dispatch=_ref21.dispatch,getState=_ref21.getState;var locationCode=action.route.query.store;if(!locationCode){if(!getIsPending(getState())){dispatch(setPending(false));}return;}setLocationOnceAvailable(locationCode,dispatch);});var alternative$=productInventoryNeedsUpdate$.switchMap(function(){return provideAlternativeLocation$.first();});/**
* Provide alternative location on PDP when preferred location is out of stock
*/subscribe(alternative$,/*#__PURE__*/function(){var _ref23=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(_ref22){var action,dispatch,getState,state,alternativeLocations,productId,params,alternativeParams,fetchParams;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1)switch(_context7.prev=_context7.next){case 0:action=_ref22.action,dispatch=_ref22.dispatch,getState=_ref22.getState;_context7.next=3;return dispatch(setUserGeolocation({silent:true}));case 3:// Get new state with geolocation
state=getState();alternativeLocations=getProductAlternativeLocations(state,action);if(!alternativeLocations){_context7.next=7;break;}return _context7.abrupt("return");case 7:productId=action.productId,params=action.params;alternativeParams=getProductAlternativeLocationParams(state);fetchParams=_extends({},alternativeParams,{},params);if(fetchParams.geolocation||fetchParams.postalCode){dispatch(fetchProductLocations(productId,fetchParams));}case 11:case"end":return _context7.stop();}},_callee7);}));return function(_x8){return _ref23.apply(this,arguments);};}());subscribe(categoryDidBackEnter$.merge(searchDidBackEntered$),function(_ref24){var _getProductsResult;var action=_ref24.action,dispatch=_ref24.dispatch,getState=_ref24.getState;var state=getState();if(!showInventoryInLists(state)){return;}var categoryId=action.route.params.categoryId;var query=getCurrentSearchQuery(state);var products=(_getProductsResult=getProductsResult(state,{categoryId:hex2bin(categoryId),searchPhrase:query}))===null||_getProductsResult===void 0?void 0:_getProductsResult.products;if(!products||!products.length){return;}var productCodes=products.map(function(_ref25){var id=_ref25.id;return id;});dispatch(fetchInventories(productCodes));});subscribe(productsReceived$.merge(productsReceivedCached$),function(_ref26){var action=_ref26.action,dispatch=_ref26.dispatch,getState=_ref26.getState;if(!showInventoryInLists(getState())){return;}if(!action.products||!action.products.length||(action===null||action===void 0?void 0:action.fetchInventory)===false){return;}var productCodes=action.type!==RECEIVE_PRODUCTS_CACHED?action.products.map(function(_ref27){var id=_ref27.id;return id;}):action.products;dispatch(fetchInventories(productCodes));});subscribe(receiveFavoritesWhileVisible$.merge(preferredLocationDidUpdateGlobalOnWishlist$),function(_ref28){var dispatch=_ref28.dispatch,getState=_ref28.getState;var state=getState();if(!showInventoryInLists(state)||isFetching(getState())){return;}var productIds=getFavoritesProductsIds(state);if(!productIds||!productIds.length){return;}dispatch(fetchInventories(productIds));});subscribe(appDidStart$,function(_ref29){var getState=_ref29.getState;// enable inventory in product lists for some users
setShowInventoryInLists(getState());});subscribe(storeDetailPageWillEnter$,/*#__PURE__*/function(){var _ref31=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(_ref30){var dispatch,getState,route,getLocation,location;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1)switch(_context8.prev=_context8.next){case 0:dispatch=_ref30.dispatch,getState=_ref30.getState;route=getCurrentRoute(getState());getLocation=makeGetLocation(function(){return route.params.code;});location=getLocation(getState());_context8.next=6;return dispatch(fetchLocations({geolocation:{longitude:location.longitude,latitude:location.latitude},limit:NEARBY_LOCATIONS_LIMIT,radius:NEARBY_LOCATIONS_RADIUS}));case 6:case"end":return _context8.stop();}},_callee8);}));return function(_x9){return _ref31.apply(this,arguments);};}());}export default locationsSubscriber;